@w0nna_dev/lina-widget 1.0.5 → 1.0.8

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.
@@ -24,11 +24,11 @@
24
24
  * @license
25
25
  * Copyright 2017 Google LLC
26
26
  * SPDX-License-Identifier: BSD-3-Clause
27
- */const Hg={attribute:!0,type:String,converter:va,reflect:!1,hasChanged:Qo},Wg=(i=Hg,e,t)=>{const{kind:n,metadata:s}=t;let r=globalThis.litPropertyMetadata.get(s);if(r===void 0&&globalThis.litPropertyMetadata.set(s,r=new Map),n==="setter"&&((i=Object.create(i)).wrapped=!0),r.set(t.name,i),n==="accessor"){const{name:o}=t;return{set(a){const c=e.get.call(this);e.set.call(this,a),this.requestUpdate(o,c,i,!0,a)},init(a){return a!==void 0&&this.C(o,void 0,i,a),a}}}if(n==="setter"){const{name:o}=t;return function(a){const c=this[o];e.call(this,a),this.requestUpdate(o,c,i,!0,a)}}throw Error("Unsupported decorator location: "+n)};function pe(i){return(e,t)=>typeof t=="object"?Wg(i,e,t):((n,s,r)=>{const o=s.hasOwnProperty(r);return s.constructor.createProperty(r,n),o?Object.getOwnPropertyDescriptor(s,r):void 0})(i,e,t)}/**
27
+ */const Hg={attribute:!0,type:String,converter:va,reflect:!1,hasChanged:Qo},Wg=(i=Hg,e,t)=>{const{kind:n,metadata:s}=t;let r=globalThis.litPropertyMetadata.get(s);if(r===void 0&&globalThis.litPropertyMetadata.set(s,r=new Map),n==="setter"&&((i=Object.create(i)).wrapped=!0),r.set(t.name,i),n==="accessor"){const{name:o}=t;return{set(a){const c=e.get.call(this);e.set.call(this,a),this.requestUpdate(o,c,i,!0,a)},init(a){return a!==void 0&&this.C(o,void 0,i,a),a}}}if(n==="setter"){const{name:o}=t;return function(a){const c=this[o];e.call(this,a),this.requestUpdate(o,c,i,!0,a)}}throw Error("Unsupported decorator location: "+n)};function ce(i){return(e,t)=>typeof t=="object"?Wg(i,e,t):((n,s,r)=>{const o=s.hasOwnProperty(r);return s.constructor.createProperty(r,n),o?Object.getOwnPropertyDescriptor(s,r):void 0})(i,e,t)}/**
28
28
  * @license
29
29
  * Copyright 2017 Google LLC
30
30
  * SPDX-License-Identifier: BSD-3-Clause
31
- */function Fi(i){return pe({...i,state:!0,attribute:!1})}/**
31
+ */function Fi(i){return ce({...i,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 xa=()=>new Qg;let Qg=class{};const sc=new WeakMap,Ta=$g(class extends Zg{render(i){return Ft}update(i,[e]){var n;const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=(n=i.options)==null?void 0:n.host,this.rt(this.ct=i.element)),Ft}rt(i){if(this.isConnected||(i=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=sc.get(e);t===void 0&&(t=new WeakMap,sc.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,i),i!==void 0&&this.G.call(this.ht,i)}else this.G.value=i}get lt(){var i,e;return typeof this.G=="function"?(i=sc.get(this.ht??globalThis))==null?void 0:i.get(this.G):(e=this.G)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function ev(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var tv=Object.defineProperty,nv=(i,e,t)=>e in i?tv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Nu=(i,e,t)=>nv(i,typeof e!="symbol"?e+"":e,t);class on{constructor(){Nu(this,"_locking"),Nu(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}}function Pt(i,e){if(!i)throw new Error(e)}const iv=34028234663852886e22,sv=-34028234663852886e22,rv=4294967295,av=2147483647,ov=-2147483648;function Ca(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>av||i<ov)throw new Error("invalid int 32: "+i)}function rc(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>rv||i<0)throw new Error("invalid uint 32: "+i)}function Ou(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>iv||i<sv))throw new Error("invalid float 32: "+i)}const Uu=Symbol("@bufbuild/protobuf/enum-type");function cv(i){const e=i[Uu];return Pt(e,"missing enum type on enum object"),e}function Fu(i,e,t,n){i[Uu]=Bu(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function Bu(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const o of e){const a=zu(o);r.push(a),n[o.name]=a,s[o.no]=a}return{typeName:i,values:r,findName(o){return n[o]},findNumber(o){return s[o]}}}function lv(i,e,t){const n={};for(const s of e){const r=zu(s);n[r.localName]=r.no,n[r.no]=r.localName}return Fu(n,i,e),n}function zu(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class ac{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),s=n.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),s=n.runtime.json,r=s.makeReadOptions(t);return s.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,s=n.makeWriteOptions(e),r=s.writerFactory();return n.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,s=n.makeWriteOptions(e);return n.writeMessage(this,s)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function dv(i,e,t,n){var s;const r=(s=n==null?void 0:n.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(a){i.util.initFields(this),i.util.initPartial(a,this)}}[r];return Object.setPrototypeOf(o.prototype,new ac),Object.assign(o,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return i.util.equals(o,a,c)}}),o}function uv(){let i=0,e=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(i|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function oc(i,e,t){for(let r=0;r<28;r=r+7){const o=i>>>r,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const n=i>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?n|128:n)&255),!!s){for(let r=3;r<31;r=r+7){const o=e>>>r,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const Ea=4294967296;function Vu(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(o,a){const c=Number(i.slice(o,a));s*=t,n=n*t+c,n>=Ea&&(s=s+(n/Ea|0),n=n%Ea)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?Hu(n,s):cc(n,s)}function hv(i,e){let t=cc(i,e);const n=t.hi&2147483648;n&&(t=Hu(t.lo,t.hi));const s=Gu(t.lo,t.hi);return n?"-"+s:s}function Gu(i,e){if({lo:i,hi:e}=fv(i,e),e<=2097151)return String(Ea*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+n*6777216+s*6710656,o=n+s*8147497,a=s*2;const c=1e7;return r>=c&&(o+=Math.floor(r/c),r%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+Wu(o)+Wu(r)}function fv(i,e){return{lo:i>>>0,hi:e>>>0}}function cc(i,e){return{lo:i|0,hi:e|0}}function Hu(i,e){return e=~e,i?i=~i+1:e+=1,cc(i,e)}const Wu=i=>{const e=String(i);return"0000000".slice(e.length)+e};function qu(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function pv(){let i=this.buf[this.pos++],e=i&127;if((i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,(i&128)==0)return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;(i&128)!==0&&t<10;t++)i=this.buf[this.pos++];if((i&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function mv(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>r||l<s)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>a||l<o)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return i.setBigInt64(0,this.parse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(c){return i.setBigInt64(0,this.uParse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigInt64(0,!0)},uDec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigUint64(0,!0)}}}const t=s=>Pt(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>Pt(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),n(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Vu(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),Vu(s)},dec(s,r){return hv(s,r)},uDec(s,r){return Gu(s,r)}}}const wt=mv();var J;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(J||(J={}));var Bi;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(Bi||(Bi={}));function zi(i,e,t){if(e===t)return!0;if(i==J.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case J.UINT64:case J.FIXED64:case J.INT64:case J.SFIXED64:case J.SINT64:return e==t}return!1}function Ls(i,e){switch(i){case J.BOOL:return!1;case J.UINT64:case J.FIXED64:case J.INT64:case J.SFIXED64:case J.SINT64:return e==0?wt.zero:"0";case J.DOUBLE:case J.FLOAT:return 0;case J.BYTES:return new Uint8Array(0);case J.STRING:return"";default:return 0}}function ju(i,e){switch(i){case J.BOOL:return e===!1;case J.STRING:return e==="";case J.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var Ot;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(Ot||(Ot={}));class gv{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),n=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],n),n+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(rc(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ca(e),qu(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Ou(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){rc(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ca(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ca(e),e=(e<<1^e>>31)>>>0,qu(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=wt.enc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=wt.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=wt.enc(e);return oc(t.lo,t.hi,this.buf),this}sint64(e){let t=wt.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return oc(s,r,this.buf),this}uint64(e){let t=wt.uEnc(e);return oc(t.lo,t.hi,this.buf),this}}class vv{constructor(e,t){this.varint64=uv,this.uint32=pv,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case Ot.Varint:for(;this.buf[this.pos++]&128;);break;case Ot.Bit64:this.pos+=4;case Ot.Bit32:this.pos+=4;break;case Ot.LengthDelimited:let s=this.uint32();this.pos+=s;break;case Ot.StartGroup:for(;;){const[r,o]=this.tag();if(o===Ot.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(o,r)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return wt.dec(...this.varint64())}uint64(){return wt.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,wt.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return wt.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return wt.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function yv(i,e,t,n){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof n=="function"?n():n;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=i.util.newFieldList([r]).list()[0]}return s},runtime:i}}function $u(i){const e=i.field.localName,t=Object.create(null);return t[e]=bv(i),[t,()=>t[e]]}function bv(i){const e=i.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return Ls(e.T,e.L);case"message":const t=e.T,n=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}function _v(i,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=i.length-1;t>=0;--t)if(i[t].no==e.no)return[i[t]];return[]}return i.filter(t=>t.no===e.no)}let fi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Ma=[];for(let i=0;i<fi.length;i++)Ma[fi[i].charCodeAt(0)]=i;Ma[45]=fi.indexOf("+"),Ma[95]=fi.indexOf("/");const Xu={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,s=0,r,o=0;for(let a=0;a<i.length;a++){if(r=Ma[i.charCodeAt(a)],r===void 0)switch(i[a]){case"=":s=0;case`
48
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:t[n++]=o<<2|(r&48)>>4,o=r,s=2;break;case 2:t[n++]=(o&15)<<4|(r&60)>>2,o=r,s=3;break;case 3:t[n++]=(o&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,s=0;for(let r=0;r<i.length;r++)switch(n=i[r],t){case 0:e+=fi[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=fi[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=fi[s|n>>6],e+=fi[n&63],t=0;break}return t&&(e+=fi[s],e+="=",t==1&&(e+="=")),e}};function Sv(i,e,t){Yu(e,i);const n=e.runtime.bin.makeReadOptions(t),s=_v(i.getType().runtime.bin.listUnknownFields(i),e.field),[r,o]=$u(e);for(const a of s)e.runtime.bin.readField(r,n.readerFactory(a.data),e.field,a.wireType,n);return o()}function xv(i,e,t,n){Yu(e,i);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(Ku(i,e)){const l=i.getType().runtime.bin.listUnknownFields(i).filter(d=>d.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(const d of l)i.getType().runtime.bin.onUnknownField(i,d.no,d.wireType,d.data)}const o=r.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[l,d]=c.tag(),u=c.skip(d,l);i.getType().runtime.bin.onUnknownField(i,l,d,u)}}function Ku(i,e){const t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function Yu(i,e){Pt(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function Ju(i,e){const t=i.localName;if(i.repeated)return e[t].length>0;if(i.oneof)return e[i.oneof.localName].case===t;switch(i.kind){case"enum":case"scalar":return i.opt||i.req?e[t]!==void 0:i.kind=="enum"?e[t]!==i.T.values[0].no:!ju(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Zu(i,e){const t=i.localName,n=!i.opt&&!i.req;if(i.repeated)e[t]=[];else if(i.oneof)e[i.oneof.localName]={case:void 0};else switch(i.kind){case"map":e[t]={};break;case"enum":e[t]=n?i.T.values[0].no:void 0;break;case"scalar":e[t]=n?Ls(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function pi(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(ac.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;const t=i.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Qu(i,e){return pi(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}J.DOUBLE,J.FLOAT,J.INT64,J.UINT64,J.INT32,J.UINT32,J.BOOL,J.STRING,J.BYTES;const eh={ignoreUnknownFields:!1},th={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Tv(i){return i?Object.assign(Object.assign({},eh),i):eh}function Cv(i){return i?Object.assign(Object.assign({},th),i):th}const wa=Symbol(),Aa=Symbol();function Ev(){return{makeReadOptions:Tv,makeWriteOptions:Cv,readMessage(i,e,t,n){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat(Yn(e)));n=n??new i;const s=new Map,r=t.typeRegistry;for(const[o,a]of Object.entries(e)){const c=i.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const l=s.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(o,'"'));s.set(c.oneof,o)}nh(n,a,c,t,i)}else{let l=!1;if(r!=null&&r.findExtension&&o.startsWith("[")&&o.endsWith("]")){const d=r.findExtension(o.substring(1,o.length-1));if(d&&d.extendee.typeName==i.typeName){l=!0;const[u,h]=$u(d);nh(u,a,d.field,t,d),xv(n,d,h(),t)}}if(!l&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(i,e){const t=i.getType(),n={};let s;try{for(s of t.fields.byNumber()){if(!Ju(s,i)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!wv(s))continue}const o=s.oneof?i[s.oneof.localName].value:i[s.localName],a=ih(s,o,e);a!==void 0&&(n[e.useProtoFieldName?s.name:s.jsonName]=a)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(i)){const a=r.findExtensionFor(t.typeName,o.no);if(a&&Ku(i,a)){const c=Sv(i,a,e),l=ih(a.field,c,e);l!==void 0&&(n[a.field.jsonName]=l)}}}catch(r){const o=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=r instanceof Error?r.message:String(r);throw new Error(o+(a.length>0?": ".concat(a):""))}return n},readScalar(i,e,t){return kr(i,e,t??Bi.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||ju(i,e)))return Ra(i,e)},debug:Yn}}function Yn(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function nh(i,e,t,n,s){let r=t.localName;if(t.repeated){if(Pt(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(e)));const o=i[r];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(a)));switch(t.kind){case"message":o.push(t.T.fromJson(a,n));break;case"enum":const c=lc(t.T,a,n.ignoreUnknownFields,!0);c!==Aa&&o.push(c);break;case"scalar":try{o.push(kr(t.T,a,t.L,!0))}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(a));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(e)));const o=i[r];for(const[a,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let l;try{l=Mv(t.K,a)}catch(d){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(e));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}switch(t.V.kind){case"message":o[l]=t.V.T.fromJson(c,n);break;case"enum":const d=lc(t.V.T,c,n.ignoreUnknownFields,!0);d!==Aa&&(o[l]=d);break;case"scalar":try{o[l]=kr(t.V.T,c,Bi.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=i[r];pi(a)?a.fromJson(e,n):(i[r]=a=o.fromJson(e,n),o.fieldWrapper&&!t.oneof&&(i[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=lc(t.T,e,n.ignoreUnknownFields,!1);switch(c){case wa:Zu(t,i);break;case Aa:break;default:i[r]=c;break}break;case"scalar":try{const l=kr(t.T,e,t.L,!1);switch(l){case wa:Zu(t,i);break;default:i[r]=l;break}}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(e));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}function Mv(i,e){if(i===J.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return kr(i,e,Bi.BIGINT,!0).toString()}function kr(i,e,t,n){if(e===null)return n?Ls(i,t):wa;switch(i){case J.DOUBLE:case J.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return i==J.FLOAT&&Ou(s),s;case J.INT32:case J.FIXED32:case J.SFIXED32:case J.SINT32:case J.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return i==J.UINT32||i==J.FIXED32?rc(r):Ca(r),r;case J.INT64:case J.SFIXED64:case J.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=wt.parse(e);return t?o.toString():o;case J.FIXED64:case J.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=wt.uParse(e);return t?a.toString():a;case J.BOOL:if(typeof e!="boolean")break;return e;case J.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case J.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Xu.dec(e)}throw new Error}function lc(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:wa;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=i.findName(e);if(s!==void 0)return s.no;if(t)return Aa;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(Yn(e)))}function wv(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function ih(i,e,t){if(i.kind=="map"){Pt(typeof e=="object"&&e!=null);const n={},s=Object.entries(e);switch(i.V.kind){case"scalar":for(const[o,a]of s)n[o.toString()]=Ra(i.V.T,a);break;case"message":for(const[o,a]of s)n[o.toString()]=a.toJson(t);break;case"enum":const r=i.V.T;for(const[o,a]of s)n[o.toString()]=dc(r,a,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?n:void 0}if(i.repeated){Pt(Array.isArray(e));const n=[];switch(i.kind){case"scalar":for(let s=0;s<e.length;s++)n.push(Ra(i.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)n.push(dc(i.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)n.push(e[s].toJson(t));break}return t.emitDefaultValues||n.length>0?n:void 0}switch(i.kind){case"scalar":return Ra(i.T,e);case"enum":return dc(i.T,e,t.enumAsInteger);case"message":return Qu(i.T,e).toJson(t)}}function dc(i,e,t){var n;if(Pt(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=i.findNumber(e);return(n=s==null?void 0:s.name)!==null&&n!==void 0?n:e}function Ra(i,e){switch(i){case J.INT32:case J.SFIXED32:case J.SINT32:case J.FIXED32:case J.UINT32:return Pt(typeof e=="number"),e;case J.FLOAT:case J.DOUBLE:return Pt(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case J.STRING:return Pt(typeof e=="string"),e;case J.BOOL:return Pt(typeof e=="boolean"),e;case J.UINT64:case J.FIXED64:case J.INT64:case J.SFIXED64:case J.SINT64:return Pt(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case J.BYTES:return Pt(e instanceof Uint8Array),Xu.enc(e)}}const Ns=Symbol("@bufbuild/protobuf/unknown-fields"),sh={readUnknownFields:!0,readerFactory:i=>new vv(i)},rh={writeUnknownFields:!0,writerFactory:()=>new gv};function Av(i){return i?Object.assign(Object.assign({},sh),i):sh}function Rv(i){return i?Object.assign(Object.assign({},rh),i):rh}function Pv(){return{makeReadOptions:Av,makeWriteOptions:Rv,listUnknownFields(i){var e;return(e=i[Ns])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Ns]},writeUnknownFields(i,e){const n=i[Ns];if(n)for(const s of n)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(i,e,t,n){const s=i;Array.isArray(s[Ns])||(s[Ns]=[]),s[Ns].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,s){const r=i.getType(),o=s?e.len:e.pos+t;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!(s===!0&&c==Ot.EndGroup));){const l=r.fields.find(a);if(!l){const d=e.skip(c,a);n.readUnknownFields&&this.onUnknownField(i,a,c,d);continue}ah(i,e,l,c,n)}if(s&&(c!=Ot.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:ah,writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){if(!Ju(s,i)){if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?i[s.oneof.localName].value:i[s.localName];oh(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&oh(i,e,t,n)}}}function ah(i,e,t,n,s){let{repeated:r,localName:o}=t;switch(t.oneof&&(i=i[t.oneof.localName],i.case!=o&&delete i.value,i.case=o,o="value"),t.kind){case"scalar":case"enum":const a=t.kind=="enum"?J.INT32:t.T;let c=ka;if(t.kind=="scalar"&&t.L>0&&(c=Iv),r){let h=i[o];if(n==Ot.LengthDelimited&&a!=J.STRING&&a!=J.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,a))}else h.push(c(e,a))}else i[o]=c(e,a);break;case"message":const l=t.T;r?i[o].push(Pa(e,new l,s,t)):pi(i[o])?Pa(e,i[o],s,t):(i[o]=Pa(e,new l,s,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(i[o]=l.fieldWrapper.unwrapField(i[o])));break;case"map":let[d,u]=kv(t,e,s);i[o][d]=u;break}}function Pa(i,e,t,n){const s=e.getType().runtime.bin,r=n==null?void 0:n.delimited;return s.readMessage(e,i,r?n.no:i.uint32(),t,r),e}function kv(i,e,t){const n=e.uint32(),s=e.pos+n;let r,o;for(;e.pos<s;){const[a]=e.tag();switch(a){case 1:r=ka(e,i.K);break;case 2:switch(i.V.kind){case"scalar":o=ka(e,i.V.T);break;case"enum":o=e.int32();break;case"message":o=Pa(e,new i.V.T,t,void 0);break}break}}if(r===void 0&&(r=Ls(i.K,Bi.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),o===void 0)switch(i.V.kind){case"scalar":o=Ls(i.V.T,Bi.BIGINT);break;case"enum":o=i.V.T.values[0].no;break;case"message":o=new i.V.T;break}return[r,o]}function Iv(i,e){const t=ka(i,e);return typeof t=="bigint"?t.toString():t}function ka(i,e){switch(e){case J.STRING:return i.string();case J.BOOL:return i.bool();case J.DOUBLE:return i.double();case J.FLOAT:return i.float();case J.INT32:return i.int32();case J.INT64:return i.int64();case J.UINT64:return i.uint64();case J.FIXED64:return i.fixed64();case J.BYTES:return i.bytes();case J.FIXED32:return i.fixed32();case J.SFIXED32:return i.sfixed32();case J.SFIXED64:return i.sfixed64();case J.SINT64:return i.sint64();case J.UINT32:return i.uint32();case J.SINT32:return i.sint32()}}function oh(i,e,t,n){Pt(e!==void 0);const s=i.repeated;switch(i.kind){case"scalar":case"enum":let r=i.kind=="enum"?J.INT32:i.T;if(s)if(Pt(Array.isArray(e)),i.packed)Lv(t,r,i.no,e);else for(const o of e)Ir(t,r,i.no,o);else Ir(t,r,i.no,e);break;case"message":if(s){Pt(Array.isArray(e));for(const o of e)ch(t,n,i,o)}else ch(t,n,i,e);break;case"map":Pt(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))Dv(t,n,i,o,a);break}}function Dv(i,e,t,n,s){i.tag(t.no,Ot.LengthDelimited),i.fork();let r=n;switch(t.K){case J.INT32:case J.FIXED32:case J.UINT32:case J.SFIXED32:case J.SINT32:r=Number.parseInt(n);break;case J.BOOL:Pt(n=="true"||n=="false"),r=n=="true";break}switch(Ir(i,t.K,1,r),t.V.kind){case"scalar":Ir(i,t.V.T,2,s);break;case"enum":Ir(i,J.INT32,2,s);break;case"message":Pt(s!==void 0),i.tag(2,Ot.LengthDelimited).bytes(s.toBinary(e));break}i.join()}function ch(i,e,t,n){const s=Qu(t.T,n);t.delimited?i.tag(t.no,Ot.StartGroup).raw(s.toBinary(e)).tag(t.no,Ot.EndGroup):i.tag(t.no,Ot.LengthDelimited).bytes(s.toBinary(e))}function Ir(i,e,t,n){Pt(n!==void 0);let[s,r]=lh(e);i.tag(t,s)[r](n)}function Lv(i,e,t,n){if(!n.length)return;i.tag(t,Ot.LengthDelimited).fork();let[,s]=lh(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function lh(i){let e=Ot.Varint;switch(i){case J.BYTES:case J.STRING:e=Ot.LengthDelimited;break;case J.DOUBLE:case J.FIXED64:case J.SFIXED64:e=Ot.Bit64;break;case J.FIXED32:case J.SFIXED32:case J.FLOAT:e=Ot.Bit32;break}const t=J[i].toLowerCase();return[e,t]}function Nv(){return{setEnumType:Fu,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const s=n.localName,r=e,o=i;if(o[s]!=null)switch(n.kind){case"oneof":const a=o[s].case;if(a===void 0)continue;const c=n.findField(a);let l=o[s].value;c&&c.kind=="message"&&!pi(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===J.BYTES&&(l=Dr(l)),r[s]={case:a,value:l};break;case"scalar":case"enum":let d=o[s];n.T===J.BYTES&&(d=n.repeated?d.map(Dr):Dr(d)),r[s]=d;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===J.BYTES)for(const[f,g]of Object.entries(o[s]))r[s][f]=Dr(g);else Object.assign(r[s],o[s]);break;case"message":const h=n.V.T;for(const f of Object.keys(o[s])){let g=o[s][f];h.fieldWrapper||(g=new h(g)),r[s][f]=g}break}break;case"message":const u=n.T;if(n.repeated)r[s]=o[s].map(h=>pi(h,u)?h:new u(h));else{const h=o[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Dr(h):r[s]=h:r[s]=pi(h,u)?h:new u(h)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const s=e[n.localName],r=t[n.localName];if(n.repeated){if(s.length!==r.length)return!1;switch(n.kind){case"message":return s.every((o,a)=>n.T.equals(o,r[a]));case"scalar":return s.every((o,a)=>zi(n.T,o,r[a]));case"enum":return s.every((o,a)=>zi(J.INT32,o,r[a]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":let o=s,a=r;return n.T.fieldWrapper&&(o!==void 0&&!pi(o)&&(o=n.T.fieldWrapper.wrapField(o)),a!==void 0&&!pi(a)&&(a=n.T.fieldWrapper.wrapField(a))),n.T.equals(o,a);case"enum":return zi(J.INT32,s,r);case"scalar":return zi(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=n.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return zi(J.INT32,s.value,r.value);case"scalar":return zi(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const d=n.V.T;return l.every(h=>d.equals(s[h],r[h]));case"enum":return l.every(h=>zi(J.INT32,s[h],r[h]));case"scalar":const u=n.V.T;return l.every(h=>zi(u,s[h],r[h]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const s of e.fields.byMember()){const r=i[s.localName];let o;if(s.repeated)o=r.map(Ia);else if(s.kind=="map"){o=n[s.localName];for(const[a,c]of Object.entries(r))o[a]=Ia(c)}else s.kind=="oneof"?o=s.findField(r.case)?{case:r.case,value:Ia(r.value)}:{case:void 0}:o=Ia(r);n[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function Ia(i){if(i===void 0)return i;if(pi(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Dr(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function Ov(i,e,t){return{syntax:i,json:Ev(),bin:Pv(),util:Object.assign(Object.assign({},Nv()),{newFieldList:e,initFields:t}),makeMessageType(n,s,r){return dv(this,n,s,r)},makeEnum:lv,makeEnumType:Bu,getEnumType:cv,makeExtension(n,s,r){return yv(this,n,s,r)}}}class Uv{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function dh(i,e){const t=uh(i);return e?t:Hv(Gv(t))}function Fv(i){return dh(i,!1)}const Bv=uh;function uh(i){let e=!1;const t=[];for(let n=0;n<i.length;n++){let s=i.charAt(n);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const zv=new Set(["constructor","toString","toJSON","valueOf"]),Vv=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),hh=i=>"".concat(i,"$"),Gv=i=>Vv.has(i)?hh(i):i,Hv=i=>zv.has(i)?hh(i):i;class Wv{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Fv(e)}addField(e){Pt(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function qv(i,e){var t,n,s,r,o,a;const c=[];let l;for(const d of typeof i=="function"?i():i){const u=d;if(u.localName=dh(d.name,d.oneof!==void 0),u.jsonName=(t=d.jsonName)!==null&&t!==void 0?t:Bv(d.name),u.repeated=(n=d.repeated)!==null&&n!==void 0?n:!1,d.kind=="scalar"&&(u.L=(s=d.L)!==null&&s!==void 0?s:Bi.BIGINT),u.delimited=(r=d.delimited)!==null&&r!==void 0?r:!1,u.req=(o=d.req)!==null&&o!==void 0?o:!1,u.opt=(a=d.opt)!==null&&a!==void 0?a:!1,d.packed===void 0&&(u.packed=d.kind=="enum"||d.kind=="scalar"&&d.T!=J.BYTES&&d.T!=J.STRING),d.oneof!==void 0){const h=typeof d.oneof=="string"?d.oneof:d.oneof.name;(!l||l.name!=h)&&(l=new Wv(h)),u.oneof=l,l.addField(u)}c.push(u)}return c}const z=Ov("proto3",i=>new Uv(i,e=>qv(e)),i=>{for(const e of i.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=Ls(e.T,e.L);break}}});class mn extends ac{constructor(e){super(),this.seconds=wt.zero,this.nanos=0,z.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(z.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=wt.parse(s/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let n="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?n="."+s.substring(0,3)+"Z":s.substring(6)==="000"?n="."+s.substring(0,6)+"Z":n="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return mn.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new mn({seconds:wt.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new mn().fromBinary(e,t)}static fromJson(e,t){return new mn().fromJson(e,t)}static fromJsonString(e,t){return new mn().fromJsonString(e,t)}static equals(e,t){return z.util.equals(mn,e,t)}}mn.runtime=z,mn.typeName="google.protobuf.Timestamp",mn.fields=z.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const jv=z.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:mn},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:$v,repeated:!0},{no:5,name:"events",kind:"message",T:Kv,repeated:!0}]),$v=z.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:Xv,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Xv=z.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:mn},{no:3,name:"value",kind:"scalar",T:2}]),Kv=z.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:mn},{no:7,name:"normalized_end_timestamp",kind:"message",T:mn,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),fh=z.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Fn=z.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Bt=z.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"}]),uc=z.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Lr=z.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Nr=z.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Bn=z.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"}]),ds=z.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"}]),Yv=z.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),jt=z.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"}]),Da=z.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:La,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:wh}]),La=z.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Jv=z.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:z.getEnumType(Bt),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}]),us=z.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:z.getEnumType(Os)},{no:4,name:"tracks",kind:"message",T:Us,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:Jv},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:z.getEnumType(Or)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:z.getEnumType(Bn)},{no:18,name:"kind_details",kind:"enum",T:z.getEnumType(Zv),repeated:!0}]),Os=z.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Or=z.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"}]),Zv=z.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Ht=z.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Qv=z.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:Vi,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:z.getEnumType(ph)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Us=z.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:z.getEnumType(Fn)},{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:z.getEnumType(Bt)},{no:10,name:"layers",kind:"message",T:Vi,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:Qv,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:z.getEnumType(Ht)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:wh},{no:19,name:"audio_features",kind:"enum",T:z.getEnumType(jt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:z.getEnumType(fh)}]),Vi=z.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:z.getEnumType(uc)},{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}]),ph=z.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),cn=z.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:z.getEnumType(Ke)},{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:hc,oneof:"value"},{no:3,name:"speaker",kind:"message",T:e0,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:yh,oneof:"value"},{no:7,name:"transcription",kind:"message",T:t0,oneof:"value"},{no:8,name:"metrics",kind:"message",T:jv,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Na,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:fc,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:pc,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:mc,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Oa,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Ua,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Fa,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:mh,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Ke=z.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),mh=z.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:z.getEnumType(Ht)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),gh=z.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:hc,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Na,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:fc,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:pc,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:mc,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Oa,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Ua,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Fa,oneof:"value"}]),e0=z.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:vh,repeated:!0}]),vh=z.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}]),hc=z.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}]),yh=z.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),t0=z.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:n0,repeated:!0}]),n0=z.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}]),Na=z.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}]),fc=z.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}]),pc=z.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),mc=z.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:bh,oneof:"value"}]),bh=z.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}]),_h=z.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Sh=z.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:z.getEnumType(xh)},{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}]),xh=z.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Th=z.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:z.getEnumType(Ch)},{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}]),Ch=z.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"}]),Eh=z.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Mh},{no:2,name:"screen",kind:"message",T:Mh},{no:3,name:"resume_connection",kind:"enum",T:z.getEnumType(Nr)},{no:4,name:"disabled_codecs",kind:"message",T:i0},{no:5,name:"force_relay",kind:"enum",T:z.getEnumType(Nr)}]),Mh=z.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:z.getEnumType(Nr)}]),i0=z.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:La,repeated:!0},{no:2,name:"publish",kind:"message",T:La,repeated:!0}]),wh=z.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),gc=z.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Ah=z.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:z.getEnumType(gc)},{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"}),Rh=z.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Oa=z.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:z.getEnumType(Ht)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Ah,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Rh,oneof:"content_header"}],{localName:"DataStream_Header"}),Ua=z.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"}),Fa=z.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"}),s0=z.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),zn=z.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),vc=z.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),r0=z.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),a0=z.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Gi,oneof:"message"},{no:2,name:"answer",kind:"message",T:Gi,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Ba,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Ur,oneof:"message"},{no:5,name:"mute",kind:"message",T:za,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Va,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:kh,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ga,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Dh,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Oh,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Tc,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Jn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Sc,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Bh,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:_c,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Ih,oneof:"message"}]),Ph=z.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:o0,oneof:"message"},{no:2,name:"answer",kind:"message",T:Gi,oneof:"message"},{no:3,name:"offer",kind:"message",T:Gi,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Ba,oneof:"message"},{no:5,name:"update",kind:"message",T:d0,oneof:"message"},{no:6,name:"track_published",kind:"message",T:bc,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ga,oneof:"message"},{no:9,name:"mute",kind:"message",T:za,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:u0,oneof:"message"},{no:11,name:"room_update",kind:"message",T:h0,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:p0,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:g0,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:y0,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:_0,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:l0,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:c0,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:x0,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:E0,oneof:"message"},{no:22,name:"request_response",kind:"message",T:M0,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:w0,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:S0,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:k0,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:b0,oneof:"message"}]),yc=z.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Vi,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:z.getEnumType(ph)}]),Ur=z.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:z.getEnumType(Fn)},{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:z.getEnumType(Bt)},{no:9,name:"layers",kind:"message",T:Vi,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:yc,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:z.getEnumType(Ht)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:z.getEnumType(fh)},{no:17,name:"audio_features",kind:"enum",T:z.getEnumType(jt),repeated:!0}]),Ba=z.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:z.getEnumType(zn)},{no:3,name:"final",kind:"scalar",T:8}]),za=z.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),o0=z.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Da},{no:2,name:"participant",kind:"message",T:us},{no:3,name:"other_participants",kind:"message",T:us,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Lh,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:Eh},{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:Sh},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:La,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),c0=z.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Lh,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Eh},{no:3,name:"server_info",kind:"message",T:Sh},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),bc=z.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Us}]),l0=z.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Gi=z.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),d0=z.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:us,repeated:!0}]),Va=z.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:_h,repeated:!0}]),kh=z.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:z.getEnumType(uc)},{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}]),_c=z.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:z.getEnumType(jt),repeated:!0}]),Ih=z.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}]),Ga=z.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:z.getEnumType(Bn)},{no:3,name:"action",kind:"enum",T:z.getEnumType(Fs)},{no:4,name:"regions",kind:"message",T:T0}]),Fs=z.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Dh=z.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Vi,repeated:!0}]),Sc=z.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}]),Lh=z.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}]),u0=z.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:vh,repeated:!0}]),h0=z.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Da}]),f0=z.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:z.getEnumType(Lr)},{no:3,name:"score",kind:"scalar",T:2}]),p0=z.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:f0,repeated:!0}]),m0=z.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:z.getEnumType(vc)}]),g0=z.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:m0,repeated:!0}]),xc=z.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:z.getEnumType(uc)},{no:2,name:"enabled",kind:"scalar",T:8}]),v0=z.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:xc,repeated:!0}]),y0=z.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:xc,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:v0,repeated:!0}]),b0=z.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:s0,repeated:!0}]),Nh=z.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}]),Oh=z.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Nh,repeated:!0}]),_0=z.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}]),S0=z.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Da},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:us},{no:4,name:"other_participants",kind:"message",T:us,repeated:!0}]),Tc=z.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Gi},{no:2,name:"subscription",kind:"message",T:Va},{no:3,name:"publish_tracks",kind:"message",T:bc,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Fh,repeated:!0},{no:5,name:"offer",kind:"message",T:Gi},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Uh,repeated:!0}]),Uh=z.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Fh=z.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:z.getEnumType(zn)}]),Jn=z.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:z.getEnumType(r0),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"}]),Bh=z.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),x0=z.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),T0=z.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:C0,repeated:!0}]),C0=z.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}]),E0=z.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:z.getEnumType(Yv)}]),M0=z.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:z.getEnumType(Cc)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Ba,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Ur,oneof:"request"},{no:6,name:"mute",kind:"message",T:za,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Sc,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:_c,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Ih,oneof:"request"}]),Cc=z.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"}]),w0=z.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),zh=z.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8}]),A0=z.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Th},{no:2,name:"connection_settings",kind:"message",T:zh},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:Ur,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Gi},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:z.getEnumType(ds)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Tc}]),R0=z.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:z.getEnumType(P0)},{no:2,name:"join_request",kind:"scalar",T:12}]),P0=z.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),k0=z.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function I0(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Ha={exports:{}},D0=Ha.exports,Vh;function L0(){return Vh||(Vh=1,(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(D0,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(v,m){var p=v[m];if(typeof p.bind=="function")return p.bind(v);try{return Function.prototype.bind.call(p,v)}catch{return function(){return Function.prototype.apply.apply(p,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&n?c:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),m=0;m<s.length;m++){var p=s[m];this[p]=m<v?e:this.methodFactory(p,v,this.name)}if(this.log=this.debug,typeof console===t&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==t&&(d.call(this),this[v].apply(this,arguments))}}function h(v,m,p){return l(v)||u.apply(this,arguments)}function f(v,m){var p=this,T,E,y,S="loglevel";typeof v=="string"?S+=":"+v:typeof v=="symbol"&&(S=void 0);function C(R){var O=(s[R]||"silent").toUpperCase();if(!(typeof window===t||!S)){try{window.localStorage[S]=O;return}catch{}try{window.document.cookie=encodeURIComponent(S)+"="+O+";"}catch{}}}function w(){var R;if(!(typeof window===t||!S)){try{R=window.localStorage[S]}catch{}if(typeof R===t)try{var O=window.document.cookie,F=encodeURIComponent(S),q=O.indexOf(F+"=");q!==-1&&(R=/^([^;]+)/.exec(O.slice(q+F.length+1))[1])}catch{}return p.levels[R]===void 0&&(R=void 0),R}}function k(){if(!(typeof window===t||!S)){try{window.localStorage.removeItem(S)}catch{}try{window.document.cookie=encodeURIComponent(S)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function _(R){var O=R;if(typeof O=="string"&&p.levels[O.toUpperCase()]!==void 0&&(O=p.levels[O.toUpperCase()]),typeof O=="number"&&O>=0&&O<=p.levels.SILENT)return O;throw new TypeError("log.setLevel() called with invalid level: "+R)}p.name=v,p.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},p.methodFactory=m||h,p.getLevel=function(){return y??E??T},p.setLevel=function(R,O){return y=_(R),O!==!1&&C(y),d.call(p)},p.setDefaultLevel=function(R){E=_(R),w()||p.setLevel(R,!1)},p.resetLevel=function(){y=null,k(),d.call(p)},p.enableAll=function(R){p.setLevel(p.levels.TRACE,R)},p.disableAll=function(R){p.setLevel(p.levels.SILENT,R)},p.rebuild=function(){if(o!==p&&(T=_(o.getLevel())),d.call(p),o===p)for(var R in r)r[R].rebuild()},T=_(o?o.getLevel():"WARN");var x=w();x!=null&&(y=_(x)),d.call(p)}o=new f,o.getLogger=function(m){if(typeof m!="symbol"&&typeof m!="string"||m==="")throw new TypeError("You must supply a name when creating a logger.");var p=r[m];return p||(p=r[m]=new f(m,o.methodFactory)),p};var g=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return r},o.default=o,o})})(Ha)),Ha.exports}var Wa=L0(),Ec;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(Ec||(Ec={}));var Vn;(function(i){i.Default="livekit",i.Room="livekit-room",i.TokenSource="livekit-token-source",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee"})(Vn||(Vn={}));let He=Wa.getLogger("livekit");Object.values(Vn).map(i=>Wa.getLogger(i)),He.setDefaultLevel(Ec.info);function mi(i){const e=Wa.getLogger(i);return e.setDefaultLevel(He.getLevel()),e}const N0=Wa.getLogger("lk-e2ee"),Fr=7e3,O0=[0,300,4*300,9*300,16*300,Fr,Fr,Fr,Fr,Fr];class U0{constructor(e){this._retryDelays=e!==void 0?[...e]:O0}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function F0(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(i,n[s])&&(t[n[s]]=i[n[s]]);return t}function P(i,e,t,n){function s(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?r(d.value):s(d.value).then(a,c)}l((n=n.apply(i,e||[])).next())})}function Gh(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function gi(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof Gh=="function"?Gh(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=i[r]&&function(o){return new Promise(function(a,c){o=i[r](o),s(a,c,o.done,o.value)})}}function s(r,o,a,c){Promise.resolve(c).then(function(l){r({value:l,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;var qa={exports:{}},Hh;function B0(){if(Hh)return qa.exports;Hh=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(S,C,w){return Function.prototype.apply.call(S,C,w)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function n(y){console&&console.warn&&console.warn(y)}var s=Number.isNaN||function(S){return S!==S};function r(){r.init.call(this)}qa.exports=r,qa.exports.once=p,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(y){if(typeof y!="number"||y<0||s(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");o=y}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||s(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function c(y){return y._maxListeners===void 0?r.defaultMaxListeners:y._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(S){for(var C=[],w=1;w<arguments.length;w++)C.push(arguments[w]);var k=S==="error",_=this._events;if(_!==void 0)k=k&&_.error===void 0;else if(!k)return!1;if(k){var x;if(C.length>0&&(x=C[0]),x instanceof Error)throw x;var R=new Error("Unhandled error."+(x?" ("+x.message+")":""));throw R.context=x,R}var O=_[S];if(O===void 0)return!1;if(typeof O=="function")e(O,this,C);else for(var F=O.length,q=g(O,F),w=0;w<F;++w)e(q[w],this,C);return!0};function l(y,S,C,w){var k,_,x;if(a(C),_=y._events,_===void 0?(_=y._events=Object.create(null),y._eventsCount=0):(_.newListener!==void 0&&(y.emit("newListener",S,C.listener?C.listener:C),_=y._events),x=_[S]),x===void 0)x=_[S]=C,++y._eventsCount;else if(typeof x=="function"?x=_[S]=w?[C,x]:[x,C]:w?x.unshift(C):x.push(C),k=c(y),k>0&&x.length>k&&!x.warned){x.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+String(S)+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=y,R.type=S,R.count=x.length,n(R)}return y}r.prototype.addListener=function(S,C){return l(this,S,C,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(S,C){return l(this,S,C,!0)};function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(y,S,C){var w={fired:!1,wrapFn:void 0,target:y,type:S,listener:C},k=d.bind(w);return k.listener=C,w.wrapFn=k,k}r.prototype.once=function(S,C){return a(C),this.on(S,u(this,S,C)),this},r.prototype.prependOnceListener=function(S,C){return a(C),this.prependListener(S,u(this,S,C)),this},r.prototype.removeListener=function(S,C){var w,k,_,x,R;if(a(C),k=this._events,k===void 0)return this;if(w=k[S],w===void 0)return this;if(w===C||w.listener===C)--this._eventsCount===0?this._events=Object.create(null):(delete k[S],k.removeListener&&this.emit("removeListener",S,w.listener||C));else if(typeof w!="function"){for(_=-1,x=w.length-1;x>=0;x--)if(w[x]===C||w[x].listener===C){R=w[x].listener,_=x;break}if(_<0)return this;_===0?w.shift():v(w,_),w.length===1&&(k[S]=w[0]),k.removeListener!==void 0&&this.emit("removeListener",S,R||C)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(S){var C,w,k;if(w=this._events,w===void 0)return this;if(w.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):w[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete w[S]),this;if(arguments.length===0){var _=Object.keys(w),x;for(k=0;k<_.length;++k)x=_[k],x!=="removeListener"&&this.removeAllListeners(x);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(C=w[S],typeof C=="function")this.removeListener(S,C);else if(C!==void 0)for(k=C.length-1;k>=0;k--)this.removeListener(S,C[k]);return this};function h(y,S,C){var w=y._events;if(w===void 0)return[];var k=w[S];return k===void 0?[]:typeof k=="function"?C?[k.listener||k]:[k]:C?m(k):g(k,k.length)}r.prototype.listeners=function(S){return h(this,S,!0)},r.prototype.rawListeners=function(S){return h(this,S,!1)},r.listenerCount=function(y,S){return typeof y.listenerCount=="function"?y.listenerCount(S):f.call(y,S)},r.prototype.listenerCount=f;function f(y){var S=this._events;if(S!==void 0){var C=S[y];if(typeof C=="function")return 1;if(C!==void 0)return C.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(y,S){for(var C=new Array(S),w=0;w<S;++w)C[w]=y[w];return C}function v(y,S){for(;S+1<y.length;S++)y[S]=y[S+1];y.pop()}function m(y){for(var S=new Array(y.length),C=0;C<S.length;++C)S[C]=y[C].listener||y[C];return S}function p(y,S){return new Promise(function(C,w){function k(x){y.removeListener(S,_),w(x)}function _(){typeof y.removeListener=="function"&&y.removeListener("error",k),C([].slice.call(arguments))}E(y,S,_,{once:!0}),S!=="error"&&T(y,k,{once:!0})})}function T(y,S,C){typeof y.on=="function"&&E(y,"error",S,C)}function E(y,S,C,w){if(typeof y.on=="function")w.once?y.once(S,C):y.on(S,C);else if(typeof y.addEventListener=="function")y.addEventListener(S,function k(_){w.once&&y.removeEventListener(S,k),C(_)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof y)}return qa.exports}var Zn=B0();let Wh=!0,qh=!0;function Br(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function hs(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const c=l=>{const d=t(l);d&&(a.handleEvent?a.handleEvent(d):a(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),s.apply(this,[o,c])};const r=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(a))return r.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[o,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function z0(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Wh=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function V0(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(qh=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function jh(){if(typeof window=="object"){if(Wh)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Mc(i,e){qh&&console.warn(i+" is deprecated, please use "+e+" instead.")}function G0(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Br(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Br(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Br(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=Br(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function $h(i){return Object.prototype.toString.call(i)==="[object Object]"}function Xh(i){return $h(i)?Object.keys(i).reduce(function(e,t){const n=$h(i[t]),s=n?Xh(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function wc(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?wc(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{wc(i,i.get(s),t)})}))}function Kh(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return i.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&r.push(o)}),r.forEach(o=>{i.forEach(a=>{a.type===n&&a.trackId===o.id&&wc(i,a,s)})}),s}const Yh=jh;function Jh(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const d=typeof a[l]=="object"?a[l]:{ideal:a[l]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(d.ideal!==void 0){c.optional=c.optional||[];let h={};typeof d.ideal=="number"?(h[u("min",l)]=d.ideal,c.optional.push(h),h={},h[u("max",l)]=d.ideal,c.optional.push(h)):(h[u("",l)]=d.ideal,c.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",l)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,l)]=d[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(d,u,h){u in d&&!(h in d)&&(d[h]=d[u],delete d[u])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const d=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete a.video.facingMode;let u;if(l.exact==="environment"||l.ideal==="environment"?u=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let f=h.find(g=>u.some(v=>g.label.toLowerCase().includes(v)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=n(a.video),Yh("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return Yh("chrome: "+JSON.stringify(a)),c(a)},r=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){s(a,d=>{t.webkitGetUserMedia(d,c,u=>{l&&l(r(u))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,l=>a(l).then(d=>{if(l.audio&&!d.getAudioTracks().length||l.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(r(d))))}}}function Zh(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Qh(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):r={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.id):r={track:s};const o=new Event("track");o.track=s,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else hs(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function ef(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,c){let l=s.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){r.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function tf(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(o=>o._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>Kh(o,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),hs(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Kh(r,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let s,r,o;return this.getSenders().forEach(a=>{a.track===n&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===n&&(r?o=!0:r=a),a.track===n)),o||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function nf(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(u=>u.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function sf(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return nf(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(u=>this._reverseStreams[u.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const u=new i.MediaStream(d.getTracks());this._streams[d.id]=u,this._reverseStreams[u.id]=d,d=u}n.apply(this,[d])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},i.RTCPeerConnection.prototype.addTrack=function(d,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(v=>v===d))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(v=>v.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const g=this._streams[u.id];if(g)g.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new i.MediaStream([d]);this._streams[u.id]=v,this._reverseStreams[v.id]=u,this.addStream(v)}return this.getSenders().find(v=>v.track===d)};function r(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:d.type,sdp:u})}function o(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:u})}["createOffer","createAnswer"].forEach(function(l){const d=i.RTCPeerConnection.prototype[l],u={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[g=>{const v=r(this,g);h[0].apply(null,[v])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):d.apply(this,arguments).then(g=>r(this,g))}};i.RTCPeerConnection.prototype[l]=u[l]});const a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:r(this,l)}}),i.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(v=>d.track===v)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Ac(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=s[t]})}function rf(i,e){hs(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var af=Object.freeze({__proto__:null,fixNegotiationNeeded:rf,shimAddTrackRemoveTrack:sf,shimAddTrackRemoveTrackWithNative:nf,shimGetSendersWithDtmf:ef,shimGetUserMedia:Jh,shimMediaStream:Zh,shimOnTrack:Qh,shimPeerConnection:Ac,shimSenderReceiverGetStats:tf});function of(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,o){Mc("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),r(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function H0(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function cf(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Rc(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=i.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[r,o,a]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((d,u)=>{c.set(u,Object.assign({},d,{type:t[d.type]||d.type}))})}return c}).then(o,a)}}function lf(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function df(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),hs(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function uf(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Mc("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function hf(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function ff(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const s=n.length>0;s&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:o}=r,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return r})}function pf(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function mf(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function gf(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var vf=Object.freeze({__proto__:null,shimAddTransceiver:ff,shimCreateAnswer:gf,shimCreateOffer:mf,shimGetDisplayMedia:H0,shimGetParameters:pf,shimGetUserMedia:of,shimOnTrack:cf,shimPeerConnection:Rc,shimRTCDataChannel:hf,shimReceiverGetStats:df,shimRemoveStream:uf,shimSenderGetStats:lf});function yf(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o<s;o++)r[o-1]=arguments[o];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function bf(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(r)>=0)return;n._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function _f(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h},e.createAnswer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h};let a=function(c,l,d){const u=s.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u};e.setLocalDescription=a,a=function(c,l,d){const u=r.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.setRemoteDescription=a,a=function(c,l,d){const u=o.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.addIceCandidate=a}function Sf(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(xf(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function xf(i){return i&&i.video!==void 0?Object.assign({},i,{video:Xh(i.video)}):i}function Tf(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const r=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(Mc("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(n.iceServers[o])}n.iceServers=r}return new e(n,s)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Cf(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ef(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Mf(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var wf=Object.freeze({__proto__:null,shimAudioContext:Mf,shimCallbacksAPI:_f,shimConstraints:xf,shimCreateOfferLegacy:Ef,shimGetUserMedia:Sf,shimLocalStreamsAPI:yf,shimRTCIceServerUrls:Tf,shimRemoteStreamsAPI:bf,shimTrackEventTransceiver:Cf}),Pc={exports:{}},Af;function W0(){return Af||(Af=1,(function(i){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
47
+ */const xa=()=>new Qg;let Qg=class{};const sc=new WeakMap,Ta=$g(class extends Zg{render(i){return Ft}update(i,[e]){var n;const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=(n=i.options)==null?void 0:n.host,this.rt(this.ct=i.element)),Ft}rt(i){if(this.isConnected||(i=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=sc.get(e);t===void 0&&(t=new WeakMap,sc.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,i),i!==void 0&&this.G.call(this.ht,i)}else this.G.value=i}get lt(){var i,e;return typeof this.G=="function"?(i=sc.get(this.ht??globalThis))==null?void 0:i.get(this.G):(e=this.G)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function ev(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var tv=Object.defineProperty,nv=(i,e,t)=>e in i?tv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Nu=(i,e,t)=>nv(i,typeof e!="symbol"?e+"":e,t);class cn{constructor(){Nu(this,"_locking"),Nu(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}}function Pt(i,e){if(!i)throw new Error(e)}const iv=34028234663852886e22,sv=-34028234663852886e22,rv=4294967295,av=2147483647,ov=-2147483648;function Ca(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>av||i<ov)throw new Error("invalid int 32: "+i)}function rc(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>rv||i<0)throw new Error("invalid uint 32: "+i)}function Ou(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>iv||i<sv))throw new Error("invalid float 32: "+i)}const Uu=Symbol("@bufbuild/protobuf/enum-type");function cv(i){const e=i[Uu];return Pt(e,"missing enum type on enum object"),e}function Fu(i,e,t,n){i[Uu]=Bu(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function Bu(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const o of e){const a=zu(o);r.push(a),n[o.name]=a,s[o.no]=a}return{typeName:i,values:r,findName(o){return n[o]},findNumber(o){return s[o]}}}function lv(i,e,t){const n={};for(const s of e){const r=zu(s);n[r.localName]=r.no,n[r.no]=r.localName}return Fu(n,i,e),n}function zu(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class ac{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),s=n.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),s=n.runtime.json,r=s.makeReadOptions(t);return s.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,s=n.makeWriteOptions(e),r=s.writerFactory();return n.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,s=n.makeWriteOptions(e);return n.writeMessage(this,s)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function dv(i,e,t,n){var s;const r=(s=n==null?void 0:n.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(a){i.util.initFields(this),i.util.initPartial(a,this)}}[r];return Object.setPrototypeOf(o.prototype,new ac),Object.assign(o,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return i.util.equals(o,a,c)}}),o}function uv(){let i=0,e=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(i|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function oc(i,e,t){for(let r=0;r<28;r=r+7){const o=i>>>r,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const n=i>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?n|128:n)&255),!!s){for(let r=3;r<31;r=r+7){const o=e>>>r,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const Ea=4294967296;function Vu(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(o,a){const c=Number(i.slice(o,a));s*=t,n=n*t+c,n>=Ea&&(s=s+(n/Ea|0),n=n%Ea)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?Hu(n,s):cc(n,s)}function hv(i,e){let t=cc(i,e);const n=t.hi&2147483648;n&&(t=Hu(t.lo,t.hi));const s=Gu(t.lo,t.hi);return n?"-"+s:s}function Gu(i,e){if({lo:i,hi:e}=fv(i,e),e<=2097151)return String(Ea*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+n*6777216+s*6710656,o=n+s*8147497,a=s*2;const c=1e7;return r>=c&&(o+=Math.floor(r/c),r%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+Wu(o)+Wu(r)}function fv(i,e){return{lo:i>>>0,hi:e>>>0}}function cc(i,e){return{lo:i|0,hi:e|0}}function Hu(i,e){return e=~e,i?i=~i+1:e+=1,cc(i,e)}const Wu=i=>{const e=String(i);return"0000000".slice(e.length)+e};function qu(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function pv(){let i=this.buf[this.pos++],e=i&127;if((i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,(i&128)==0)return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;(i&128)!==0&&t<10;t++)i=this.buf[this.pos++];if((i&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function mv(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>r||l<s)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>a||l<o)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return i.setBigInt64(0,this.parse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(c){return i.setBigInt64(0,this.uParse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigInt64(0,!0)},uDec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigUint64(0,!0)}}}const t=s=>Pt(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>Pt(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),n(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Vu(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),Vu(s)},dec(s,r){return hv(s,r)},uDec(s,r){return Gu(s,r)}}}const wt=mv();var J;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(J||(J={}));var Bi;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(Bi||(Bi={}));function zi(i,e,t){if(e===t)return!0;if(i==J.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case J.UINT64:case J.FIXED64:case J.INT64:case J.SFIXED64:case J.SINT64:return e==t}return!1}function Ls(i,e){switch(i){case J.BOOL:return!1;case J.UINT64:case J.FIXED64:case J.INT64:case J.SFIXED64:case J.SINT64:return e==0?wt.zero:"0";case J.DOUBLE:case J.FLOAT:return 0;case J.BYTES:return new Uint8Array(0);case J.STRING:return"";default:return 0}}function ju(i,e){switch(i){case J.BOOL:return e===!1;case J.STRING:return e==="";case J.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var Ot;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(Ot||(Ot={}));class gv{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),n=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],n),n+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(rc(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ca(e),qu(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Ou(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){rc(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ca(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ca(e),e=(e<<1^e>>31)>>>0,qu(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=wt.enc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=wt.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=wt.enc(e);return oc(t.lo,t.hi,this.buf),this}sint64(e){let t=wt.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return oc(s,r,this.buf),this}uint64(e){let t=wt.uEnc(e);return oc(t.lo,t.hi,this.buf),this}}class vv{constructor(e,t){this.varint64=uv,this.uint32=pv,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case Ot.Varint:for(;this.buf[this.pos++]&128;);break;case Ot.Bit64:this.pos+=4;case Ot.Bit32:this.pos+=4;break;case Ot.LengthDelimited:let s=this.uint32();this.pos+=s;break;case Ot.StartGroup:for(;;){const[r,o]=this.tag();if(o===Ot.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(o,r)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return wt.dec(...this.varint64())}uint64(){return wt.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,wt.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return wt.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return wt.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function yv(i,e,t,n){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof n=="function"?n():n;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=i.util.newFieldList([r]).list()[0]}return s},runtime:i}}function $u(i){const e=i.field.localName,t=Object.create(null);return t[e]=bv(i),[t,()=>t[e]]}function bv(i){const e=i.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return Ls(e.T,e.L);case"message":const t=e.T,n=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}function _v(i,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=i.length-1;t>=0;--t)if(i[t].no==e.no)return[i[t]];return[]}return i.filter(t=>t.no===e.no)}let fi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Ma=[];for(let i=0;i<fi.length;i++)Ma[fi[i].charCodeAt(0)]=i;Ma[45]=fi.indexOf("+"),Ma[95]=fi.indexOf("/");const Xu={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,s=0,r,o=0;for(let a=0;a<i.length;a++){if(r=Ma[i.charCodeAt(a)],r===void 0)switch(i[a]){case"=":s=0;case`
48
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:t[n++]=o<<2|(r&48)>>4,o=r,s=2;break;case 2:t[n++]=(o&15)<<4|(r&60)>>2,o=r,s=3;break;case 3:t[n++]=(o&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,s=0;for(let r=0;r<i.length;r++)switch(n=i[r],t){case 0:e+=fi[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=fi[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=fi[s|n>>6],e+=fi[n&63],t=0;break}return t&&(e+=fi[s],e+="=",t==1&&(e+="=")),e}};function Sv(i,e,t){Yu(e,i);const n=e.runtime.bin.makeReadOptions(t),s=_v(i.getType().runtime.bin.listUnknownFields(i),e.field),[r,o]=$u(e);for(const a of s)e.runtime.bin.readField(r,n.readerFactory(a.data),e.field,a.wireType,n);return o()}function xv(i,e,t,n){Yu(e,i);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(Ku(i,e)){const l=i.getType().runtime.bin.listUnknownFields(i).filter(d=>d.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(const d of l)i.getType().runtime.bin.onUnknownField(i,d.no,d.wireType,d.data)}const o=r.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[l,d]=c.tag(),u=c.skip(d,l);i.getType().runtime.bin.onUnknownField(i,l,d,u)}}function Ku(i,e){const t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function Yu(i,e){Pt(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function Ju(i,e){const t=i.localName;if(i.repeated)return e[t].length>0;if(i.oneof)return e[i.oneof.localName].case===t;switch(i.kind){case"enum":case"scalar":return i.opt||i.req?e[t]!==void 0:i.kind=="enum"?e[t]!==i.T.values[0].no:!ju(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Zu(i,e){const t=i.localName,n=!i.opt&&!i.req;if(i.repeated)e[t]=[];else if(i.oneof)e[i.oneof.localName]={case:void 0};else switch(i.kind){case"map":e[t]={};break;case"enum":e[t]=n?i.T.values[0].no:void 0;break;case"scalar":e[t]=n?Ls(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function pi(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(ac.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;const t=i.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Qu(i,e){return pi(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}J.DOUBLE,J.FLOAT,J.INT64,J.UINT64,J.INT32,J.UINT32,J.BOOL,J.STRING,J.BYTES;const eh={ignoreUnknownFields:!1},th={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Tv(i){return i?Object.assign(Object.assign({},eh),i):eh}function Cv(i){return i?Object.assign(Object.assign({},th),i):th}const wa=Symbol(),Aa=Symbol();function Ev(){return{makeReadOptions:Tv,makeWriteOptions:Cv,readMessage(i,e,t,n){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat(Yn(e)));n=n??new i;const s=new Map,r=t.typeRegistry;for(const[o,a]of Object.entries(e)){const c=i.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const l=s.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(o,'"'));s.set(c.oneof,o)}nh(n,a,c,t,i)}else{let l=!1;if(r!=null&&r.findExtension&&o.startsWith("[")&&o.endsWith("]")){const d=r.findExtension(o.substring(1,o.length-1));if(d&&d.extendee.typeName==i.typeName){l=!0;const[u,h]=$u(d);nh(u,a,d.field,t,d),xv(n,d,h(),t)}}if(!l&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(i,e){const t=i.getType(),n={};let s;try{for(s of t.fields.byNumber()){if(!Ju(s,i)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!wv(s))continue}const o=s.oneof?i[s.oneof.localName].value:i[s.localName],a=ih(s,o,e);a!==void 0&&(n[e.useProtoFieldName?s.name:s.jsonName]=a)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(i)){const a=r.findExtensionFor(t.typeName,o.no);if(a&&Ku(i,a)){const c=Sv(i,a,e),l=ih(a.field,c,e);l!==void 0&&(n[a.field.jsonName]=l)}}}catch(r){const o=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=r instanceof Error?r.message:String(r);throw new Error(o+(a.length>0?": ".concat(a):""))}return n},readScalar(i,e,t){return kr(i,e,t??Bi.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||ju(i,e)))return Ra(i,e)},debug:Yn}}function Yn(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function nh(i,e,t,n,s){let r=t.localName;if(t.repeated){if(Pt(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(e)));const o=i[r];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(a)));switch(t.kind){case"message":o.push(t.T.fromJson(a,n));break;case"enum":const c=lc(t.T,a,n.ignoreUnknownFields,!0);c!==Aa&&o.push(c);break;case"scalar":try{o.push(kr(t.T,a,t.L,!0))}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(a));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(e)));const o=i[r];for(const[a,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let l;try{l=Mv(t.K,a)}catch(d){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(e));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}switch(t.V.kind){case"message":o[l]=t.V.T.fromJson(c,n);break;case"enum":const d=lc(t.V.T,c,n.ignoreUnknownFields,!0);d!==Aa&&(o[l]=d);break;case"scalar":try{o[l]=kr(t.V.T,c,Bi.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=i[r];pi(a)?a.fromJson(e,n):(i[r]=a=o.fromJson(e,n),o.fieldWrapper&&!t.oneof&&(i[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=lc(t.T,e,n.ignoreUnknownFields,!1);switch(c){case wa:Zu(t,i);break;case Aa:break;default:i[r]=c;break}break;case"scalar":try{const l=kr(t.T,e,t.L,!1);switch(l){case wa:Zu(t,i);break;default:i[r]=l;break}}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Yn(e));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}function Mv(i,e){if(i===J.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return kr(i,e,Bi.BIGINT,!0).toString()}function kr(i,e,t,n){if(e===null)return n?Ls(i,t):wa;switch(i){case J.DOUBLE:case J.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return i==J.FLOAT&&Ou(s),s;case J.INT32:case J.FIXED32:case J.SFIXED32:case J.SINT32:case J.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return i==J.UINT32||i==J.FIXED32?rc(r):Ca(r),r;case J.INT64:case J.SFIXED64:case J.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=wt.parse(e);return t?o.toString():o;case J.FIXED64:case J.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=wt.uParse(e);return t?a.toString():a;case J.BOOL:if(typeof e!="boolean")break;return e;case J.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case J.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Xu.dec(e)}throw new Error}function lc(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:wa;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=i.findName(e);if(s!==void 0)return s.no;if(t)return Aa;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(Yn(e)))}function wv(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function ih(i,e,t){if(i.kind=="map"){Pt(typeof e=="object"&&e!=null);const n={},s=Object.entries(e);switch(i.V.kind){case"scalar":for(const[o,a]of s)n[o.toString()]=Ra(i.V.T,a);break;case"message":for(const[o,a]of s)n[o.toString()]=a.toJson(t);break;case"enum":const r=i.V.T;for(const[o,a]of s)n[o.toString()]=dc(r,a,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?n:void 0}if(i.repeated){Pt(Array.isArray(e));const n=[];switch(i.kind){case"scalar":for(let s=0;s<e.length;s++)n.push(Ra(i.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)n.push(dc(i.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)n.push(e[s].toJson(t));break}return t.emitDefaultValues||n.length>0?n:void 0}switch(i.kind){case"scalar":return Ra(i.T,e);case"enum":return dc(i.T,e,t.enumAsInteger);case"message":return Qu(i.T,e).toJson(t)}}function dc(i,e,t){var n;if(Pt(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=i.findNumber(e);return(n=s==null?void 0:s.name)!==null&&n!==void 0?n:e}function Ra(i,e){switch(i){case J.INT32:case J.SFIXED32:case J.SINT32:case J.FIXED32:case J.UINT32:return Pt(typeof e=="number"),e;case J.FLOAT:case J.DOUBLE:return Pt(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case J.STRING:return Pt(typeof e=="string"),e;case J.BOOL:return Pt(typeof e=="boolean"),e;case J.UINT64:case J.FIXED64:case J.INT64:case J.SFIXED64:case J.SINT64:return Pt(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case J.BYTES:return Pt(e instanceof Uint8Array),Xu.enc(e)}}const Ns=Symbol("@bufbuild/protobuf/unknown-fields"),sh={readUnknownFields:!0,readerFactory:i=>new vv(i)},rh={writeUnknownFields:!0,writerFactory:()=>new gv};function Av(i){return i?Object.assign(Object.assign({},sh),i):sh}function Rv(i){return i?Object.assign(Object.assign({},rh),i):rh}function Pv(){return{makeReadOptions:Av,makeWriteOptions:Rv,listUnknownFields(i){var e;return(e=i[Ns])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Ns]},writeUnknownFields(i,e){const n=i[Ns];if(n)for(const s of n)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(i,e,t,n){const s=i;Array.isArray(s[Ns])||(s[Ns]=[]),s[Ns].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,s){const r=i.getType(),o=s?e.len:e.pos+t;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!(s===!0&&c==Ot.EndGroup));){const l=r.fields.find(a);if(!l){const d=e.skip(c,a);n.readUnknownFields&&this.onUnknownField(i,a,c,d);continue}ah(i,e,l,c,n)}if(s&&(c!=Ot.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:ah,writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){if(!Ju(s,i)){if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?i[s.oneof.localName].value:i[s.localName];oh(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&oh(i,e,t,n)}}}function ah(i,e,t,n,s){let{repeated:r,localName:o}=t;switch(t.oneof&&(i=i[t.oneof.localName],i.case!=o&&delete i.value,i.case=o,o="value"),t.kind){case"scalar":case"enum":const a=t.kind=="enum"?J.INT32:t.T;let c=ka;if(t.kind=="scalar"&&t.L>0&&(c=Iv),r){let h=i[o];if(n==Ot.LengthDelimited&&a!=J.STRING&&a!=J.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,a))}else h.push(c(e,a))}else i[o]=c(e,a);break;case"message":const l=t.T;r?i[o].push(Pa(e,new l,s,t)):pi(i[o])?Pa(e,i[o],s,t):(i[o]=Pa(e,new l,s,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(i[o]=l.fieldWrapper.unwrapField(i[o])));break;case"map":let[d,u]=kv(t,e,s);i[o][d]=u;break}}function Pa(i,e,t,n){const s=e.getType().runtime.bin,r=n==null?void 0:n.delimited;return s.readMessage(e,i,r?n.no:i.uint32(),t,r),e}function kv(i,e,t){const n=e.uint32(),s=e.pos+n;let r,o;for(;e.pos<s;){const[a]=e.tag();switch(a){case 1:r=ka(e,i.K);break;case 2:switch(i.V.kind){case"scalar":o=ka(e,i.V.T);break;case"enum":o=e.int32();break;case"message":o=Pa(e,new i.V.T,t,void 0);break}break}}if(r===void 0&&(r=Ls(i.K,Bi.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),o===void 0)switch(i.V.kind){case"scalar":o=Ls(i.V.T,Bi.BIGINT);break;case"enum":o=i.V.T.values[0].no;break;case"message":o=new i.V.T;break}return[r,o]}function Iv(i,e){const t=ka(i,e);return typeof t=="bigint"?t.toString():t}function ka(i,e){switch(e){case J.STRING:return i.string();case J.BOOL:return i.bool();case J.DOUBLE:return i.double();case J.FLOAT:return i.float();case J.INT32:return i.int32();case J.INT64:return i.int64();case J.UINT64:return i.uint64();case J.FIXED64:return i.fixed64();case J.BYTES:return i.bytes();case J.FIXED32:return i.fixed32();case J.SFIXED32:return i.sfixed32();case J.SFIXED64:return i.sfixed64();case J.SINT64:return i.sint64();case J.UINT32:return i.uint32();case J.SINT32:return i.sint32()}}function oh(i,e,t,n){Pt(e!==void 0);const s=i.repeated;switch(i.kind){case"scalar":case"enum":let r=i.kind=="enum"?J.INT32:i.T;if(s)if(Pt(Array.isArray(e)),i.packed)Lv(t,r,i.no,e);else for(const o of e)Ir(t,r,i.no,o);else Ir(t,r,i.no,e);break;case"message":if(s){Pt(Array.isArray(e));for(const o of e)ch(t,n,i,o)}else ch(t,n,i,e);break;case"map":Pt(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))Dv(t,n,i,o,a);break}}function Dv(i,e,t,n,s){i.tag(t.no,Ot.LengthDelimited),i.fork();let r=n;switch(t.K){case J.INT32:case J.FIXED32:case J.UINT32:case J.SFIXED32:case J.SINT32:r=Number.parseInt(n);break;case J.BOOL:Pt(n=="true"||n=="false"),r=n=="true";break}switch(Ir(i,t.K,1,r),t.V.kind){case"scalar":Ir(i,t.V.T,2,s);break;case"enum":Ir(i,J.INT32,2,s);break;case"message":Pt(s!==void 0),i.tag(2,Ot.LengthDelimited).bytes(s.toBinary(e));break}i.join()}function ch(i,e,t,n){const s=Qu(t.T,n);t.delimited?i.tag(t.no,Ot.StartGroup).raw(s.toBinary(e)).tag(t.no,Ot.EndGroup):i.tag(t.no,Ot.LengthDelimited).bytes(s.toBinary(e))}function Ir(i,e,t,n){Pt(n!==void 0);let[s,r]=lh(e);i.tag(t,s)[r](n)}function Lv(i,e,t,n){if(!n.length)return;i.tag(t,Ot.LengthDelimited).fork();let[,s]=lh(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function lh(i){let e=Ot.Varint;switch(i){case J.BYTES:case J.STRING:e=Ot.LengthDelimited;break;case J.DOUBLE:case J.FIXED64:case J.SFIXED64:e=Ot.Bit64;break;case J.FIXED32:case J.SFIXED32:case J.FLOAT:e=Ot.Bit32;break}const t=J[i].toLowerCase();return[e,t]}function Nv(){return{setEnumType:Fu,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const s=n.localName,r=e,o=i;if(o[s]!=null)switch(n.kind){case"oneof":const a=o[s].case;if(a===void 0)continue;const c=n.findField(a);let l=o[s].value;c&&c.kind=="message"&&!pi(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===J.BYTES&&(l=Dr(l)),r[s]={case:a,value:l};break;case"scalar":case"enum":let d=o[s];n.T===J.BYTES&&(d=n.repeated?d.map(Dr):Dr(d)),r[s]=d;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===J.BYTES)for(const[f,g]of Object.entries(o[s]))r[s][f]=Dr(g);else Object.assign(r[s],o[s]);break;case"message":const h=n.V.T;for(const f of Object.keys(o[s])){let g=o[s][f];h.fieldWrapper||(g=new h(g)),r[s][f]=g}break}break;case"message":const u=n.T;if(n.repeated)r[s]=o[s].map(h=>pi(h,u)?h:new u(h));else{const h=o[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Dr(h):r[s]=h:r[s]=pi(h,u)?h:new u(h)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const s=e[n.localName],r=t[n.localName];if(n.repeated){if(s.length!==r.length)return!1;switch(n.kind){case"message":return s.every((o,a)=>n.T.equals(o,r[a]));case"scalar":return s.every((o,a)=>zi(n.T,o,r[a]));case"enum":return s.every((o,a)=>zi(J.INT32,o,r[a]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":let o=s,a=r;return n.T.fieldWrapper&&(o!==void 0&&!pi(o)&&(o=n.T.fieldWrapper.wrapField(o)),a!==void 0&&!pi(a)&&(a=n.T.fieldWrapper.wrapField(a))),n.T.equals(o,a);case"enum":return zi(J.INT32,s,r);case"scalar":return zi(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=n.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return zi(J.INT32,s.value,r.value);case"scalar":return zi(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const d=n.V.T;return l.every(h=>d.equals(s[h],r[h]));case"enum":return l.every(h=>zi(J.INT32,s[h],r[h]));case"scalar":const u=n.V.T;return l.every(h=>zi(u,s[h],r[h]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const s of e.fields.byMember()){const r=i[s.localName];let o;if(s.repeated)o=r.map(Ia);else if(s.kind=="map"){o=n[s.localName];for(const[a,c]of Object.entries(r))o[a]=Ia(c)}else s.kind=="oneof"?o=s.findField(r.case)?{case:r.case,value:Ia(r.value)}:{case:void 0}:o=Ia(r);n[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function Ia(i){if(i===void 0)return i;if(pi(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Dr(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function Ov(i,e,t){return{syntax:i,json:Ev(),bin:Pv(),util:Object.assign(Object.assign({},Nv()),{newFieldList:e,initFields:t}),makeMessageType(n,s,r){return dv(this,n,s,r)},makeEnum:lv,makeEnumType:Bu,getEnumType:cv,makeExtension(n,s,r){return yv(this,n,s,r)}}}class Uv{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function dh(i,e){const t=uh(i);return e?t:Hv(Gv(t))}function Fv(i){return dh(i,!1)}const Bv=uh;function uh(i){let e=!1;const t=[];for(let n=0;n<i.length;n++){let s=i.charAt(n);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const zv=new Set(["constructor","toString","toJSON","valueOf"]),Vv=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),hh=i=>"".concat(i,"$"),Gv=i=>Vv.has(i)?hh(i):i,Hv=i=>zv.has(i)?hh(i):i;class Wv{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Fv(e)}addField(e){Pt(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function qv(i,e){var t,n,s,r,o,a;const c=[];let l;for(const d of typeof i=="function"?i():i){const u=d;if(u.localName=dh(d.name,d.oneof!==void 0),u.jsonName=(t=d.jsonName)!==null&&t!==void 0?t:Bv(d.name),u.repeated=(n=d.repeated)!==null&&n!==void 0?n:!1,d.kind=="scalar"&&(u.L=(s=d.L)!==null&&s!==void 0?s:Bi.BIGINT),u.delimited=(r=d.delimited)!==null&&r!==void 0?r:!1,u.req=(o=d.req)!==null&&o!==void 0?o:!1,u.opt=(a=d.opt)!==null&&a!==void 0?a:!1,d.packed===void 0&&(u.packed=d.kind=="enum"||d.kind=="scalar"&&d.T!=J.BYTES&&d.T!=J.STRING),d.oneof!==void 0){const h=typeof d.oneof=="string"?d.oneof:d.oneof.name;(!l||l.name!=h)&&(l=new Wv(h)),u.oneof=l,l.addField(u)}c.push(u)}return c}const z=Ov("proto3",i=>new Uv(i,e=>qv(e)),i=>{for(const e of i.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=Ls(e.T,e.L);break}}});class gn extends ac{constructor(e){super(),this.seconds=wt.zero,this.nanos=0,z.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(z.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=wt.parse(s/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let n="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?n="."+s.substring(0,3)+"Z":s.substring(6)==="000"?n="."+s.substring(0,6)+"Z":n="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return gn.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new gn({seconds:wt.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new gn().fromBinary(e,t)}static fromJson(e,t){return new gn().fromJson(e,t)}static fromJsonString(e,t){return new gn().fromJsonString(e,t)}static equals(e,t){return z.util.equals(gn,e,t)}}gn.runtime=z,gn.typeName="google.protobuf.Timestamp",gn.fields=z.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const jv=z.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:gn},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:$v,repeated:!0},{no:5,name:"events",kind:"message",T:Kv,repeated:!0}]),$v=z.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:Xv,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Xv=z.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:gn},{no:3,name:"value",kind:"scalar",T:2}]),Kv=z.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:gn},{no:7,name:"normalized_end_timestamp",kind:"message",T:gn,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),fh=z.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Fn=z.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Bt=z.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"}]),uc=z.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Lr=z.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Nr=z.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Bn=z.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"}]),ds=z.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"}]),Yv=z.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),$t=z.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"}]),Da=z.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:La,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:wh}]),La=z.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Jv=z.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:z.getEnumType(Bt),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}]),us=z.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:z.getEnumType(Os)},{no:4,name:"tracks",kind:"message",T:Us,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:Jv},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:z.getEnumType(Or)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:z.getEnumType(Bn)},{no:18,name:"kind_details",kind:"enum",T:z.getEnumType(Zv),repeated:!0}]),Os=z.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Or=z.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"}]),Zv=z.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Ht=z.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Qv=z.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:Vi,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:z.getEnumType(ph)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Us=z.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:z.getEnumType(Fn)},{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:z.getEnumType(Bt)},{no:10,name:"layers",kind:"message",T:Vi,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:Qv,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:z.getEnumType(Ht)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:wh},{no:19,name:"audio_features",kind:"enum",T:z.getEnumType($t),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:z.getEnumType(fh)}]),Vi=z.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:z.getEnumType(uc)},{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}]),ph=z.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),ln=z.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:z.getEnumType(Ke)},{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:hc,oneof:"value"},{no:3,name:"speaker",kind:"message",T:e0,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:yh,oneof:"value"},{no:7,name:"transcription",kind:"message",T:t0,oneof:"value"},{no:8,name:"metrics",kind:"message",T:jv,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Na,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:fc,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:pc,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:mc,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Oa,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Ua,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Fa,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:mh,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Ke=z.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),mh=z.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:z.getEnumType(Ht)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),gh=z.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:hc,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Na,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:fc,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:pc,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:mc,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Oa,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Ua,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Fa,oneof:"value"}]),e0=z.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:vh,repeated:!0}]),vh=z.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}]),hc=z.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}]),yh=z.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),t0=z.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:n0,repeated:!0}]),n0=z.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}]),Na=z.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}]),fc=z.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}]),pc=z.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),mc=z.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:bh,oneof:"value"}]),bh=z.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}]),_h=z.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Sh=z.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:z.getEnumType(xh)},{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}]),xh=z.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Th=z.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:z.getEnumType(Ch)},{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}]),Ch=z.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"}]),Eh=z.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Mh},{no:2,name:"screen",kind:"message",T:Mh},{no:3,name:"resume_connection",kind:"enum",T:z.getEnumType(Nr)},{no:4,name:"disabled_codecs",kind:"message",T:i0},{no:5,name:"force_relay",kind:"enum",T:z.getEnumType(Nr)}]),Mh=z.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:z.getEnumType(Nr)}]),i0=z.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:La,repeated:!0},{no:2,name:"publish",kind:"message",T:La,repeated:!0}]),wh=z.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),gc=z.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Ah=z.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:z.getEnumType(gc)},{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"}),Rh=z.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Oa=z.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:z.getEnumType(Ht)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Ah,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Rh,oneof:"content_header"}],{localName:"DataStream_Header"}),Ua=z.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"}),Fa=z.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"}),s0=z.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),zn=z.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),vc=z.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),r0=z.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),a0=z.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Gi,oneof:"message"},{no:2,name:"answer",kind:"message",T:Gi,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Ba,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Ur,oneof:"message"},{no:5,name:"mute",kind:"message",T:za,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Va,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:kh,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ga,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Dh,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Oh,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Tc,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Jn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Sc,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Bh,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:_c,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Ih,oneof:"message"}]),Ph=z.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:o0,oneof:"message"},{no:2,name:"answer",kind:"message",T:Gi,oneof:"message"},{no:3,name:"offer",kind:"message",T:Gi,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Ba,oneof:"message"},{no:5,name:"update",kind:"message",T:d0,oneof:"message"},{no:6,name:"track_published",kind:"message",T:bc,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ga,oneof:"message"},{no:9,name:"mute",kind:"message",T:za,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:u0,oneof:"message"},{no:11,name:"room_update",kind:"message",T:h0,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:p0,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:g0,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:y0,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:_0,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:l0,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:c0,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:x0,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:E0,oneof:"message"},{no:22,name:"request_response",kind:"message",T:M0,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:w0,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:S0,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:k0,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:b0,oneof:"message"}]),yc=z.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Vi,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:z.getEnumType(ph)}]),Ur=z.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:z.getEnumType(Fn)},{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:z.getEnumType(Bt)},{no:9,name:"layers",kind:"message",T:Vi,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:yc,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:z.getEnumType(Ht)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:z.getEnumType(fh)},{no:17,name:"audio_features",kind:"enum",T:z.getEnumType($t),repeated:!0}]),Ba=z.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:z.getEnumType(zn)},{no:3,name:"final",kind:"scalar",T:8}]),za=z.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),o0=z.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Da},{no:2,name:"participant",kind:"message",T:us},{no:3,name:"other_participants",kind:"message",T:us,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Lh,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:Eh},{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:Sh},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:La,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),c0=z.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Lh,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Eh},{no:3,name:"server_info",kind:"message",T:Sh},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),bc=z.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Us}]),l0=z.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Gi=z.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),d0=z.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:us,repeated:!0}]),Va=z.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:_h,repeated:!0}]),kh=z.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:z.getEnumType(uc)},{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}]),_c=z.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:z.getEnumType($t),repeated:!0}]),Ih=z.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}]),Ga=z.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:z.getEnumType(Bn)},{no:3,name:"action",kind:"enum",T:z.getEnumType(Fs)},{no:4,name:"regions",kind:"message",T:T0}]),Fs=z.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Dh=z.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Vi,repeated:!0}]),Sc=z.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}]),Lh=z.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}]),u0=z.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:vh,repeated:!0}]),h0=z.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Da}]),f0=z.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:z.getEnumType(Lr)},{no:3,name:"score",kind:"scalar",T:2}]),p0=z.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:f0,repeated:!0}]),m0=z.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:z.getEnumType(vc)}]),g0=z.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:m0,repeated:!0}]),xc=z.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:z.getEnumType(uc)},{no:2,name:"enabled",kind:"scalar",T:8}]),v0=z.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:xc,repeated:!0}]),y0=z.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:xc,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:v0,repeated:!0}]),b0=z.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:s0,repeated:!0}]),Nh=z.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}]),Oh=z.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Nh,repeated:!0}]),_0=z.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}]),S0=z.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Da},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:us},{no:4,name:"other_participants",kind:"message",T:us,repeated:!0}]),Tc=z.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Gi},{no:2,name:"subscription",kind:"message",T:Va},{no:3,name:"publish_tracks",kind:"message",T:bc,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Fh,repeated:!0},{no:5,name:"offer",kind:"message",T:Gi},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Uh,repeated:!0}]),Uh=z.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Fh=z.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:z.getEnumType(zn)}]),Jn=z.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:z.getEnumType(r0),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"}]),Bh=z.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),x0=z.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),T0=z.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:C0,repeated:!0}]),C0=z.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}]),E0=z.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:z.getEnumType(Yv)}]),M0=z.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:z.getEnumType(Cc)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Ba,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Ur,oneof:"request"},{no:6,name:"mute",kind:"message",T:za,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Sc,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:_c,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Ih,oneof:"request"}]),Cc=z.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"}]),w0=z.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),zh=z.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8}]),A0=z.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Th},{no:2,name:"connection_settings",kind:"message",T:zh},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:Ur,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Gi},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:z.getEnumType(ds)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Tc}]),R0=z.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:z.getEnumType(P0)},{no:2,name:"join_request",kind:"scalar",T:12}]),P0=z.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),k0=z.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function I0(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Ha={exports:{}},D0=Ha.exports,Vh;function L0(){return Vh||(Vh=1,(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(D0,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(v,m){var p=v[m];if(typeof p.bind=="function")return p.bind(v);try{return Function.prototype.bind.call(p,v)}catch{return function(){return Function.prototype.apply.apply(p,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&n?c:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),m=0;m<s.length;m++){var p=s[m];this[p]=m<v?e:this.methodFactory(p,v,this.name)}if(this.log=this.debug,typeof console===t&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==t&&(d.call(this),this[v].apply(this,arguments))}}function h(v,m,p){return l(v)||u.apply(this,arguments)}function f(v,m){var p=this,T,E,y,S="loglevel";typeof v=="string"?S+=":"+v:typeof v=="symbol"&&(S=void 0);function C(R){var O=(s[R]||"silent").toUpperCase();if(!(typeof window===t||!S)){try{window.localStorage[S]=O;return}catch{}try{window.document.cookie=encodeURIComponent(S)+"="+O+";"}catch{}}}function w(){var R;if(!(typeof window===t||!S)){try{R=window.localStorage[S]}catch{}if(typeof R===t)try{var O=window.document.cookie,F=encodeURIComponent(S),q=O.indexOf(F+"=");q!==-1&&(R=/^([^;]+)/.exec(O.slice(q+F.length+1))[1])}catch{}return p.levels[R]===void 0&&(R=void 0),R}}function k(){if(!(typeof window===t||!S)){try{window.localStorage.removeItem(S)}catch{}try{window.document.cookie=encodeURIComponent(S)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function _(R){var O=R;if(typeof O=="string"&&p.levels[O.toUpperCase()]!==void 0&&(O=p.levels[O.toUpperCase()]),typeof O=="number"&&O>=0&&O<=p.levels.SILENT)return O;throw new TypeError("log.setLevel() called with invalid level: "+R)}p.name=v,p.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},p.methodFactory=m||h,p.getLevel=function(){return y??E??T},p.setLevel=function(R,O){return y=_(R),O!==!1&&C(y),d.call(p)},p.setDefaultLevel=function(R){E=_(R),w()||p.setLevel(R,!1)},p.resetLevel=function(){y=null,k(),d.call(p)},p.enableAll=function(R){p.setLevel(p.levels.TRACE,R)},p.disableAll=function(R){p.setLevel(p.levels.SILENT,R)},p.rebuild=function(){if(o!==p&&(T=_(o.getLevel())),d.call(p),o===p)for(var R in r)r[R].rebuild()},T=_(o?o.getLevel():"WARN");var x=w();x!=null&&(y=_(x)),d.call(p)}o=new f,o.getLogger=function(m){if(typeof m!="symbol"&&typeof m!="string"||m==="")throw new TypeError("You must supply a name when creating a logger.");var p=r[m];return p||(p=r[m]=new f(m,o.methodFactory)),p};var g=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return r},o.default=o,o})})(Ha)),Ha.exports}var Wa=L0(),Ec;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(Ec||(Ec={}));var Vn;(function(i){i.Default="livekit",i.Room="livekit-room",i.TokenSource="livekit-token-source",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee"})(Vn||(Vn={}));let He=Wa.getLogger("livekit");Object.values(Vn).map(i=>Wa.getLogger(i)),He.setDefaultLevel(Ec.info);function mi(i){const e=Wa.getLogger(i);return e.setDefaultLevel(He.getLevel()),e}const N0=Wa.getLogger("lk-e2ee"),Fr=7e3,O0=[0,300,4*300,9*300,16*300,Fr,Fr,Fr,Fr,Fr];class U0{constructor(e){this._retryDelays=e!==void 0?[...e]:O0}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function F0(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(i,n[s])&&(t[n[s]]=i[n[s]]);return t}function P(i,e,t,n){function s(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(d){try{l(n.next(d))}catch(u){o(u)}}function c(d){try{l(n.throw(d))}catch(u){o(u)}}function l(d){d.done?r(d.value):s(d.value).then(a,c)}l((n=n.apply(i,e||[])).next())})}function Gh(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function gi(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof Gh=="function"?Gh(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=i[r]&&function(o){return new Promise(function(a,c){o=i[r](o),s(a,c,o.done,o.value)})}}function s(r,o,a,c){Promise.resolve(c).then(function(l){r({value:l,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;var qa={exports:{}},Hh;function B0(){if(Hh)return qa.exports;Hh=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(S,C,w){return Function.prototype.apply.call(S,C,w)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function n(y){console&&console.warn&&console.warn(y)}var s=Number.isNaN||function(S){return S!==S};function r(){r.init.call(this)}qa.exports=r,qa.exports.once=p,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(y){if(typeof y!="number"||y<0||s(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");o=y}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||s(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function c(y){return y._maxListeners===void 0?r.defaultMaxListeners:y._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(S){for(var C=[],w=1;w<arguments.length;w++)C.push(arguments[w]);var k=S==="error",_=this._events;if(_!==void 0)k=k&&_.error===void 0;else if(!k)return!1;if(k){var x;if(C.length>0&&(x=C[0]),x instanceof Error)throw x;var R=new Error("Unhandled error."+(x?" ("+x.message+")":""));throw R.context=x,R}var O=_[S];if(O===void 0)return!1;if(typeof O=="function")e(O,this,C);else for(var F=O.length,q=g(O,F),w=0;w<F;++w)e(q[w],this,C);return!0};function l(y,S,C,w){var k,_,x;if(a(C),_=y._events,_===void 0?(_=y._events=Object.create(null),y._eventsCount=0):(_.newListener!==void 0&&(y.emit("newListener",S,C.listener?C.listener:C),_=y._events),x=_[S]),x===void 0)x=_[S]=C,++y._eventsCount;else if(typeof x=="function"?x=_[S]=w?[C,x]:[x,C]:w?x.unshift(C):x.push(C),k=c(y),k>0&&x.length>k&&!x.warned){x.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+String(S)+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=y,R.type=S,R.count=x.length,n(R)}return y}r.prototype.addListener=function(S,C){return l(this,S,C,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(S,C){return l(this,S,C,!0)};function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(y,S,C){var w={fired:!1,wrapFn:void 0,target:y,type:S,listener:C},k=d.bind(w);return k.listener=C,w.wrapFn=k,k}r.prototype.once=function(S,C){return a(C),this.on(S,u(this,S,C)),this},r.prototype.prependOnceListener=function(S,C){return a(C),this.prependListener(S,u(this,S,C)),this},r.prototype.removeListener=function(S,C){var w,k,_,x,R;if(a(C),k=this._events,k===void 0)return this;if(w=k[S],w===void 0)return this;if(w===C||w.listener===C)--this._eventsCount===0?this._events=Object.create(null):(delete k[S],k.removeListener&&this.emit("removeListener",S,w.listener||C));else if(typeof w!="function"){for(_=-1,x=w.length-1;x>=0;x--)if(w[x]===C||w[x].listener===C){R=w[x].listener,_=x;break}if(_<0)return this;_===0?w.shift():v(w,_),w.length===1&&(k[S]=w[0]),k.removeListener!==void 0&&this.emit("removeListener",S,R||C)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(S){var C,w,k;if(w=this._events,w===void 0)return this;if(w.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):w[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete w[S]),this;if(arguments.length===0){var _=Object.keys(w),x;for(k=0;k<_.length;++k)x=_[k],x!=="removeListener"&&this.removeAllListeners(x);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(C=w[S],typeof C=="function")this.removeListener(S,C);else if(C!==void 0)for(k=C.length-1;k>=0;k--)this.removeListener(S,C[k]);return this};function h(y,S,C){var w=y._events;if(w===void 0)return[];var k=w[S];return k===void 0?[]:typeof k=="function"?C?[k.listener||k]:[k]:C?m(k):g(k,k.length)}r.prototype.listeners=function(S){return h(this,S,!0)},r.prototype.rawListeners=function(S){return h(this,S,!1)},r.listenerCount=function(y,S){return typeof y.listenerCount=="function"?y.listenerCount(S):f.call(y,S)},r.prototype.listenerCount=f;function f(y){var S=this._events;if(S!==void 0){var C=S[y];if(typeof C=="function")return 1;if(C!==void 0)return C.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(y,S){for(var C=new Array(S),w=0;w<S;++w)C[w]=y[w];return C}function v(y,S){for(;S+1<y.length;S++)y[S]=y[S+1];y.pop()}function m(y){for(var S=new Array(y.length),C=0;C<S.length;++C)S[C]=y[C].listener||y[C];return S}function p(y,S){return new Promise(function(C,w){function k(x){y.removeListener(S,_),w(x)}function _(){typeof y.removeListener=="function"&&y.removeListener("error",k),C([].slice.call(arguments))}E(y,S,_,{once:!0}),S!=="error"&&T(y,k,{once:!0})})}function T(y,S,C){typeof y.on=="function"&&E(y,"error",S,C)}function E(y,S,C,w){if(typeof y.on=="function")w.once?y.once(S,C):y.on(S,C);else if(typeof y.addEventListener=="function")y.addEventListener(S,function k(_){w.once&&y.removeEventListener(S,k),C(_)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof y)}return qa.exports}var Zn=B0();let Wh=!0,qh=!0;function Br(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function hs(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const c=l=>{const d=t(l);d&&(a.handleEvent?a.handleEvent(d):a(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),s.apply(this,[o,c])};const r=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(a))return r.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[o,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function z0(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Wh=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function V0(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(qh=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function jh(){if(typeof window=="object"){if(Wh)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Mc(i,e){qh&&console.warn(i+" is deprecated, please use "+e+" instead.")}function G0(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Br(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Br(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Br(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=Br(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function $h(i){return Object.prototype.toString.call(i)==="[object Object]"}function Xh(i){return $h(i)?Object.keys(i).reduce(function(e,t){const n=$h(i[t]),s=n?Xh(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function wc(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?wc(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{wc(i,i.get(s),t)})}))}function Kh(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return i.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&r.push(o)}),r.forEach(o=>{i.forEach(a=>{a.type===n&&a.trackId===o.id&&wc(i,a,s)})}),s}const Yh=jh;function Jh(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const d=typeof a[l]=="object"?a[l]:{ideal:a[l]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(d.ideal!==void 0){c.optional=c.optional||[];let h={};typeof d.ideal=="number"?(h[u("min",l)]=d.ideal,c.optional.push(h),h={},h[u("max",l)]=d.ideal,c.optional.push(h)):(h[u("",l)]=d.ideal,c.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",l)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,l)]=d[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(d,u,h){u in d&&!(h in d)&&(d[h]=d[u],delete d[u])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const d=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete a.video.facingMode;let u;if(l.exact==="environment"||l.ideal==="environment"?u=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let f=h.find(g=>u.some(v=>g.label.toLowerCase().includes(v)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=n(a.video),Yh("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return Yh("chrome: "+JSON.stringify(a)),c(a)},r=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){s(a,d=>{t.webkitGetUserMedia(d,c,u=>{l&&l(r(u))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,l=>a(l).then(d=>{if(l.audio&&!d.getAudioTracks().length||l.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(r(d))))}}}function Zh(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Qh(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):r={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.id):r={track:s};const o=new Event("track");o.track=s,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else hs(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function ef(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,c){let l=s.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){r.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function tf(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(o=>o._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>Kh(o,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),hs(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Kh(r,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let s,r,o;return this.getSenders().forEach(a=>{a.track===n&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===n&&(r?o=!0:r=a),a.track===n)),o||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function nf(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(u=>u.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function sf(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return nf(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(u=>this._reverseStreams[u.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const u=new i.MediaStream(d.getTracks());this._streams[d.id]=u,this._reverseStreams[u.id]=d,d=u}n.apply(this,[d])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},i.RTCPeerConnection.prototype.addTrack=function(d,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(v=>v===d))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(v=>v.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const g=this._streams[u.id];if(g)g.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new i.MediaStream([d]);this._streams[u.id]=v,this._reverseStreams[v.id]=u,this.addStream(v)}return this.getSenders().find(v=>v.track===d)};function r(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:d.type,sdp:u})}function o(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:u})}["createOffer","createAnswer"].forEach(function(l){const d=i.RTCPeerConnection.prototype[l],u={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[g=>{const v=r(this,g);h[0].apply(null,[v])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):d.apply(this,arguments).then(g=>r(this,g))}};i.RTCPeerConnection.prototype[l]=u[l]});const a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:r(this,l)}}),i.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(v=>d.track===v)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Ac(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=s[t]})}function rf(i,e){hs(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var af=Object.freeze({__proto__:null,fixNegotiationNeeded:rf,shimAddTrackRemoveTrack:sf,shimAddTrackRemoveTrackWithNative:nf,shimGetSendersWithDtmf:ef,shimGetUserMedia:Jh,shimMediaStream:Zh,shimOnTrack:Qh,shimPeerConnection:Ac,shimSenderReceiverGetStats:tf});function of(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,o){Mc("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),r(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function H0(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function cf(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Rc(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=i.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[r,o,a]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((d,u)=>{c.set(u,Object.assign({},d,{type:t[d.type]||d.type}))})}return c}).then(o,a)}}function lf(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function df(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),hs(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function uf(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Mc("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function hf(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function ff(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const s=n.length>0;s&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:o}=r,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return r})}function pf(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function mf(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function gf(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var vf=Object.freeze({__proto__:null,shimAddTransceiver:ff,shimCreateAnswer:gf,shimCreateOffer:mf,shimGetDisplayMedia:H0,shimGetParameters:pf,shimGetUserMedia:of,shimOnTrack:cf,shimPeerConnection:Rc,shimRTCDataChannel:hf,shimReceiverGetStats:df,shimRemoveStream:uf,shimSenderGetStats:lf});function yf(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o<s;o++)r[o-1]=arguments[o];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function bf(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(r)>=0)return;n._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function _f(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h},e.createAnswer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h};let a=function(c,l,d){const u=s.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u};e.setLocalDescription=a,a=function(c,l,d){const u=r.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.setRemoteDescription=a,a=function(c,l,d){const u=o.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.addIceCandidate=a}function Sf(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(xf(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function xf(i){return i&&i.video!==void 0?Object.assign({},i,{video:Xh(i.video)}):i}function Tf(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const r=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(Mc("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(n.iceServers[o])}n.iceServers=r}return new e(n,s)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Cf(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ef(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Mf(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var wf=Object.freeze({__proto__:null,shimAudioContext:Mf,shimCallbacksAPI:_f,shimConstraints:xf,shimCreateOfferLegacy:Ef,shimGetUserMedia:Sf,shimLocalStreamsAPI:yf,shimRTCIceServerUrls:Tf,shimRemoteStreamsAPI:bf,shimTrackEventTransceiver:Cf}),Pc={exports:{}},Af;function W0(){return Af||(Af=1,(function(i){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
49
49
  `).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
50
50
  m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
51
51
  `)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(s=>s.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const s={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let r=8;r<n.length;r+=2)switch(n[r]){case"raddr":s.relatedAddress=n[r+1];break;case"rport":s.relatedPort=parseInt(n[r+1],10);break;case"tcptype":s.tcpType=n[r+1];break;case"ufrag":s.ufrag=n[r+1],s.usernameFragment=n[r+1];break;default:s[n[r]]===void 0&&(s[n[r]]=n[r+1]);break}return s},e.writeCandidate=function(t){const n=[];n.push(t.foundation);const s=t.component;s==="rtp"?n.push(1):s==="rtcp"?n.push(2):n.push(s),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);const r=t.type;return n.push("typ"),n.push(r),r!=="host"&&t.relatedAddress&&t.relatedPort&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" ");const s={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),s.name=n[0],s.clockRate=parseInt(n[1],10),s.channels=n.length===3?parseInt(n[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
@@ -79,17 +79,17 @@ t=0 0\r
79
79
  `},e.getDirection=function(t,n){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let s=0;s<n.length;s++)if(n[s].length<2||n[s].charAt(1)!=="=")return!1;return!0},i.exports=e})(Pc)),Pc.exports}var Rf=W0(),Bs=I0(Rf),q0=ev({__proto__:null,default:Bs},[Rf]);function ja(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const e=i.RTCIceCandidate;i.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){const s=new e(n),r=Bs.parseCandidate(n.candidate);for(const o in r)o in s||Object.defineProperty(s,o,{value:r[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(n)},i.RTCIceCandidate.prototype=e.prototype,hs(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function kc(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||hs(i,"icecandidate",e=>{if(e.candidate){const t=Bs.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function $a(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const c=Bs.splitSections(a.sdp);return c.shift(),c.some(l=>{const d=Bs.parseMLine(l);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},n=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},s=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(a,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const d=Bs.matchPrefix(a.sdp,"a=max-message-size:");return d.length>0?l=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=n(arguments[0]),l=s(c),d=r(arguments[0],c);let u;l===0&&d===0?u=Number.POSITIVE_INFINITY:l===0||d===0?u=Math.max(l,d):u=Math.min(l,d);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return o.apply(this,arguments)}}function Xa(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,s){const r=n.send;n.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(n.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(n,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},hs(i,"datachannel",n=>(e(n.channel,n.target),n))}function Ic(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const o=new Event("connectionstatechange",s);r.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Dc(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
80
80
  a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
81
81
  `).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
82
- `);i.RTCSessionDescription&&s instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Ka(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Ya(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var j0=Object.freeze({__proto__:null,removeExtmapAllowMixed:Dc,shimAddIceCandidateNullOrEmpty:Ka,shimConnectionState:Ic,shimMaxMessageSize:$a,shimParameterlessSetLocalDescription:Ya,shimRTCIceCandidate:ja,shimRTCIceCandidateRelayProtocol:kc,shimSendThrowTypeError:Xa});function $0(){let{window:i}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=jh,n=G0(i),s={browserDetails:n,commonShim:j0,extractVersion:Br,disableLog:z0,disableWarnings:V0,sdp:q0};switch(n.browser){case"chrome":if(!af||!Ac||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=af,Ka(i,n),Ya(i),Jh(i,n),Zh(i),Ac(i,n),Qh(i),sf(i,n),ef(i),tf(i),rf(i,n),ja(i),kc(i),Ic(i),$a(i,n),Xa(i),Dc(i,n);break;case"firefox":if(!vf||!Rc||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=vf,Ka(i,n),Ya(i),of(i,n),Rc(i,n),cf(i),uf(i),lf(i),df(i),hf(i),ff(i),pf(i),mf(i),gf(i),ja(i),Ic(i),$a(i,n),Xa(i);break;case"safari":if(!wf||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=wf,Ka(i,n),Ya(i),Tf(i),Ef(i),_f(i),yf(i),bf(i),Cf(i),Sf(i),Mf(i),ja(i),kc(i),$a(i,n),Xa(i),Dc(i,n);break;default:t("Unsupported browser!");break}return s}$0({window:typeof window>"u"?void 0:window});class gn extends Promise{constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}const X0=/version\/(\d+(\.?_?\d+)+)/i;let Lc;function vn(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Lc===void 0||e){const n=K0.find(s=>{let{test:r}=s;return r.test(t)});Lc=n==null?void 0:n.describe(t)}return Lc}const K0=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:Ja(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Nc(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:Ja(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Nc(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:Ja(X0,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:Nc(i)}}}];function Ja(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}function Nc(i){return i.includes("mac os")?Ja(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var Y0="2.17.0";const J0=Y0,Z0=16;class Qn extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var gt;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.ServerUnreachable=1]="ServerUnreachable",i[i.InternalError=2]="InternalError",i[i.Cancelled=3]="Cancelled",i[i.LeaveRequest=4]="LeaveRequest",i[i.Timeout=5]="Timeout",i[i.WebSocket=6]="WebSocket",i[i.ServiceNotFound=7]="ServiceNotFound"})(gt||(gt={}));class Ne extends Qn{constructor(e,t,n,s){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=s,this.reasonName=gt[t]}static notAllowed(e,t,n){return new Ne(e,gt.NotAllowed,t,n)}static timeout(e){return new Ne(e,gt.Timeout)}static leaveRequest(e,t){return new Ne(e,gt.LeaveRequest,void 0,t)}static internal(e,t){return new Ne(e,gt.InternalError,void 0,t)}static cancelled(e){return new Ne(e,gt.Cancelled)}static serverUnreachable(e,t){return new Ne(e,gt.ServerUnreachable,t)}static websocket(e,t,n){return new Ne(e,gt.WebSocket,t,n)}static serviceNotFound(e,t){return new Ne(e,gt.ServiceNotFound,void 0,t)}}class Oc extends Qn{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class vi extends Qn{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Q0 extends Qn{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Ut extends Qn{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class zs extends Qn{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Pf extends Qn{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class kf extends Qn{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Cc[t]}}var ln;(function(i){i[i.AlreadyOpened=0]="AlreadyOpened",i[i.AbnormalEnd=1]="AbnormalEnd",i[i.DecodeFailed=2]="DecodeFailed",i[i.LengthExceeded=3]="LengthExceeded",i[i.Incomplete=4]="Incomplete",i[i.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",i[i.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(ln||(ln={}));class In extends Qn{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=ln[t]}}class Vs extends Qn{constructor(e){super(18,e),this.name="SignalReconnectError"}}var Za;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(Za||(Za={})),(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(Za||(Za={}));class Jt{}Jt.setTimeout=function(){return setTimeout(...arguments)},Jt.setInterval=function(){return setInterval(...arguments)},Jt.clearTimeout=function(){return clearTimeout(...arguments)},Jt.clearInterval=function(){return clearInterval(...arguments)};var ne;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.Moved="moved",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.ParticipantAttributesChanged="participantAttributesChanged",i.ParticipantActive="participantActive",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged",i.ChatMessage="chatMessage",i.LocalTrackSubscribed="localTrackSubscribed",i.MetricsReceived="metricsReceived"})(ne||(ne={}));var le;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackCpuConstrained="localTrackCpuConstrained",i.LocalSenderCreated="localSenderCreated",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.TrackCpuConstrained="trackCpuConstrained",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded",i.AttributesChanged="attributesChanged",i.LocalTrackSubscribed="localTrackSubscribed",i.ChatMessage="chatMessage",i.Active="active"})(le||(le={}));var ce;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackSubscribed="localTrackSubscribed",i.Offline="offline",i.SignalRequestResponse="signalRequestResponse",i.SignalConnected="signalConnected",i.RoomMoved="roomMoved"})(ce||(ce={}));var ae;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.CpuConstrained="cpuConstrained",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed",i.TrackProcessorUpdate="trackProcessorUpdate",i.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",i.TranscriptionReceived="transcriptionReceived",i.TimeSyncUpdate="timeSyncUpdate",i.PreConnectBufferFlushed="preConnectBufferFlushed"})(ae||(ae={}));function ey(i){return typeof i>"u"?i:typeof structuredClone=="function"?typeof i=="object"&&i!==null?structuredClone(Object.assign({},i)):structuredClone(i):JSON.parse(JSON.stringify(i))}class ft{constructor(e,t,n,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const ty=["vp8","h264"],ny=["vp8","h264","vp9","av1","h265"];function iy(i){return!!ty.find(e=>e===i)}const sy=iy;var If;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(If||(If={}));var Uc;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(Uc||(Uc={}));const zr={h90:new ft(160,90,9e4,20),h180:new ft(320,180,16e4,20),h216:new ft(384,216,18e4,20),h360:new ft(640,360,45e4,20),h540:new ft(960,540,8e5,25),h720:new ft(1280,720,17e5,30),h1080:new ft(1920,1080,3e6,30),h1440:new ft(2560,1440,5e6,30),h2160:new ft(3840,2160,8e6,30)},Fc={h120:new ft(160,120,7e4,20),h180:new ft(240,180,125e3,20),h240:new ft(320,240,14e4,20),h360:new ft(480,360,33e4,20),h480:new ft(640,480,5e5,20),h540:new ft(720,540,6e5,25),h720:new ft(960,720,13e5,30),h1080:new ft(1440,1080,23e5,30),h1440:new ft(1920,1440,38e5,30)},Bc={h360fps3:new ft(640,360,2e5,3,"medium"),h360fps15:new ft(640,360,4e5,15,"medium"),h720fps5:new ft(1280,720,8e5,5,"medium"),h720fps15:new ft(1280,720,15e5,15,"medium"),h720fps30:new ft(1280,720,2e6,30,"medium"),h1080fps15:new ft(1920,1080,25e5,15,"medium"),h1080fps30:new ft(1920,1080,5e6,30,"medium"),original:new ft(0,0,7e6,30,"medium")};function Df(i,e,t){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=Of(i??{}),d=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(zc(h.audio,e),(n=(r=h.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=c??d)),h.video&&(zc(h.video,t),(s=(o=h.video).deviceId)!==null&&s!==void 0||(o.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=l??u)),h}function zc(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Vc(i){var e,t,n,s;const r={};if(i.video)if(typeof i.video=="object"){const o={},a=o,c=i.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":zc(a,c.resolution);break;default:a[l]=c[l]}}),r.video=o,(e=(n=r.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else r.video=i.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return i.audio?typeof i.audio=="object"?(r.audio=i.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Lf(i){return P(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const n=Nf();if(n){const s=n.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,o=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield Zt(t),s.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return n.close(),!c}return!1})()})}function Nf(){var i;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((i=window.document)===null||i===void 0)&&i.body)){const n=()=>P(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",n)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",n))}),window.document.body.addEventListener("click",n)}return t}}function ry(i){return i==="audioinput"?Z.Source.Microphone:i==="videoinput"?Z.Source.Camera:Z.Source.Unknown}function Gc(i){return i===Z.Source.Microphone?"audioinput":i===Z.Source.Camera?"videoinput":void 0}function ay(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,ps()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio,preferCurrentTab:i.preferCurrentTab}}function Vr(i){return i.split("/")[1].toLowerCase()}function oy(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new bc({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function Je(i){return"mediaStreamTrack"in i?{trackID:i.sid,source:i.source,muted:i.isMuted,enabled:i.mediaStreamTrack.enabled,kind:i.kind,streamID:i.mediaStreamID,streamTrackID:i.mediaStreamTrack.id}:{trackID:i.trackSid,enabled:i.isEnabled,muted:i.isMuted,trackInfo:Object.assign({mimeType:i.mimeType,name:i.trackName,encrypted:i.isEncrypted,kind:i.kind,source:i.source},i.track?Je(i.track):{})}}function cy(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function ly(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(i)],s={};for(const r of n)i[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Of(i){const e=Object.assign({},i);let t,n;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:ey(e)}}function dy(i){switch(i){case Bt.CAMERA:return Z.Source.Camera;case Bt.MICROPHONE:return Z.Source.Microphone;case Bt.SCREEN_SHARE:return Z.Source.ScreenShare;case Bt.SCREEN_SHARE_AUDIO:return Z.Source.ScreenShareAudio;default:return Z.Source.Unknown}}function Uf(i,e){return i.width*i.height<e.width*e.height}function uy(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}const hy=5e3,Gr=[];var En;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(En||(En={}));class Z extends Zn.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Z.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=He,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),hy):this.handleAppVisibilityChanged()},this.log=mi((s=n.loggerName)!==null&&s!==void 0?s:Vn.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Z.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Je(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Z.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===Z.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Gr.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Gr.splice(Gr.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Gs(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?ae.AudioPlaybackStarted:ae.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?ae.AudioPlaybackFailed:ae.VideoPlaybackFailed,r):r.name==="AbortError"?He.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):He.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&n.some(o=>o.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(ae.ElementAttached,e),e}detach(e){try{if(e){Hs(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(ae.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Hs(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(ae.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=mi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Gr.forEach(n=>{n.parentElement||(t=!1)}),t&&Gr.push(e)}}handleAppVisibilityChanged(){return P(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===Z.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){yn()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){yn()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Gs(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(s=>{t.removeTrack(s)}),t.addTrack(i)),(!ps()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(ps()||fs())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Hs(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function s(l){switch(l){case e.Audio:return Fn.AUDIO;case e.Video:return Fn.VIDEO;default:return Fn.DATA}}i.kindToProto=s;function r(l){switch(l){case Fn.AUDIO:return e.Audio;case Fn.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function o(l){switch(l){case t.Camera:return Bt.CAMERA;case t.Microphone:return Bt.MICROPHONE;case t.ScreenShare:return Bt.SCREEN_SHARE;case t.ScreenShareAudio:return Bt.SCREEN_SHARE_AUDIO;default:return Bt.UNKNOWN}}i.sourceToProto=o;function a(l){switch(l){case Bt.CAMERA:return t.Camera;case Bt.MICROPHONE:return t.Microphone;case Bt.SCREEN_SHARE:return t.ScreenShare;case Bt.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=a;function c(l){switch(l){case vc.ACTIVE:return n.Active;case vc.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(Z||(Z={}));const fy="|",Ff="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function py(i){const e=i.split(fy);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function Zt(i){return new gn(e=>Jt.setTimeout(e,i))}function Hc(){return"addTransceiver"in RTCPeerConnection.prototype}function Wc(){return"addTrack"in RTCPeerConnection.prototype}function my(){if(!("getCapabilities"in RTCRtpSender)||ps()||fs())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function gy(){if(!("getCapabilities"in RTCRtpSender)||fs())return!1;if(ps()){const t=vn();if(t!=null&&t.version&&ti(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&ti(t.osVersion,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Gn(i){return i==="av1"||i==="vp9"}function qc(i){return!document||Hr()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function vy(){return typeof RTCPeerConnection>"u"?!1:Hc()||Wc()}function fs(){var i;return((i=vn())===null||i===void 0?void 0:i.name)==="Firefox"}function Bf(){const i=vn();return!!i&&i.name==="Chrome"&&i.os!=="iOS"}function ps(){var i;return((i=vn())===null||i===void 0?void 0:i.name)==="Safari"}function Hr(){const i=vn();return(i==null?void 0:i.name)==="Safari"||(i==null?void 0:i.os)==="iOS"}function yy(){const i=vn();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&ti(i.osVersion,"17")>=0}function by(i){return i||(i=vn()),(i==null?void 0:i.name)==="Safari"&&ti(i.version,"18.3")>0||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&ti(i.osVersion,"18.3")>0}function zf(){var i,e;return yn()?(e=(i=navigator.userAgentData)===null||i===void 0?void 0:i.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function _y(){const i=vn(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&ti(i.osVersion,e)>=0?!0:i.name==="Safari"&&ti(i.version,e)>=0}function yn(){return typeof document<"u"}function ei(){return navigator.product=="ReactNative"}function Ws(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function jc(i){return Ws(i)?i.hostname.split(".")[0]:null}function Vf(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Gf(){if(!ei())return;let i=Vf();if(i)return i.platform}function Hf(){if(yn())return window.devicePixelRatio;if(ei()){let i=Vf();if(i)return i.devicePixelRatio}return 1}function ti(i,e){const t=i.split("."),n=e.split("."),s=Math.min(t.length,n.length);for(let r=0;r<s;++r){const o=parseInt(t[r],10),a=parseInt(n[r],10);if(o>a)return 1;if(o<a)return-1;if(r===s-1&&o===a)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function Sy(i){for(const e of i)e.target.handleResize(e)}function xy(i){for(const e of i)e.target.handleVisibilityChanged(e)}let $c=null;const Wf=()=>($c||($c=new ResizeObserver(Sy)),$c);let Xc=null;const qf=()=>(Xc||(Xc=new IntersectionObserver(xy,{root:null,rootMargin:"0px"})),Xc);function Ty(){var i;const e=new Th({sdk:Ch.JS,protocol:Z0,version:J0});return ei()&&(e.os=(i=Gf())!==null&&i!==void 0?i:""),e}function jf(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=i,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(i/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=t,a}let Wr;function Kc(){if(!Wr){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[Wr]=n.stream.getAudioTracks(),!Wr)throw Error("Could not get empty media stream audio track");Wr.enabled=!1}return Wr.clone()}class Dn{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,s)=>P(this,void 0,void 0,function*(){this.resolve=n,this.reject=s,e&&(yield e(n,s))})).finally(()=>{var n;this._isResolved=!0,(n=this.onFinally)===null||n===void 0||n.call(this)})}}function Cy(i){return ny.includes(i)}function Hi(i){if(typeof i=="string"||typeof i=="number")return i;if(Array.isArray(i))return i[0];if(i.exact!==void 0)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal!==void 0)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function Ey(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function qr(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function My(i,e){return i.segments.map(t=>{let{id:n,text:s,language:r,startTime:o,endTime:a,final:c}=t;var l;const d=(l=e.get(n))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(n):e.set(n,d),{id:n,text:s,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:r,firstReceivedTime:d,lastReceivedTime:u}})}function wy(i){const{id:e,timestamp:t,message:n,editTimestamp:s}=i;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}function $f(i){switch(i.reason){case gt.LeaveRequest:return i.context;case gt.Cancelled:return Bn.CLIENT_INITIATED;case gt.NotAllowed:return Bn.USER_REJECTED;case gt.ServerUnreachable:return Bn.JOIN_FAILURE;default:return Bn.UNKNOWN_REASON}}function Qa(i){return i!==void 0?Number(i):void 0}function ms(i){return i!==void 0?BigInt(i):void 0}function qs(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function ni(i){return!!i&&i.kind==Z.Kind.Audio}function Wi(i){return!!i&&i.kind==Z.Kind.Video}function qi(i){return qs(i)&&Wi(i)}function yi(i){return qs(i)&&ni(i)}function Yc(i){return!!i&&!i.isLocal}function Ay(i){return!!i&&!i.isLocal}function Jc(i){return Yc(i)&&Wi(i)}function Ry(i){return i.isLocal}function Py(i,e){const t=[];let n=new TextEncoder().encode(i);for(;n.length>e;){let s=e;for(;s>0;){const r=n[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(n.slice(0,s)),n=n.slice(s)}return n.length>0&&t.push(n),t}function ky(i){var e;const t=i.get("Cache-Control");if(t){const n=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(n)return parseInt(n,10)}}function Iy(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const n=Dy(i,e);return t?n:Zc(n,"v1")}function Dy(i,e){const t=new URL(Ey(i));return e.forEach((n,s)=>{t.searchParams.set(s,n)}),Zc(t,"rtc")}function Ly(i){const e=new URL(qr(i));return Zc(e,"validate")}function Xf(i){return i.endsWith("/")?i:"".concat(i,"/")}function Zc(i,e){return i.pathname="".concat(Xf(i.pathname)).concat(e),i}function Kf(i){if(typeof i=="string")return Ph.fromJson(JSON.parse(i),{ignoreUnknownFields:!0});if(i instanceof ArrayBuffer)return Ph.fromBinary(new Uint8Array(i));throw new Error("could not decode websocket message: ".concat(typeof i))}function Ny(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(i instanceof AbortSignal))return e;const t=i.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const Oy=10,jr="lk_e2ee",Uy={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Oy,keyringSize:16};var ji;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(ji||(ji={}));var Yf;(function(i){i.KeyRatcheted="keyRatcheted"})(Yf||(Yf={}));var $i;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})($i||($i={}));var Jf;(function(i){i.Error="cryptorError"})(Jf||(Jf={}));function Fy(){return By()||Qc()}function Qc(){return typeof window.RTCRtpScriptTransform<"u"}function By(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function zy(i){var e,t,n,s,r;if(((e=i.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=i.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((n=i.value)===null||n===void 0?void 0:n.case)!=="speaker"&&((s=i.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=i.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new gh({value:i.value})}class IM extends Zn.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n,s)=>{He.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Uy),e),this.on(ji.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const s={key:e,participantIdentity:t,keyIndex:n};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(n??0),s),this.emit(ji.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(ji.RatchetRequest,e,t)}}var Zf;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(Zf||(Zf={}));class Vy extends Zn.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=n=>{var s,r;const{kind:o,data:a}=n.data;switch(o){case"error":if(He.error(a.error.message),a.uuid){const d=this.decryptDataRequests.get(a.uuid);if(d!=null&&d.reject){d.reject(a.error);break}const u=this.encryptDataRequests.get(a.uuid);if(u!=null&&u.reject){u.reject(a.error);break}}this.emit($i.EncryptionError,a.error,a.participantIdentity);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(d=>{this.postKey(d)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(d=>{this.postKey(d)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit($i.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const d=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!d)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit($i.ParticipantEncryptionStatusChanged,a.enabled,d)}break;case"ratchetKey":this.keyProvider.emit(ji.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(a.uuid);c!=null&&c.resolve&&c.resolve(a);break;case"encryptDataResponse":const l=this.encryptDataRequests.get(a.uuid);l!=null&&l.resolve&&l.resolve(a);break}},this.onWorkerError=n=>{He.error("e2ee worker encountered an error:",{error:n.error}),this.emit($i.EncryptionError,n.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Fy())throw new Oc("tried to setup end-to-end encryption on an unsupported browser");if(He.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:N0.getLevel()}};this.worker&&(He.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){He.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?He.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(ce.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(ne.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==Ht.NONE,s.identity)),e.on(ne.ConnectionStateChanged,n=>{n===ot.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==Ht.NONE,s.identity)})})}).on(ne.TrackUnsubscribed,(n,s,r)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(ne.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(ne.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(le.LocalSenderCreated,(n,s)=>P(this,void 0,void 0,function*(){this.setupE2EESender(s,n)})),e.localParticipant.on(le.LocalTrackPublished,n=>{if(!Wi(n.track)||!Hr())return;const s={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:Vr(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(ji.SetKey,n=>this.postKey(n)).on(ji.RatchetRequest,(n,s)=>this.postRatchetRequest(n,s))}encryptData(e){return P(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Dn;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(n),s.promise})}handleEncryptedData(e,t,n,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:s}},a=new Dn;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage(o),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Vr(n.mimeType):void 0)}}setupE2EESender(e,t){if(!qs(e)||!t){t||He.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return P(this,void 0,void 0,function*(){if(this.worker){if(Qc()&&!Bf()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(jr in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,o=e.readableStream;if(!r||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:r,trackId:t,codec:s,participantIdentity:n,isReuse:jr in e}};this.worker.postMessage(a,[o,r])}e[jr]=!0}})}handleSender(e,t,n){var s;if(!(jr in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Qc()&&!Bf()){He.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{He.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[r.readable,r.writable])}e[jr]=!0}}}const Gy=500,Hy=15e3;class js{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new js),this._instance}addFailedConnectionAttempt(e){var t;const n=new URL(e),s=jc(n);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,Zt(Math.min(Gy*Math.pow(2,r),Hy)))}getBackOffPromise(e){const t=new URL(e),n=t&&jc(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&jc(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}js._instance=null;const el="default";class $t{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new $t),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=$t.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){He.debug("awaiting getUserMedia promise");try{t?yield $t.userMediaPromiseMap.get(t):yield Promise.all($t.userMediaPromiseMap.values())}catch{He.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(s&&!(ps()&&n.hasDeviceInUse(t))&&(o.filter(c=>c.kind===t).length===0||o.some(c=>{const l=c.label==="",d=t?c.kind===t:!0;return l&&d}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return n._previousDevices=o,t&&(o=o.filter(a=>a.kind===t)),o})()})}normalizeDeviceId(e,t,n){return P(this,void 0,void 0,function*(){if(t!==el)return t;const s=yield this.getDevices(e),r=s.find(a=>a.deviceId===el);if(!r){He.warn("could not reliably determine default device");return}const o=s.find(a=>a.deviceId!==el&&a.groupId===(n??r.groupId));if(!o){He.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?$t.userMediaPromiseMap.has(e):$t.userMediaPromiseMap.size>0}}$t.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],$t.userMediaPromiseMap=new Map;var $r;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})($r||($r={}));class Wy{constructor(){this.pendingTasks=new Map,this.taskMutex=new on,this.nextTaskIndex=0}run(e){return P(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:$r.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=$r.RUNNING,yield e()}finally{t.status=$r.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return P(this,void 0,void 0,function*(){return this.run(()=>P(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class qy{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,s;if(!((n=t.signal)===null||n===void 0)&&n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const o=function(){let{closeCode:a,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(a,c)};this.opened=new gn((a,c)=>{const l=()=>{c(Ne.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{a({readable:new ReadableStream({start(d){r.onmessage=u=>{let{data:h}=u;return d.enqueue(h)},r.onerror=u=>d.error(u)},cancel:o}),writable:new WritableStream({write(d){r.send(d)},abort(){r.close()},close:o}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),this.closed=new gn((a,c)=>{const l=()=>P(this,void 0,void 0,function*(){const d=new gn(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{h(f)},{once:!0})}),u=yield gn.race([Zt(250),d]);u?a(u):c(Ne.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=d=>{let{code:u,reason:h}=d;a({closeCode:u,reason:h}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=o}}const jy=["syncState","trickle","offer","answer","simulate","leave"];function $y(i){const e=jy.indexOf(i.case)>=0;return He.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var vt;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(vt||(vt={}));const Xy=250;class tl{get currentState(){return this.state}get isDisconnected(){return this.state===vt.DISCONNECTING||this.state===vt.DISCONNECTED}get isEstablishingConnection(){return this.state===vt.CONNECTING||this.state===vt.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;this.rtt=0,this.state=vt.DISCONNECTED,this.log=He,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=mi((n=t.loggerName)!==null&&n!==void 0?n:Vn.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Wy,this.queuedRequests=[],this.closingLock=new on,this.connectionLock=new on,this.state=vt.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return l.state=vt.CONNECTING,l.options=a,yield l.connect(r,o,a,c,d)})()})}reconnect(e,t,n,s){return P(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=vt.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const u=yield l.connectionLock.lock();l.connectOptions=a,l.useV0SignalPath=d;const h=Ty(),f=d?Ky(o,h,a):Yy(o,h,a),g=Iy(r,f,d).toString(),v=Ly(g).toString();return new Promise((m,p)=>P(l,void 0,void 0,function*(){var T,E;try{let y=!1;const S=x=>P(this,void 0,void 0,function*(){if(y)return;y=!0;const R=x instanceof Event?x.currentTarget:x,O=Ny(R,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(O)).catch(F=>{this.log.error(F),this.close()}):this.close(),C(),p(Ne.cancelled(O))});c==null||c.addEventListener("abort",S);const C=()=>{clearTimeout(w),c==null||c.removeEventListener("abort",S)},w=setTimeout(()=>{S(Ne.timeout("room connection has timed out (signal)"))},a.websocketTimeout),k=(x,R)=>{this.handleSignalConnected(x,w,R)},_=new URL(g);_.searchParams.has("access_token")&&_.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(_),Object.assign({reconnect:a.reconnect,reconnectReason:a.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new qy(g);try{this.ws.closed.then(G=>{var W;this.isEstablishingConnection&&p(Ne.internal("Websocket got closed during a (re)connection attempt: ".concat(G.reason))),G.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:G.reason,code:G.closeCode,wasClean:G.closeCode===1e3,state:this.state})),this.state===vt.CONNECTED&&this.handleOnClose((W=G.reason)!==null&&W!==void 0?W:"Unexpected WS error"))}).catch(G=>{this.isEstablishingConnection&&p(Ne.internal("Websocket error during a (re)connection attempt: ".concat(G)))});const x=yield this.ws.opened.catch(G=>P(this,void 0,void 0,function*(){if(this.state!==vt.CONNECTED){this.state=vt.DISCONNECTED,clearTimeout(w);const W=yield this.handleConnectionError(G,v);p(W);return}this.handleWSError(G),p(G)}));if(clearTimeout(w),!x)return;const R=x.readable.getReader();this.streamWriter=x.writable.getWriter();const O=yield R.read();if(R.releaseLock(),!O.value)throw Ne.internal("no message received as first message");const F=Kf(O.value),q=this.validateFirstMessage(F,(T=a.reconnect)!==null&&T!==void 0?T:!1);if(!q.isValid){p(q.error);return}((E=F.message)===null||E===void 0?void 0:E.case)==="join"&&(this.pingTimeoutDuration=F.message.value.pingTimeout,this.pingIntervalDuration=F.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));const K=q.shouldProcessFirstMessage?F:void 0;k(x,K),m(q.response)}catch(x){p(x)}finally{C()}}finally{u()}}))})()})}startReadingLoop(e,t){return P(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Zt(this.signalLatency));const{done:n,value:s}=yield e.read();if(n)break;const r=Kf(s);this.handleSignalResponse(r)}})}close(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([vt.DISCONNECTING||vt.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=vt.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,Zt(Xy)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=vt.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:$s(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:$s(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Ba({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new za({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const a=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new Sc({requestId:a,metadata:n,name:s,attributes:o})}),a})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Dh({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Oh({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:wt.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Bh({timestamp:wt.parse(Date.now()),rtt:wt.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new _c({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ga({reason:Bn.CLIENT_INITIATED,action:Fs.DISCONNECT})})}sendRequest(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!$y(t)&&n.state===vt.RECONNECTING){n.queuedRequests.push(()=>P(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield n.requestQueue.flush()),n.signalLatency&&(yield Zt(n.signalLatency)),n.isDisconnected){n.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!n.streamWriter){n.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),n.logContext);return}const o=new a0({message:t});try{n.useJSON?yield n.streamWriter.write(o.toJsonString()):yield n.streamWriter.write(o.toBinary())}catch(a){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:a}))}})()})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const o=Qf(s.value);this.onAnswer&&this.onAnswer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const o=Qf(s.value);this.onOffer&&this.onOffer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const o=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(o,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=s.value.speakers)!==null&&n!==void 0?n:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return P(this,void 0,void 0,function*(){if(this.state===vt.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Jt.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&&Jt.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=Jt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Jt.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=vt.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){var n,s,r,o,a;return((n=e.message)===null||n===void 0?void 0:n.case)==="join"?{isValid:!0,response:e.message.value}:this.state===vt.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((o=e.message)===null||o===void 0?void 0:o.case)==="leave"?{isValid:!1,error:Ne.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:Ne.internal("Unexpected first message")}:{isValid:!1,error:Ne.internal("did not receive join response, got ".concat((a=e.message)===null||a===void 0?void 0:a.case," instead"))}}handleConnectionError(e,t){return P(this,void 0,void 0,function*(){try{const n=yield fetch(t);switch(n.status){case 404:return Ne.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield n.text();return Ne.notAllowed(s,n.status);default:break}return e instanceof Ne?e:Ne.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof Ne?n:Ne.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}})}}function Qf(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function $s(i,e){return new Gi({sdp:i.sdp,type:i.type,id:e})}function Ky(i,e,t){var n;const s=new URLSearchParams;return s.set("access_token",i),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",ei()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&s.set("network",navigator.connection.type),s}function Yy(i,e,t){const n=new URLSearchParams;n.set("access_token",i);const s=new A0({clientInfo:e,connectionSettings:new zh({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new R0({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),n}class ep{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Jy{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();const s=n+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[s,r]of n.entries())t.push(e(r,s,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var Hn={},nl={},il={exports:{}},tp;function sl(){if(tp)return il.exports;tp=1;var i=il.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(i).forEach(function(e){var t=i[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),il.exports}var np;function Zy(){return np||(np=1,(function(i){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,c,l,d){if(d&&!l)c[d]=e(a[1]);else for(var u=0;u<l.length;u+=1)a[u+1]!=null&&(c[l[u]]=e(a[u+1]))},n=function(a,c,l){var d=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:d&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:d?c[a.name]:c;t(l.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},s=sl(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(a){var c={},l=[],d=c;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var g=0;g<(s[h]||[]).length;g+=1){var v=s[h][g];if(v.reg.test(f))return n(v,d,f)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};i.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(a){return a.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},i.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},i.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}})(nl)),nl}var rl,ip;function Qy(){if(ip)return rl;ip=1;var i=sl(),e=/%[sdv%]/g,t=function(o){var a=1,c=arguments,l=c.length;return o.replace(e,function(d){if(a>=l)return d;var u=c[a];switch(a+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},n=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,d=[o+"="+l];if(a.names)for(var u=0;u<a.names.length;u+=1){var h=a.names[u];a.name?d.push(c[a.name][h]):d.push(c[a.names[u]])}else d.push(c[a.name]);return t.apply(null,d)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return rl=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=a.outerOrder||s,l=a.innerOrder||r,d=[];return c.forEach(function(u){i[u].forEach(function(h){h.name in o&&o[h.name]!=null?d.push(n(u,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){d.push(n(u,h,f))})})}),o.media.forEach(function(u){d.push(n("m",i.m[0],u)),l.forEach(function(h){i[h].forEach(function(f){f.name in u&&u[f.name]!=null?d.push(n(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(g){d.push(n(h,f,g))})})})}),d.join(`\r
82
+ `);i.RTCSessionDescription&&s instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Ka(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Ya(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var j0=Object.freeze({__proto__:null,removeExtmapAllowMixed:Dc,shimAddIceCandidateNullOrEmpty:Ka,shimConnectionState:Ic,shimMaxMessageSize:$a,shimParameterlessSetLocalDescription:Ya,shimRTCIceCandidate:ja,shimRTCIceCandidateRelayProtocol:kc,shimSendThrowTypeError:Xa});function $0(){let{window:i}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=jh,n=G0(i),s={browserDetails:n,commonShim:j0,extractVersion:Br,disableLog:z0,disableWarnings:V0,sdp:q0};switch(n.browser){case"chrome":if(!af||!Ac||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=af,Ka(i,n),Ya(i),Jh(i,n),Zh(i),Ac(i,n),Qh(i),sf(i,n),ef(i),tf(i),rf(i,n),ja(i),kc(i),Ic(i),$a(i,n),Xa(i),Dc(i,n);break;case"firefox":if(!vf||!Rc||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=vf,Ka(i,n),Ya(i),of(i,n),Rc(i,n),cf(i),uf(i),lf(i),df(i),hf(i),ff(i),pf(i),mf(i),gf(i),ja(i),Ic(i),$a(i,n),Xa(i);break;case"safari":if(!wf||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=wf,Ka(i,n),Ya(i),Tf(i),Ef(i),_f(i),yf(i),bf(i),Cf(i),Sf(i),Mf(i),ja(i),kc(i),$a(i,n),Xa(i),Dc(i,n);break;default:t("Unsupported browser!");break}return s}$0({window:typeof window>"u"?void 0:window});class vn extends Promise{constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}const X0=/version\/(\d+(\.?_?\d+)+)/i;let Lc;function yn(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Lc===void 0||e){const n=K0.find(s=>{let{test:r}=s;return r.test(t)});Lc=n==null?void 0:n.describe(t)}return Lc}const K0=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:Ja(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Nc(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:Ja(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Nc(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:Ja(X0,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:Nc(i)}}}];function Ja(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}function Nc(i){return i.includes("mac os")?Ja(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var Y0="2.17.0";const J0=Y0,Z0=16;class Qn extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var gt;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.ServerUnreachable=1]="ServerUnreachable",i[i.InternalError=2]="InternalError",i[i.Cancelled=3]="Cancelled",i[i.LeaveRequest=4]="LeaveRequest",i[i.Timeout=5]="Timeout",i[i.WebSocket=6]="WebSocket",i[i.ServiceNotFound=7]="ServiceNotFound"})(gt||(gt={}));class Ne extends Qn{constructor(e,t,n,s){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=s,this.reasonName=gt[t]}static notAllowed(e,t,n){return new Ne(e,gt.NotAllowed,t,n)}static timeout(e){return new Ne(e,gt.Timeout)}static leaveRequest(e,t){return new Ne(e,gt.LeaveRequest,void 0,t)}static internal(e,t){return new Ne(e,gt.InternalError,void 0,t)}static cancelled(e){return new Ne(e,gt.Cancelled)}static serverUnreachable(e,t){return new Ne(e,gt.ServerUnreachable,t)}static websocket(e,t,n){return new Ne(e,gt.WebSocket,t,n)}static serviceNotFound(e,t){return new Ne(e,gt.ServiceNotFound,void 0,t)}}class Oc extends Qn{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class vi extends Qn{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Q0 extends Qn{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Ut extends Qn{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class zs extends Qn{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Pf extends Qn{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class kf extends Qn{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Cc[t]}}var dn;(function(i){i[i.AlreadyOpened=0]="AlreadyOpened",i[i.AbnormalEnd=1]="AbnormalEnd",i[i.DecodeFailed=2]="DecodeFailed",i[i.LengthExceeded=3]="LengthExceeded",i[i.Incomplete=4]="Incomplete",i[i.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",i[i.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(dn||(dn={}));class In extends Qn{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=dn[t]}}class Vs extends Qn{constructor(e){super(18,e),this.name="SignalReconnectError"}}var Za;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(Za||(Za={})),(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(Za||(Za={}));class Zt{}Zt.setTimeout=function(){return setTimeout(...arguments)},Zt.setInterval=function(){return setInterval(...arguments)},Zt.clearTimeout=function(){return clearTimeout(...arguments)},Zt.clearInterval=function(){return clearInterval(...arguments)};var ne;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.Moved="moved",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.ParticipantAttributesChanged="participantAttributesChanged",i.ParticipantActive="participantActive",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged",i.ChatMessage="chatMessage",i.LocalTrackSubscribed="localTrackSubscribed",i.MetricsReceived="metricsReceived"})(ne||(ne={}));var de;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackCpuConstrained="localTrackCpuConstrained",i.LocalSenderCreated="localSenderCreated",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.TrackCpuConstrained="trackCpuConstrained",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded",i.AttributesChanged="attributesChanged",i.LocalTrackSubscribed="localTrackSubscribed",i.ChatMessage="chatMessage",i.Active="active"})(de||(de={}));var le;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackSubscribed="localTrackSubscribed",i.Offline="offline",i.SignalRequestResponse="signalRequestResponse",i.SignalConnected="signalConnected",i.RoomMoved="roomMoved"})(le||(le={}));var ae;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.CpuConstrained="cpuConstrained",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed",i.TrackProcessorUpdate="trackProcessorUpdate",i.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",i.TranscriptionReceived="transcriptionReceived",i.TimeSyncUpdate="timeSyncUpdate",i.PreConnectBufferFlushed="preConnectBufferFlushed"})(ae||(ae={}));function ey(i){return typeof i>"u"?i:typeof structuredClone=="function"?typeof i=="object"&&i!==null?structuredClone(Object.assign({},i)):structuredClone(i):JSON.parse(JSON.stringify(i))}class ft{constructor(e,t,n,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const ty=["vp8","h264"],ny=["vp8","h264","vp9","av1","h265"];function iy(i){return!!ty.find(e=>e===i)}const sy=iy;var If;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(If||(If={}));var Uc;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(Uc||(Uc={}));const zr={h90:new ft(160,90,9e4,20),h180:new ft(320,180,16e4,20),h216:new ft(384,216,18e4,20),h360:new ft(640,360,45e4,20),h540:new ft(960,540,8e5,25),h720:new ft(1280,720,17e5,30),h1080:new ft(1920,1080,3e6,30),h1440:new ft(2560,1440,5e6,30),h2160:new ft(3840,2160,8e6,30)},Fc={h120:new ft(160,120,7e4,20),h180:new ft(240,180,125e3,20),h240:new ft(320,240,14e4,20),h360:new ft(480,360,33e4,20),h480:new ft(640,480,5e5,20),h540:new ft(720,540,6e5,25),h720:new ft(960,720,13e5,30),h1080:new ft(1440,1080,23e5,30),h1440:new ft(1920,1440,38e5,30)},Bc={h360fps3:new ft(640,360,2e5,3,"medium"),h360fps15:new ft(640,360,4e5,15,"medium"),h720fps5:new ft(1280,720,8e5,5,"medium"),h720fps15:new ft(1280,720,15e5,15,"medium"),h720fps30:new ft(1280,720,2e6,30,"medium"),h1080fps15:new ft(1920,1080,25e5,15,"medium"),h1080fps30:new ft(1920,1080,5e6,30,"medium"),original:new ft(0,0,7e6,30,"medium")};function Df(i,e,t){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=Of(i??{}),d=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(zc(h.audio,e),(n=(r=h.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=c??d)),h.video&&(zc(h.video,t),(s=(o=h.video).deviceId)!==null&&s!==void 0||(o.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=l??u)),h}function zc(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Vc(i){var e,t,n,s;const r={};if(i.video)if(typeof i.video=="object"){const o={},a=o,c=i.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":zc(a,c.resolution);break;default:a[l]=c[l]}}),r.video=o,(e=(n=r.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else r.video=i.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return i.audio?typeof i.audio=="object"?(r.audio=i.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Lf(i){return P(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const n=Nf();if(n){const s=n.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,o=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield Qt(t),s.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return n.close(),!c}return!1})()})}function Nf(){var i;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((i=window.document)===null||i===void 0)&&i.body)){const n=()=>P(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",n)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",n))}),window.document.body.addEventListener("click",n)}return t}}function ry(i){return i==="audioinput"?Z.Source.Microphone:i==="videoinput"?Z.Source.Camera:Z.Source.Unknown}function Gc(i){return i===Z.Source.Microphone?"audioinput":i===Z.Source.Camera?"videoinput":void 0}function ay(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,ps()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio,preferCurrentTab:i.preferCurrentTab}}function Vr(i){return i.split("/")[1].toLowerCase()}function oy(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new bc({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function Je(i){return"mediaStreamTrack"in i?{trackID:i.sid,source:i.source,muted:i.isMuted,enabled:i.mediaStreamTrack.enabled,kind:i.kind,streamID:i.mediaStreamID,streamTrackID:i.mediaStreamTrack.id}:{trackID:i.trackSid,enabled:i.isEnabled,muted:i.isMuted,trackInfo:Object.assign({mimeType:i.mimeType,name:i.trackName,encrypted:i.isEncrypted,kind:i.kind,source:i.source},i.track?Je(i.track):{})}}function cy(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function ly(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(i)],s={};for(const r of n)i[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Of(i){const e=Object.assign({},i);let t,n;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:ey(e)}}function dy(i){switch(i){case Bt.CAMERA:return Z.Source.Camera;case Bt.MICROPHONE:return Z.Source.Microphone;case Bt.SCREEN_SHARE:return Z.Source.ScreenShare;case Bt.SCREEN_SHARE_AUDIO:return Z.Source.ScreenShareAudio;default:return Z.Source.Unknown}}function Uf(i,e){return i.width*i.height<e.width*e.height}function uy(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}const hy=5e3,Gr=[];var Mn;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(Mn||(Mn={}));class Z extends Zn.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Z.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=He,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),hy):this.handleAppVisibilityChanged()},this.log=mi((s=n.loggerName)!==null&&s!==void 0?s:Vn.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Z.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Je(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Z.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===Z.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Gr.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Gr.splice(Gr.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Gs(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?ae.AudioPlaybackStarted:ae.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?ae.AudioPlaybackFailed:ae.VideoPlaybackFailed,r):r.name==="AbortError"?He.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):He.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&n.some(o=>o.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(ae.ElementAttached,e),e}detach(e){try{if(e){Hs(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(ae.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Hs(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(ae.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=mi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Gr.forEach(n=>{n.parentElement||(t=!1)}),t&&Gr.push(e)}}handleAppVisibilityChanged(){return P(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===Z.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){bn()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){bn()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Gs(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(s=>{t.removeTrack(s)}),t.addTrack(i)),(!ps()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(ps()||fs())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Hs(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function s(l){switch(l){case e.Audio:return Fn.AUDIO;case e.Video:return Fn.VIDEO;default:return Fn.DATA}}i.kindToProto=s;function r(l){switch(l){case Fn.AUDIO:return e.Audio;case Fn.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function o(l){switch(l){case t.Camera:return Bt.CAMERA;case t.Microphone:return Bt.MICROPHONE;case t.ScreenShare:return Bt.SCREEN_SHARE;case t.ScreenShareAudio:return Bt.SCREEN_SHARE_AUDIO;default:return Bt.UNKNOWN}}i.sourceToProto=o;function a(l){switch(l){case Bt.CAMERA:return t.Camera;case Bt.MICROPHONE:return t.Microphone;case Bt.SCREEN_SHARE:return t.ScreenShare;case Bt.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=a;function c(l){switch(l){case vc.ACTIVE:return n.Active;case vc.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(Z||(Z={}));const fy="|",Ff="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function py(i){const e=i.split(fy);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function Qt(i){return new vn(e=>Zt.setTimeout(e,i))}function Hc(){return"addTransceiver"in RTCPeerConnection.prototype}function Wc(){return"addTrack"in RTCPeerConnection.prototype}function my(){if(!("getCapabilities"in RTCRtpSender)||ps()||fs())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function gy(){if(!("getCapabilities"in RTCRtpSender)||fs())return!1;if(ps()){const t=yn();if(t!=null&&t.version&&ti(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&ti(t.osVersion,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Gn(i){return i==="av1"||i==="vp9"}function qc(i){return!document||Hr()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function vy(){return typeof RTCPeerConnection>"u"?!1:Hc()||Wc()}function fs(){var i;return((i=yn())===null||i===void 0?void 0:i.name)==="Firefox"}function Bf(){const i=yn();return!!i&&i.name==="Chrome"&&i.os!=="iOS"}function ps(){var i;return((i=yn())===null||i===void 0?void 0:i.name)==="Safari"}function Hr(){const i=yn();return(i==null?void 0:i.name)==="Safari"||(i==null?void 0:i.os)==="iOS"}function yy(){const i=yn();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&ti(i.osVersion,"17")>=0}function by(i){return i||(i=yn()),(i==null?void 0:i.name)==="Safari"&&ti(i.version,"18.3")>0||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&ti(i.osVersion,"18.3")>0}function zf(){var i,e;return bn()?(e=(i=navigator.userAgentData)===null||i===void 0?void 0:i.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function _y(){const i=yn(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&ti(i.osVersion,e)>=0?!0:i.name==="Safari"&&ti(i.version,e)>=0}function bn(){return typeof document<"u"}function ei(){return navigator.product=="ReactNative"}function Ws(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function jc(i){return Ws(i)?i.hostname.split(".")[0]:null}function Vf(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Gf(){if(!ei())return;let i=Vf();if(i)return i.platform}function Hf(){if(bn())return window.devicePixelRatio;if(ei()){let i=Vf();if(i)return i.devicePixelRatio}return 1}function ti(i,e){const t=i.split("."),n=e.split("."),s=Math.min(t.length,n.length);for(let r=0;r<s;++r){const o=parseInt(t[r],10),a=parseInt(n[r],10);if(o>a)return 1;if(o<a)return-1;if(r===s-1&&o===a)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function Sy(i){for(const e of i)e.target.handleResize(e)}function xy(i){for(const e of i)e.target.handleVisibilityChanged(e)}let $c=null;const Wf=()=>($c||($c=new ResizeObserver(Sy)),$c);let Xc=null;const qf=()=>(Xc||(Xc=new IntersectionObserver(xy,{root:null,rootMargin:"0px"})),Xc);function Ty(){var i;const e=new Th({sdk:Ch.JS,protocol:Z0,version:J0});return ei()&&(e.os=(i=Gf())!==null&&i!==void 0?i:""),e}function jf(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=i,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(i/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=t,a}let Wr;function Kc(){if(!Wr){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[Wr]=n.stream.getAudioTracks(),!Wr)throw Error("Could not get empty media stream audio track");Wr.enabled=!1}return Wr.clone()}class Dn{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,s)=>P(this,void 0,void 0,function*(){this.resolve=n,this.reject=s,e&&(yield e(n,s))})).finally(()=>{var n;this._isResolved=!0,(n=this.onFinally)===null||n===void 0||n.call(this)})}}function Cy(i){return ny.includes(i)}function Hi(i){if(typeof i=="string"||typeof i=="number")return i;if(Array.isArray(i))return i[0];if(i.exact!==void 0)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal!==void 0)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function Ey(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function qr(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function My(i,e){return i.segments.map(t=>{let{id:n,text:s,language:r,startTime:o,endTime:a,final:c}=t;var l;const d=(l=e.get(n))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(n):e.set(n,d),{id:n,text:s,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:r,firstReceivedTime:d,lastReceivedTime:u}})}function wy(i){const{id:e,timestamp:t,message:n,editTimestamp:s}=i;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}function $f(i){switch(i.reason){case gt.LeaveRequest:return i.context;case gt.Cancelled:return Bn.CLIENT_INITIATED;case gt.NotAllowed:return Bn.USER_REJECTED;case gt.ServerUnreachable:return Bn.JOIN_FAILURE;default:return Bn.UNKNOWN_REASON}}function Qa(i){return i!==void 0?Number(i):void 0}function ms(i){return i!==void 0?BigInt(i):void 0}function qs(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function ni(i){return!!i&&i.kind==Z.Kind.Audio}function Wi(i){return!!i&&i.kind==Z.Kind.Video}function qi(i){return qs(i)&&Wi(i)}function yi(i){return qs(i)&&ni(i)}function Yc(i){return!!i&&!i.isLocal}function Ay(i){return!!i&&!i.isLocal}function Jc(i){return Yc(i)&&Wi(i)}function Ry(i){return i.isLocal}function Py(i,e){const t=[];let n=new TextEncoder().encode(i);for(;n.length>e;){let s=e;for(;s>0;){const r=n[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(n.slice(0,s)),n=n.slice(s)}return n.length>0&&t.push(n),t}function ky(i){var e;const t=i.get("Cache-Control");if(t){const n=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(n)return parseInt(n,10)}}function Iy(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const n=Dy(i,e);return t?n:Zc(n,"v1")}function Dy(i,e){const t=new URL(Ey(i));return e.forEach((n,s)=>{t.searchParams.set(s,n)}),Zc(t,"rtc")}function Ly(i){const e=new URL(qr(i));return Zc(e,"validate")}function Xf(i){return i.endsWith("/")?i:"".concat(i,"/")}function Zc(i,e){return i.pathname="".concat(Xf(i.pathname)).concat(e),i}function Kf(i){if(typeof i=="string")return Ph.fromJson(JSON.parse(i),{ignoreUnknownFields:!0});if(i instanceof ArrayBuffer)return Ph.fromBinary(new Uint8Array(i));throw new Error("could not decode websocket message: ".concat(typeof i))}function Ny(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(i instanceof AbortSignal))return e;const t=i.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const Oy=10,jr="lk_e2ee",Uy={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Oy,keyringSize:16};var ji;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(ji||(ji={}));var Yf;(function(i){i.KeyRatcheted="keyRatcheted"})(Yf||(Yf={}));var $i;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})($i||($i={}));var Jf;(function(i){i.Error="cryptorError"})(Jf||(Jf={}));function Fy(){return By()||Qc()}function Qc(){return typeof window.RTCRtpScriptTransform<"u"}function By(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function zy(i){var e,t,n,s,r;if(((e=i.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=i.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((n=i.value)===null||n===void 0?void 0:n.case)!=="speaker"&&((s=i.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=i.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new gh({value:i.value})}class IM extends Zn.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n,s)=>{He.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Uy),e),this.on(ji.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const s={key:e,participantIdentity:t,keyIndex:n};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(n??0),s),this.emit(ji.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(ji.RatchetRequest,e,t)}}var Zf;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(Zf||(Zf={}));class Vy extends Zn.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=n=>{var s,r;const{kind:o,data:a}=n.data;switch(o){case"error":if(He.error(a.error.message),a.uuid){const d=this.decryptDataRequests.get(a.uuid);if(d!=null&&d.reject){d.reject(a.error);break}const u=this.encryptDataRequests.get(a.uuid);if(u!=null&&u.reject){u.reject(a.error);break}}this.emit($i.EncryptionError,a.error,a.participantIdentity);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(d=>{this.postKey(d)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(d=>{this.postKey(d)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit($i.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const d=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!d)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit($i.ParticipantEncryptionStatusChanged,a.enabled,d)}break;case"ratchetKey":this.keyProvider.emit(ji.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(a.uuid);c!=null&&c.resolve&&c.resolve(a);break;case"encryptDataResponse":const l=this.encryptDataRequests.get(a.uuid);l!=null&&l.resolve&&l.resolve(a);break}},this.onWorkerError=n=>{He.error("e2ee worker encountered an error:",{error:n.error}),this.emit($i.EncryptionError,n.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Fy())throw new Oc("tried to setup end-to-end encryption on an unsupported browser");if(He.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:N0.getLevel()}};this.worker&&(He.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){He.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?He.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(le.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(ne.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==Ht.NONE,s.identity)),e.on(ne.ConnectionStateChanged,n=>{n===ot.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==Ht.NONE,s.identity)})})}).on(ne.TrackUnsubscribed,(n,s,r)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(ne.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(ne.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(de.LocalSenderCreated,(n,s)=>P(this,void 0,void 0,function*(){this.setupE2EESender(s,n)})),e.localParticipant.on(de.LocalTrackPublished,n=>{if(!Wi(n.track)||!Hr())return;const s={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:Vr(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(ji.SetKey,n=>this.postKey(n)).on(ji.RatchetRequest,(n,s)=>this.postRatchetRequest(n,s))}encryptData(e){return P(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Dn;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(n),s.promise})}handleEncryptedData(e,t,n,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:s}},a=new Dn;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage(o),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Vr(n.mimeType):void 0)}}setupE2EESender(e,t){if(!qs(e)||!t){t||He.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return P(this,void 0,void 0,function*(){if(this.worker){if(Qc()&&!Bf()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(jr in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,o=e.readableStream;if(!r||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:r,trackId:t,codec:s,participantIdentity:n,isReuse:jr in e}};this.worker.postMessage(a,[o,r])}e[jr]=!0}})}handleSender(e,t,n){var s;if(!(jr in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Qc()&&!Bf()){He.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{He.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[r.readable,r.writable])}e[jr]=!0}}}const Gy=500,Hy=15e3;class js{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new js),this._instance}addFailedConnectionAttempt(e){var t;const n=new URL(e),s=jc(n);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,Qt(Math.min(Gy*Math.pow(2,r),Hy)))}getBackOffPromise(e){const t=new URL(e),n=t&&jc(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&jc(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}js._instance=null;const el="default";class Xt{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Xt),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=Xt.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){He.debug("awaiting getUserMedia promise");try{t?yield Xt.userMediaPromiseMap.get(t):yield Promise.all(Xt.userMediaPromiseMap.values())}catch{He.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(s&&!(ps()&&n.hasDeviceInUse(t))&&(o.filter(c=>c.kind===t).length===0||o.some(c=>{const l=c.label==="",d=t?c.kind===t:!0;return l&&d}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return n._previousDevices=o,t&&(o=o.filter(a=>a.kind===t)),o})()})}normalizeDeviceId(e,t,n){return P(this,void 0,void 0,function*(){if(t!==el)return t;const s=yield this.getDevices(e),r=s.find(a=>a.deviceId===el);if(!r){He.warn("could not reliably determine default device");return}const o=s.find(a=>a.deviceId!==el&&a.groupId===(n??r.groupId));if(!o){He.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?Xt.userMediaPromiseMap.has(e):Xt.userMediaPromiseMap.size>0}}Xt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Xt.userMediaPromiseMap=new Map;var $r;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})($r||($r={}));class Wy{constructor(){this.pendingTasks=new Map,this.taskMutex=new cn,this.nextTaskIndex=0}run(e){return P(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:$r.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=$r.RUNNING,yield e()}finally{t.status=$r.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return P(this,void 0,void 0,function*(){return this.run(()=>P(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class qy{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,s;if(!((n=t.signal)===null||n===void 0)&&n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const o=function(){let{closeCode:a,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(a,c)};this.opened=new vn((a,c)=>{const l=()=>{c(Ne.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{a({readable:new ReadableStream({start(d){r.onmessage=u=>{let{data:h}=u;return d.enqueue(h)},r.onerror=u=>d.error(u)},cancel:o}),writable:new WritableStream({write(d){r.send(d)},abort(){r.close()},close:o}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),this.closed=new vn((a,c)=>{const l=()=>P(this,void 0,void 0,function*(){const d=new vn(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{h(f)},{once:!0})}),u=yield vn.race([Qt(250),d]);u?a(u):c(Ne.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=d=>{let{code:u,reason:h}=d;a({closeCode:u,reason:h}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=o}}const jy=["syncState","trickle","offer","answer","simulate","leave"];function $y(i){const e=jy.indexOf(i.case)>=0;return He.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var vt;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(vt||(vt={}));const Xy=250;class tl{get currentState(){return this.state}get isDisconnected(){return this.state===vt.DISCONNECTING||this.state===vt.DISCONNECTED}get isEstablishingConnection(){return this.state===vt.CONNECTING||this.state===vt.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;this.rtt=0,this.state=vt.DISCONNECTED,this.log=He,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=mi((n=t.loggerName)!==null&&n!==void 0?n:Vn.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Wy,this.queuedRequests=[],this.closingLock=new cn,this.connectionLock=new cn,this.state=vt.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return l.state=vt.CONNECTING,l.options=a,yield l.connect(r,o,a,c,d)})()})}reconnect(e,t,n,s){return P(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=vt.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const u=yield l.connectionLock.lock();l.connectOptions=a,l.useV0SignalPath=d;const h=Ty(),f=d?Ky(o,h,a):Yy(o,h,a),g=Iy(r,f,d).toString(),v=Ly(g).toString();return new Promise((m,p)=>P(l,void 0,void 0,function*(){var T,E;try{let y=!1;const S=x=>P(this,void 0,void 0,function*(){if(y)return;y=!0;const R=x instanceof Event?x.currentTarget:x,O=Ny(R,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(O)).catch(F=>{this.log.error(F),this.close()}):this.close(),C(),p(Ne.cancelled(O))});c==null||c.addEventListener("abort",S);const C=()=>{clearTimeout(w),c==null||c.removeEventListener("abort",S)},w=setTimeout(()=>{S(Ne.timeout("room connection has timed out (signal)"))},a.websocketTimeout),k=(x,R)=>{this.handleSignalConnected(x,w,R)},_=new URL(g);_.searchParams.has("access_token")&&_.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(_),Object.assign({reconnect:a.reconnect,reconnectReason:a.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new qy(g);try{this.ws.closed.then(G=>{var W;this.isEstablishingConnection&&p(Ne.internal("Websocket got closed during a (re)connection attempt: ".concat(G.reason))),G.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:G.reason,code:G.closeCode,wasClean:G.closeCode===1e3,state:this.state})),this.state===vt.CONNECTED&&this.handleOnClose((W=G.reason)!==null&&W!==void 0?W:"Unexpected WS error"))}).catch(G=>{this.isEstablishingConnection&&p(Ne.internal("Websocket error during a (re)connection attempt: ".concat(G)))});const x=yield this.ws.opened.catch(G=>P(this,void 0,void 0,function*(){if(this.state!==vt.CONNECTED){this.state=vt.DISCONNECTED,clearTimeout(w);const W=yield this.handleConnectionError(G,v);p(W);return}this.handleWSError(G),p(G)}));if(clearTimeout(w),!x)return;const R=x.readable.getReader();this.streamWriter=x.writable.getWriter();const O=yield R.read();if(R.releaseLock(),!O.value)throw Ne.internal("no message received as first message");const F=Kf(O.value),q=this.validateFirstMessage(F,(T=a.reconnect)!==null&&T!==void 0?T:!1);if(!q.isValid){p(q.error);return}((E=F.message)===null||E===void 0?void 0:E.case)==="join"&&(this.pingTimeoutDuration=F.message.value.pingTimeout,this.pingIntervalDuration=F.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));const K=q.shouldProcessFirstMessage?F:void 0;k(x,K),m(q.response)}catch(x){p(x)}finally{C()}}finally{u()}}))})()})}startReadingLoop(e,t){return P(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Qt(this.signalLatency));const{done:n,value:s}=yield e.read();if(n)break;const r=Kf(s);this.handleSignalResponse(r)}})}close(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([vt.DISCONNECTING||vt.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=vt.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,Qt(Xy)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=vt.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:$s(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:$s(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Ba({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new za({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const a=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new Sc({requestId:a,metadata:n,name:s,attributes:o})}),a})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Dh({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Oh({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:wt.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Bh({timestamp:wt.parse(Date.now()),rtt:wt.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new _c({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ga({reason:Bn.CLIENT_INITIATED,action:Fs.DISCONNECT})})}sendRequest(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!$y(t)&&n.state===vt.RECONNECTING){n.queuedRequests.push(()=>P(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield n.requestQueue.flush()),n.signalLatency&&(yield Qt(n.signalLatency)),n.isDisconnected){n.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!n.streamWriter){n.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),n.logContext);return}const o=new a0({message:t});try{n.useJSON?yield n.streamWriter.write(o.toJsonString()):yield n.streamWriter.write(o.toBinary())}catch(a){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:a}))}})()})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const o=Qf(s.value);this.onAnswer&&this.onAnswer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const o=Qf(s.value);this.onOffer&&this.onOffer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const o=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(o,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=s.value.speakers)!==null&&n!==void 0?n:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return P(this,void 0,void 0,function*(){if(this.state===vt.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Zt.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&&Zt.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=Zt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Zt.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=vt.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){var n,s,r,o,a;return((n=e.message)===null||n===void 0?void 0:n.case)==="join"?{isValid:!0,response:e.message.value}:this.state===vt.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((o=e.message)===null||o===void 0?void 0:o.case)==="leave"?{isValid:!1,error:Ne.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:Ne.internal("Unexpected first message")}:{isValid:!1,error:Ne.internal("did not receive join response, got ".concat((a=e.message)===null||a===void 0?void 0:a.case," instead"))}}handleConnectionError(e,t){return P(this,void 0,void 0,function*(){try{const n=yield fetch(t);switch(n.status){case 404:return Ne.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield n.text();return Ne.notAllowed(s,n.status);default:break}return e instanceof Ne?e:Ne.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof Ne?n:Ne.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}})}}function Qf(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function $s(i,e){return new Gi({sdp:i.sdp,type:i.type,id:e})}function Ky(i,e,t){var n;const s=new URLSearchParams;return s.set("access_token",i),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",ei()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&s.set("network",navigator.connection.type),s}function Yy(i,e,t){const n=new URLSearchParams;n.set("access_token",i);const s=new A0({clientInfo:e,connectionSettings:new zh({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new R0({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),n}class ep{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Jy{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();const s=n+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[s,r]of n.entries())t.push(e(r,s,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var Hn={},nl={},il={exports:{}},tp;function sl(){if(tp)return il.exports;tp=1;var i=il.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(i).forEach(function(e){var t=i[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),il.exports}var np;function Zy(){return np||(np=1,(function(i){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,c,l,d){if(d&&!l)c[d]=e(a[1]);else for(var u=0;u<l.length;u+=1)a[u+1]!=null&&(c[l[u]]=e(a[u+1]))},n=function(a,c,l){var d=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:d&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:d?c[a.name]:c;t(l.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},s=sl(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(a){var c={},l=[],d=c;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var g=0;g<(s[h]||[]).length;g+=1){var v=s[h][g];if(v.reg.test(f))return n(v,d,f)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};i.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(a){return a.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},i.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},i.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}})(nl)),nl}var rl,ip;function Qy(){if(ip)return rl;ip=1;var i=sl(),e=/%[sdv%]/g,t=function(o){var a=1,c=arguments,l=c.length;return o.replace(e,function(d){if(a>=l)return d;var u=c[a];switch(a+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},n=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,d=[o+"="+l];if(a.names)for(var u=0;u<a.names.length;u+=1){var h=a.names[u];a.name?d.push(c[a.name][h]):d.push(c[a.names[u]])}else d.push(c[a.name]);return t.apply(null,d)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return rl=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=a.outerOrder||s,l=a.innerOrder||r,d=[];return c.forEach(function(u){i[u].forEach(function(h){h.name in o&&o[h.name]!=null?d.push(n(u,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){d.push(n(u,h,f))})})}),o.media.forEach(function(u){d.push(n("m",i.m[0],u)),l.forEach(function(h){i[h].forEach(function(f){f.name in u&&u[f.name]!=null?d.push(n(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(g){d.push(n(h,f,g))})})})}),d.join(`\r
83
83
  `)+`\r
84
- `},rl}var sp;function eb(){if(sp)return Hn;sp=1;var i=Zy(),e=Qy(),t=sl();return Hn.grammar=t,Hn.write=e,Hn.parse=i.parse,Hn.parseParams=i.parseParams,Hn.parseFmtpConfig=i.parseFmtpConfig,Hn.parsePayloads=i.parsePayloads,Hn.parseRemoteCandidates=i.parseRemoteCandidates,Hn.parseImageAttributes=i.parseImageAttributes,Hn.parseSimulcastStreamList=i.parseSimulcastStreamList,Hn}var Xi=eb();function al(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var o=(n=t.isImmediate)!=null&&n,a=(s=t.callback)!=null&&s,c=t.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(v,m){var p=o&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,l=Date.now(),!o){var E=i.apply(g,f);a&&a(E),d.forEach(function(y){return(0,y.resolve)(E)}),d=[]}},u()),p){var T=i.apply(g,f);return a&&a(T),v(T)}d.push({resolve:v,reject:m})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),d.forEach(function(g){return(0,g.reject)(f)}),d=[]},h}const tb=.7,nb=20,Xs={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class rp extends Zn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;super(),this.log=He,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=al(s=>P(this,void 0,void 0,function*(){this.emit(Xs.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),nb),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=mi((n=t.loggerName)!==null&&n!==void 0?n:Vn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new on}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return P(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return P(this,void 0,void 0,function*(){var n;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:o}=ib(e);this.remoteStereoMids=r,this.remoteNackMids=o}else if(e.type==="answer"){const r=Xi.parse((n=e.sdp)!==null&&n!==void 0?n:"");r.media.forEach(o=>{const a=ol(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||a!=c.transceiver.mid)return!1;let l=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0)return!0;let d=!1;for(const u of o.fmtp)if(u.payload===l){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),d=!0;break}return d||c.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=Xi.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Xs.NegotiationComplete),e.sdp&&Xi.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Xs.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const a=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&a)yield this._pc.setRemoteDescription(a);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const o=Xi.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(o.media.forEach(a=>{op(a),a.type==="audio"?ap(a,["all"],[]):a.type==="video"&&this.trackBitrates.some(c=>{if(!a.msid||!c.cid||!a.msid.includes(c.cid))return!1;let l=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0||(Gn(c.codec)&&!ps()&&this.ensureVideoDDExtensionForSVC(a,o),!Gn(c.codec)))return!0;const d=Math.round(c.maxbr*tb);for(const u of a.fmtp)if(u.payload===l){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(d));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,Xi.write(o)),this.onOffer(r,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=Xi.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{op(s),s.type==="audio"&&ap(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Xi.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Ut("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Ut("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return P(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,s=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),n.set(a.id,a);break;case"remote-candidate":s.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const o=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return s.get(o)})}setMungedSDP(e,t,n){return P(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const o={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new zs(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,s;if(!((n=e.ext)===null||n===void 0?void 0:n.some(o=>o.uri===Ff))){if(this.ddExtID===0){let o=0;t.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Ff})}}}function ap(i,e,t){const n=ol(i.mid);let s=0;i.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(n)&&!i.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&i.rtcpFb.push({payload:s,type:"nack"}),(e.includes(n)||e.length===1&&e[0]==="all")&&i.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function ib(i){var e;const t=[],n=[],s=Xi.parse((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(o=>{var a;const c=ol(o.mid);o.type==="audio"&&(o.rtp.some(l=>l.codec==="opus"?(r=l.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(l=>l.payload===r&&l.type==="nack")&&n.push(c),o.fmtp.some(l=>l.payload===r?(l.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:n}}function op(i){if(i.connection){const e=i.connection.ip.indexOf(":")>=0;(i.connection.version===4&&e||i.connection.version===6&&!e)&&(i.connection.ip="0.0.0.0",i.connection.version=4)}}function ol(i){return typeof i=="number"?i.toFixed(0):i}const cl="vp8",sb={audioPreset:Uc.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Bc.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:cl,backupCodec:!0,preConnectBuffer:!1},cp={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},lp={deviceId:{ideal:"default"},resolution:zr.h720.resolution},rb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new U0,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},ll={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var kt;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(kt||(kt={}));class ab{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){var s;this.peerConnectionTimeout=ll.peerConnectionTimeout,this.log=He,this.updateState=()=>{var r,o;const a=this.state,c=this.requiredTransports.map(l=>l.getConnectionState());c.every(l=>l==="connected")?this.state=kt.CONNECTED:c.some(l=>l==="failed")?this.state=kt.FAILED:c.some(l=>l==="connecting")?this.state=kt.CONNECTING:c.every(l=>l==="closed")?this.state=kt.CLOSED:c.some(l=>l==="closed")?this.state=kt.CLOSING:c.every(l=>l==="new")&&(this.state=kt.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(kt[a]," to ").concat(kt[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=mi((s=n.loggerName)!==null&&s!==void 0?s:Vn.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new rp(e,n),this._mode=t,t!=="publisher-only"&&(this.subscriber=new rp(e,n),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,zn.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,r)},this.subscriber.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,zn.PUBLISHER)},this.publisher.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)},this.publisher.onOffer=(r,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r,o)},this.state=kt.NEW,this.connectionLock=new on,this.remoteOfferLock=new on}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return P(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return P(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return P(this,void 0,void 0,function*(){var n;t===zn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(n=this.subscriber)===null||n===void 0?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return P(this,void 0,void 0,function*(){var n,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(n=this.subscriber)===null||n===void 0?void 0:n.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),(n=this.subscriber)===null||n===void 0||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return P(this,void 0,void 0,function*(){var n;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return P(this,void 0,void 0,function*(){return new gn((t,n)=>P(this,void 0,void 0,function*(){const s=setTimeout(()=>{n(new zs("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),n(new zs("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(Xs.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Xs.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(o=>{clearTimeout(s),o instanceof Error?n(o):n(new Error(String(o)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const n=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return n==null?void 0:n.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===zn.PUBLISHER?this.publisher.getConnectedAddress():e===zn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(n.getConnectionState()!=="connected")return new Promise((c,l)=>P(r,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),Jt.clearTimeout(u),l(Ne.cancelled("room connection has been cancelled"))};s!=null&&s.signal.aborted&&d(),s==null||s.signal.addEventListener("abort",d);const u=Jt.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",d),l(Ne.internal("could not establish pc connection"))},o);for(;this.state!==kt.CONNECTED;)if(yield Zt(50),s!=null&&s.signal.aborted){l(Ne.cancelled("room connection has been cancelled"));return}Jt.clearTimeout(u),s==null||s.signal.removeEventListener("abort",d),c()}))})()})}}const dp=5e3,ob=3e4;class et{static fetchRegionSettings(e,t,n){return P(this,void 0,void 0,function*(){const s=yield et.fetchLock.lock();try{const r=yield fetch("".concat(cb(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(r.ok){const o=ky(r.headers),a=o?o*1e3:dp;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:a}}else throw r.status===401?Ne.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):Ne.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof Ne?r:n!=null&&n.aborted?Ne.cancelled("Region fetching was aborted"):Ne.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,n){return P(this,void 0,void 0,function*(){const s=et.settingsTimeouts.get(e.hostname);clearTimeout(s),et.settingsTimeouts.set(e.hostname,setTimeout(()=>P(this,void 0,void 0,function*(){try{const r=yield et.fetchRegionSettings(e,t);et.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof Ne&&r.reason===gt.NotAllowed){He.debug("token is not valid, cancelling auto region refresh");return}He.debug("auto refetching of region settings failed",{error:r}),et.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){et.cache.set(e.hostname,n),et.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=et.settingsTimeouts.get(e);t&&(clearTimeout(t),et.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=et.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const n=et.connectionTrackers.get(e);n&&n.connectionCount===0&&(He.debug("stopping region refetch after disconnect delay",{hostname:e}),et.stopRefetch(e)),n&&(n.cleanupTimeout=void 0)},ob))}static cancelCleanup(e){const t=et.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=et.connectionTrackers.get(e);t||(t={connectionCount:0},et.connectionTrackers.set(e,t)),t.connectionCount++,et.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=et.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&et.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Ws(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return P(this,void 0,void 0,function*(){return et.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return P(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=et.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),et.updateCachedRegionSettings(this.serverUrl,this.token,t));const n=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(n.length>0){const s=n[0];return this.attemptedRegions.push(s),He.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){et.updateCachedRegionSettings(this.serverUrl,this.token,e)}}et.cache=new Map,et.settingsTimeouts=new Map,et.connectionTrackers=new Map,et.fetchLock=new on;function cb(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}class It extends Error{constructor(e,t,n){super(t),this.code=e,this.message=hp(t,It.MAX_MESSAGE_BYTES),this.data=n?hp(n,It.MAX_DATA_BYTES):void 0}static fromProto(e){return new It(e.code,e.message,e.data)}toProto(){return new bh({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new It(It.ErrorCode[e],It.ErrorMessage[e],t)}}It.MAX_MESSAGE_BYTES=256,It.MAX_DATA_BYTES=15360,It.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},It.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 up=15360;function dl(i){return new TextEncoder().encode(i).length}function hp(i,e){if(dl(i)<=e)return i;let t=0,n=i.length;const s=new TextEncoder;for(;t<n;){const r=Math.floor((t+n+1)/2);s.encode(i.slice(0,r)).length<=e?t=r:n=r-1}return i.slice(0,t)}const ul=2e3;function eo(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}const hl=typeof MediaRecorder<"u";class lb{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const db=hl?MediaRecorder:lb;class ub extends db{constructor(e,t){if(!hl)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let n,s;const r=()=>s===void 0,o=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",a),s==null||s.close(),s=void 0},a=c=>{s==null||s.error(c),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",a),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,n=l=>P(this,void 0,void 0,function*(){let d;if(l.data.arrayBuffer){const u=yield l.data.arrayBuffer();d=new Uint8Array(u)}else if(l.data.byteArray)d=l.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(d)}),this.addEventListener("dataavailable",n)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function hb(){return hl}const fb=1e3,pb=1e4;class fp extends Z{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=al(()=>P(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>P(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(ae.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new on,this.pauseUpstreamLock=new on,this.trackChangeLock=new on,this.trackChangeLock.lock().then(o=>P(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Z.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return P(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Hs(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Gs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Gs(s??e,r)}))})}waitForDimensions(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:fb;return(function*(){var n;if(e.kind===Z.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=vn())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Zt(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield Zt(50)}throw new vi("unable to get track dimensions after timeout")})()})}setDeviceId(e){return P(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Hi(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Hi(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===Z.Source.ScreenShare)return;const{deviceId:n,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===Z.Kind.Audio?"audioinput":"videoinput";return t?$t.getInstance().normalizeDeviceId(r,n,s):n})()})}mute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return P(this,void 0,void 0,function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new vi("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e){return P(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:s}=e,r=F0(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===Z.Kind.Video?o.video=n||s?{deviceId:n,facingMode:s}:!0:o.audio=n?Object.assign({deviceId:n},r):!0,this.attachedElements.forEach(l=>{Hs(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===Z.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(ae.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ae.Muted:ae.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),zf()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(ae.UpstreamPaused,this);const n=vn();if((n==null?void 0:n.name)==="Safari"&&ti(n.version,"12.0")<0)throw new Oc("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(ae.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const o=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const a=document.createElement(n.kind),c={kind:n.kind,track:n._mediaStreamTrack,element:a,audioContext:n.audioContext};if(yield t.init(c),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Gs(n._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:l})),setTimeout(()=>{a.play().catch(d=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:d}))})},100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:l}))}),n.processor=t,n.processorElement=a,n.processor.processedTrack){for(const l of n.attachedElements)l!==n.processorElement&&s&&(Hs(n._mediaStreamTrack,l),Gs(n.processor.processedTrack,l));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(ae.TrackProcessorUpdate,n.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}})()})}internalStopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var n,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(ae.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!hb()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new ub(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},pb)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class to extends fp{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,Z.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=eo(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ae.AudioTrackFeatureUpdate,this,jt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ae.AudioTrackFeatureUpdate,this,jt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===Z.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Hi(this._constraints.deviceId);return this.source===Z.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return P(this,void 0,void 0,function*(){let t;if(e){const n=Vc({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return P(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){yn()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ul)))}setProcessor(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!ei()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(ae.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return P(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(s=>{s.type==="outbound-rtp"&&(n={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),n})}checkForSilence(){return P(this,void 0,void 0,function*(){const e=yield Lf(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(ae.AudioSilenceDetected)),e})}}function mb(i,e,t){switch(i.kind){case"audio":return new to(i,e,!1,void 0,t);case"video":return new no(i,e,!1,t);default:throw new vi("unsupported track type: ".concat(i.kind))}}const gb=Object.values(zr),vb=Object.values(Fc),yb=Object.values(Bc),bb=[zr.h180,zr.h360],_b=[Fc.h180,Fc.h360],Sb=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new ft(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,i.encoding.priority)}),fl=["q","h","f"];function pl(i,e,t,n){var s,r;let o=n==null?void 0:n.videoEncoding;i&&(o=n==null?void 0:n.screenShareEncoding);const a=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,l=n==null?void 0:n.videoCodec;if(!o&&!a&&!c||!e||!t)return[{}];o||(o=Tb(i,e,t,l),He.debug("using video encoding",o));const d=o.maxFramerate,u=new ft(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Gn(l)){const g=new gp(c),v=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const m=vn();if(Hr()||ei()||(m==null?void 0:m.name)==="Chrome"&&ti(m==null?void 0:m.version,"113")<0){const p=g.suffix=="h"?2:3,T=by(m);for(let E=0;E<g.spatial;E+=1)v.push({rid:fl[2-E],maxBitrate:o.maxBitrate/Math.pow(p,E),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:T?Math.pow(2,E):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),He.debug("using svc encoding",{encodings:v}),v}if(!a)return[o];let h=[];i?h=(s=mp(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:pp(i,u):h=(r=mp(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:pp(i,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return ml(e,t,[g,f,u],d);if(v>=480)return ml(e,t,[g,u],d)}return ml(e,t,[u])}function xb(i,e,t){var n,s,r,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&He.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const a=i.mediaStreamTrack.getSettings(),c=(n=a.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,l=(r=a.height)!==null&&r!==void 0?r:(o=i.dimensions)===null||o===void 0?void 0:o.height;return i.source===Z.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),pl(i.source===Z.Source.ScreenShare,c,l,t)}function Tb(i,e,t,n){const s=Cb(i,e,t);let{encoding:r}=s[0];const o=Math.max(e,t);for(let a=0;a<s.length;a+=1){const c=s[a];if(r=c.encoding,c.width>=o)break}if(n)switch(n){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Cb(i,e,t){if(i)return yb;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?gb:vb}function pp(i,e){if(i)return Sb(e);const{width:t,height:n}=e,s=t>n?t/n:n/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?bb:_b}function ml(i,e,t,n){const s=[];if(t.forEach((r,o)=>{if(o>=fl.length)return;const a=Math.min(i,e),l={rid:fl[o],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},d=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=fs()||o===0;r.encoding.priority&&u&&(l.priority=r.encoding.priority,l.networkPriority=r.encoding.priority),s.push(l)}),ei()&&Gf()==="ios"){let r;s.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let o=!0;s.forEach(a=>{var c;a.maxFramerate!=r&&(o&&(o=!1,He.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),He.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),a.maxFramerate=r)})}return s}function mp(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:s}=t;return n.maxBitrate>s.maxBitrate?1:n.maxBitrate<s.maxBitrate?-1:n.maxBitrate===s.maxBitrate&&n.maxFramerate&&s.maxFramerate?n.maxFramerate>s.maxFramerate?1:-1:0})}class gp{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Eb(i){return i.source===Z.Source.ScreenShare||i.constraints.height&&Hi(i.constraints.height)>=1080?"maintain-resolution":"balanced"}const Mb=5e3;class no extends fp{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,Z.Kind.Video,t,n,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const o=new Map(r.map(c=>[c.rid,c])),a=r.some(c=>c.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(ae.CpuConstrained)),this.prevStats){let c=0;o.forEach((l,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);c+=eo(l,h)}),this._currentBitrate=c}this.prevStats=o}),this.senderLock=new on}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!yn())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ul))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=gi(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;a=!0)r=l.value,a=!1,yield(o=r.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(d){n={error:d}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=gi(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;a=!0){r=l.value,a=!1;const d=r;yield(o=d.sender)===null||o===void 0?void 0:o.replaceTrack(d.mediaStreamTrack)}}catch(d){n={error:d}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===Z.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===Z.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return P(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(s=>{var r;if(s.type==="outbound-rtp"){const o={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},a=n.get(s.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t.sort((s,r)=>{var o,a;return((o=r.frameWidth)!==null&&o!==void 0?o:0)-((a=s.frameWidth)!==null&&a!==void 0?a:0)}),t})}setPublishingQuality(e){const t=[];for(let n=En.LOW;n<=En.HIGH;n+=1)t.push(new xc({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Gn(this.codec),t)}restartTrack(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o;let a;if(e){const u=Vc({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var c=!0,l=gi(this.simulcastCodecs.values()),d;d=yield l.next(),t=d.done,!t;c=!0){r=d.value,c=!1;const u=r;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){n={error:u}}finally{try{!c&&!t&&(s=l.return)&&(yield s.call(l))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return P(this,arguments,void 0,function(n){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,c,l,d,u;if(yield t.setProcessor.call(s,n,r),!((d=s.processor)===null||d===void 0)&&d.processedTrack)try{for(var h=!0,f=gi(s.simulcastCodecs.values()),g;g=yield f.next(),o=g.done,!o;h=!0)l=g.value,h=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){a={error:v}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return P(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Mb))}setPublishingCodecs(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o,a,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Gn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,n=gi(e);s=yield n.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Gn(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of d.qualities)if(h.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield vp(u.sender,u.encodings,d.qualities,this.senderLock,Gn(d.codec),this.log,this.logContext))}}}catch(d){o={error:d}}finally{try{!t&&!r&&(a=n.return)&&(yield a.call(n))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,t){return P(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield vp(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return P(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((n,s)=>{var r;return Object.assign(Object.assign({},n),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Gn(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?n.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),zf()&&this.isInBackground&&this.source===Z.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function vp(i,e,t,n,s,r,o){return P(this,void 0,void 0,function*(){const a=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:i,qualities:t,senderEncodings:e}));try{const c=i.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var g;let v=(g=h.rid)!==null&&g!==void 0?g:"";v===""&&(v="q");const m=yp(v),p=t.find(T=>T.quality===m);p&&h.active!==p.enabled&&(d=!0,h.active=p.enabled,r.debug("setting layer ".concat(p.quality," to ").concat(h.active?"enabled":"disabled"),o),fs()&&(p.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),d&&(c.encodings=l,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield i.setParameters(c))}finally{a()}})}function yp(i){switch(i){case"f":return En.HIGH;case"h":return En.MEDIUM;case"q":return En.LOW;default:return En.HIGH}}function bp(i,e,t,n){if(!t)return[new Vi({quality:En.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new gp(s),o=[],a=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let l=0;l<r.spatial;l+=1)o.push(new Vi({quality:Math.min(En.HIGH,r.spatial-1)-l,width:Math.ceil(i/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return t.map(s=>{var r,o,a;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let l=yp((o=s.rid)!==null&&o!==void 0?o:"");return new Vi({quality:l,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(a=s.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const _p="_lossy",Sp="_reliable",wb=2*1e3,gl="leave-reconnect",Ab=3e4,Rb=8*1024,Pb=256*1024;var Ln;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Ln||(Ln={}));class kb extends Zn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ll.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ln.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=He,this.reliableDataSequence=1,this.reliableMessageBuffer=new ep,this.reliableReceivedState=new Jy(Ab),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=n=>P(this,[n],void 0,function(s){var r=this;let{channel:o}=s;return(function*(){if(o){if(o.label===Sp)r.reliableDCSub=o;else if(o.label===_p)r.lossyDCSub=o;else return;r.log.debug("on data channel ".concat(o.id,", ").concat(o.label),r.logContext),o.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=n=>P(this,void 0,void 0,function*(){var s,r,o,a,c;const l=yield this.dataProcessLock.lock();try{let d;if(n.data instanceof ArrayBuffer)d=n.data;else if(n.data instanceof Blob)d=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const u=cn.fromBinary(new Uint8Array(d));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(ce.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=gh.fromBinary(h.payload),g=new cn({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((a=g.value)===null||a===void 0?void 0:a.case)==="user"&&xp(g,g.value.value),this.emit(ce.DataPacketReceived,g,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&xp(u,u.value.value),this.emit(ce.DataPacketReceived,u,Ht.NONE)}finally{l()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:o}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?Ke.LOSSY:Ke.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,s)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(ce.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){r(o);return}n===gl&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Jt.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===Ln.Connected&&n();const r=()=>{this.off(ce.Disconnected,o),n()},o=()=>{this.off(ce.Restarted,r),s()};this.once(ce.Restarted,r),this.once(ce.Disconnected,o)}),this.updateAndEmitDCBufferStatus=n=>{if(n===Ke.RELIABLE){const r=this.dataChannelForKind(n);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(n);typeof s<"u"&&s!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,s),this.emit(ce.DCBufferStatusChanged,s,n))},this.isBufferStatusLow=n=>{const s=this.dataChannelForKind(n);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>P(this,void 0,void 0,function*(){!this.url||!(yield fetch(qr(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===vt.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===vt.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(ds.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>P(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(qr(this.url),{method:"HEAD"}),Zt(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=mi((t=e.loggerName)!==null&&t!==void 0?t:Vn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new tl(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new on,this.dataProcessLock=new on,this.dcBufferStatus=new Map([[Ke.LOSSY,!0],[Ke.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(ce.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(ce.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(ce.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(ce.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(ce.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(ce.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(ce.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(ce.SignalRequestResponse,n)}get logContext(){var e,t,n,s,r,o;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||s===void 0?void 0:s.sid,participant:(o=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){l.url=r,l.token=o,l.signalOpts=a,l.maxJoinAttempts=a.maxRetries;try{l.joinAttempts+=1,l.setupSignalClientCallbacks();const u=yield l.client.join(r,o,a,c,d);return l._isClosed=!1,l.latestJoinResponse=u,l.subscriberPrimary=u.subscriberPrimary,l.pcManager||(yield l.configure(u,!d)),(!l.subscriberPrimary||u.fastPublish)&&l.negotiate().catch(h=>{He.error(h,l.logContext)}),l.registerOnLineListener(),l.clientConfiguration=u.clientConfiguration,l.emit(ce.SignalConnected,u),u}catch(u){if(u instanceof Ne){if(u.reason===gt.ServerUnreachable){if(l.log.warn("Couldn't connect to server, attempt ".concat(l.joinAttempts," of ").concat(l.maxJoinAttempts),l.logContext),l.joinAttempts<l.maxJoinAttempts)return l.join(r,o,a,c,d)}else if(u.reason===gt.ServiceNotFound)return l.log.warn("Initial connection failed: ".concat(u.message," – Retrying")),l.join(r,o,a,c,!0)}throw u}})()})}close(){return P(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(ce.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return P(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new ep,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return P(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new vi("a track with the same ID has already been published");return new Promise((t,n)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(Ne.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return P(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return P(this,void 0,void 0,function*(){var n,s;if(this.pcManager&&this.pcManager.currentState!==kt.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new ab(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(ce.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(o,a)=>{this.client.sendIceCandidate(o,a)},this.pcManager.onPublisherOffer=(o,a)=>{this.client.sendOffer(o,a)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(o,a,c)=>P(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(o),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),o===kt.CONNECTED){const u=this.pcState===Ln.New;this.pcState=Ln.Connected,u&&this.emit(ce.Connected,e)}else o===kt.FAILED&&(this.pcState===Ln.Connected||this.pcState===Ln.Reconnecting)&&(this.pcState=Ln.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?ds.RR_SUBSCRIBER_FAILED:ds.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===vt.RECONNECTING,d=[kt.FAILED,kt.CLOSING,kt.CLOSED].includes(o);l&&d&&!this._isClosed&&this.emit(ce.Offline)}),this.pcManager.onTrack=o=>{o.streams.length!==0&&this.emit(ce.MediaTrackAdded,o.track,o.streams[0],o.receiver)},Ib((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>P(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>P(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(ce.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(ce.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(ce.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(ce.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(ce.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,n;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",ds.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:dp,regionSettings:e.regions})),e.action){case Fs.DISCONNECT:this.emit(ce.Disconnected,e==null?void 0:e.reason),this.close();break;case Fs.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(gl);break;case Fs.RESUME:this.handleDisconnect(gl)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const s=[];e.iceServers.forEach(r=>{const o={urls:r.urls};r.username&&(o.username=r.username),r.credential&&(o.credential=r.credential),s.push(o)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Nr.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(_p,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Sp,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Ke.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,Rb),Pb)}},1e3))}createSender(e,t,n){return P(this,void 0,void 0,function*(){if(Hc())return yield this.createTransceiverRTCRtpSender(e,t,n);if(Wc())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Ut("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(Hc())return this.createSimulcastTransceiverSender(e,t,n,s);if(Wc())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Ut("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ut("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Wi(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ut("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ut("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return P(this,void 0,void 0,function*(){var t,n,s;if(!this._isClosed){if(this.attemptingReconnect){He.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Nr.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:kt.NEW)===kt.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let o=!0;r instanceof Ut?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),o=!1):r instanceof Vs||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",ds.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(ce.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return P(this,void 0,void 0,function*(){var t,n,s;try{if(!this.url||!this.token)throw new Ut("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(ce.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Vs;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(o){throw o instanceof Ne&&o.reason===gt.NotAllowed?new Ut("could not reconnect, token might be expired"):new Vs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(ce.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==vt.CONNECTED)throw new Vs("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(ce.Restarted)}catch(r){const o=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return P(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Ut("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ut("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(ce.Resuming);let n;try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof Ne&&s.reason===gt.NotAllowed?new Ut("could not reconnect, token might be expired"):s instanceof Ne&&s.reason===gt.LeaveRequest?s:new Vs(r)}if(this.emit(ce.SignalResumed),n){const s=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==vt.CONNECTED)throw new Vs("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),n!=null&&n.lastMessageSeq&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(ce.Resumed)})}waitForPCInitialConnection(e,t){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ut("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return P(this,void 0,void 0,function*(){this.pcState=Ln.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Zt(wb),!this.pcManager)throw new Ut("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ln.Connected}catch(e){throw this.pcState=Ln.Disconnected,Ne.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,n,s){return P(this,void 0,void 0,function*(){const r=new cn({destinationIdentities:[e],kind:Ke.RELIABLE,value:{case:"rpcResponse",value:new mc({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,Ke.RELIABLE)})}publishRpcAck(e,t){return P(this,void 0,void 0,function*(){const n=new cn({destinationIdentities:[e],kind:Ke.RELIABLE,value:{case:"rpcAck",value:new pc({requestId:t})}});yield this.sendDataPacket(n,Ke.RELIABLE)})}sendDataPacket(e,t){return P(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=zy(e);if(r){const o=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new mh({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}t===Ke.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===Ke.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=n.byteLength}if(this.attemptingReconnect)return;s.send(n)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return P(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Ke.RELIABLE);const t=this.dataChannelForKind(Ke.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(n=>{t.send(n.data)})),this.updateAndEmitDCBufferStatus(Ke.RELIABLE)})}waitForBufferStatusLow(e){return new gn((t,n)=>P(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>n(new Ut("engine closed"));for(this.once(ce.Closing,s);!this.dcBufferStatus.get(e);)yield Zt(10);this.off(ce.Closing,s),t()}}))}ensureDataTransportConnected(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!n.pcManager)throw new Ut("PC manager is closed");const o=s?n.pcManager.subscriber:n.pcManager.publisher,a=s?"Subscriber":"Publisher";if(!o)throw Ne.internal("".concat(a," connection not set"));let c=!1;!s&&!n.dataChannelForKind(t,s)&&(n.createDataChannels(),c=!0),!c&&!s&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&n.negotiate().catch(u=>{He.error(u,n.logContext)});const l=n.dataChannelForKind(t,s);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<d;){if(o.isICEConnected&&((r=n.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield Zt(50)}throw Ne.internal("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()))})()})}ensurePublisherConnected(e){return P(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==kt.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return P(this,void 0,void 0,function*(){return new gn((e,t)=>P(this,void 0,void 0,function*(){if(!this.pcManager){t(new zs("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new zs("cannot negotiate on closed engine")),this.on(ce.Closing,s),this.pcManager.publisher.once(Xs.RTPVideoPayloadTypes,r=>{const o=new Map;r.forEach(a=>{const c=a.codec.toLowerCase();Cy(c)&&o.set(a.payload,c)}),this.emit(ce.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof zs&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ds.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(ce.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===Ke.LOSSY)return this.lossyDCSub;if(e===Ke.RELIABLE)return this.reliableDCSub}else{if(e===Ke.LOSSY)return this.lossyDC;if(e===Ke.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,s,r,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const a=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=(n=this.pcManager.subscriber)===null||n===void 0?void 0:n.getRemoteDescription(),d=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(o=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,f=new Array;e.forEach(g=>{g.isDesired!==u&&h.push(g.trackSid),g.isEnabled||f.push(g.trackSid)}),this.client.sendSyncState(new Tc({answer:this.pcManager.mode==="publisher-only"?c?$s({sdp:c.sdp,type:c.type}):void 0:d?$s({sdp:d.sdp,type:d.type}):void 0,offer:this.pcManager.mode==="publisher-only"?a?$s({sdp:a.sdp,type:a.type}):void 0:l?$s({sdp:l.sdp,type:l.type}):void 0,subscription:new Va({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:oy(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((g,v)=>new Uh({publisherSid:v,lastSeq:g}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Fh({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(Ke.LOSSY),zn.PUBLISHER),t(this.dataChannelForKind(Ke.RELIABLE),zn.PUBLISHER),t(this.dataChannelForKind(Ke.LOSSY,!0),zn.SUBSCRIBER),t(this.dataChannelForKind(Ke.RELIABLE,!0),zn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Jt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){yn()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){yn()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(n){const s=Object.entries(this.midToTrackId).find(r=>{let[o]=r;return o===n});if(s)return s[1]}}}function Ib(i){return i!==void 0&&i>13}function xp(i,e){const t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;const n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}class Tp{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new In("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),ln.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new In("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),ln.LengthExceeded)}}constructor(e,t,n,s){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class Db extends Tp{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Dn,n=null,s=null;if(this.signal){const o=this.signal;s=()=>{var a;(a=t.reject)===null||a===void 0||a.call(t,o.reason)},o.addEventListener("abort",s),n=o}const r=()=>{e.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var o,a;try{const{done:c,value:l}=yield Promise.race([e.read(),t.promise,(a=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw r(),c}}),return(){return P(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,s,r,o;let a=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=gi(c),u;u=yield d.next(),n=u.done,!n;l=!0){o=u.value,l=!1;const h=o;a.add(h)}}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return Array.from(a)})()})}}class Lb extends Tp{constructor(e,t,n,s){super(e,t,n,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Qa(e.chunkIndex),s=this.receivedChunks.get(n);if(s&&s.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let n=new Dn,s=null,r=null;if(this.signal){const a=this.signal;r=()=>{var c;(c=n.reject)===null||c===void 0||c.call(n,a.reason)},a.addEventListener("abort",r),s=a}const o=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var a,c;try{const{done:l,value:d}=yield Promise.race([e.read(),n.promise,(c=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(d);let u;try{u=t.decode(d.content)}catch(h){throw new In("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),ln.DecodeFailed)}return{done:!1,value:u}}}catch(l){throw o(),l}}),return(){return P(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,s,r,o;let a="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=gi(c),u;u=yield d.next(),n=u.done,!n;l=!0)o=u.value,l=!1,a+=o}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return a})()})}}class Nb{constructor(){this.log=He,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new In('A text stream handler for topic "'.concat(e,'" has already been set.'),ln.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new In('A byte stream handler for topic "'.concat(e,'" has already been set.'),ln.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,n,s,r;const o=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),a=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(o.length>0||a.length>0){const c=new In("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),ln.AbnormalEnd);for(const[l,d]of a)(n=(t=d.outOfBandFailureRejectingFuture).reject)===null||n===void 0||n.call(t,c),this.byteStreamControllers.delete(l);for(const[l,d]of o)(r=(s=d.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e,t){return P(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,n){return P(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let o;const a=new Dn;a.promise.catch(d=>{this.log.error(d)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Qa(e.timestamp),attributes:e.attributes,encryptionType:n},l=new ReadableStream({start:d=>{if(o=d,this.textStreamControllers.has(e.streamId))throw new In("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ln.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new Db(c,l,Qa(e.totalLength),a),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o;const a=new Dn;a.promise.catch(d=>{this.log.error(d)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n},l=new ReadableStream({start:d=>{if(o=d,this.textStreamControllers.has(e.streamId))throw new In("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ln.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new Lb(c,l,Qa(e.totalLength),a),{identity:t})}})}handleStreamChunk(e,t){const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new In("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ln.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new In("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),ln.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new In("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ln.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new In("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),ln.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Cp{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return P(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Ob extends Cp{}class Ub extends Cp{}const Ep=15e3;class Fb{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return P(this,void 0,void 0,function*(){var n;const s=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(n=t==null?void 0:t.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(u,h)=>{var f;c[h]=u;const g=c.reduce((v,m)=>v+m,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},d=yield this.streamText({streamId:s,totalSize:o,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:a,attributes:t==null?void 0:t.attributes});return yield d.write(e),l(1,0),yield d.close(),t!=null&&t.attachments&&a&&(yield Promise.all(t.attachments.map((u,h)=>P(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{l(f,h+1)}})})))),d.info})}streamText(e){return P(this,void 0,void 0,function*(){var t,n,s;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),o={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e==null?void 0:e.topic)!==null&&n!==void 0?n:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?Ht.GCM:Ht.NONE},a=new Oa({streamId:r,mimeType:o.mimeType,topic:o.topic,timestamp:ms(o.timestamp),totalLength:ms(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new Ah({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?gc.UPDATE:gc.CREATE})}}),c=e==null?void 0:e.destinationIdentities,l=new cn({destinationIdentities:c,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(l,Ke.RELIABLE);let d=0;const u=this.engine,h=new WritableStream({write(v){return P(this,void 0,void 0,function*(){for(const m of Py(v,Ep)){const p=new Ua({content:m,streamId:r,chunkIndex:ms(d)}),T=new cn({destinationIdentities:c,value:{case:"streamChunk",value:p}});yield u.sendDataPacket(T,Ke.RELIABLE),d+=1}})},close(){return P(this,void 0,void 0,function*(){const v=new Fa({streamId:r}),m=new cn({destinationIdentities:c,value:{case:"streamTrailer",value:v}});yield u.sendDataPacket(m,Ke.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let f=()=>P(this,void 0,void 0,function*(){yield g.close()});u.once(ce.Closing,f);const g=new Ob(h,o,()=>this.engine.off(ce.Closing,f));return g})}sendFile(e,t){return P(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return P(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=n==null?void 0:n.mimeType)!==null&&s!==void 0?s:t.type,topic:n==null?void 0:n.topic,destinationIdentities:n==null?void 0:n.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o,a;const c=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),l=e==null?void 0:e.destinationIdentities,d={id:c,mimeType:(n=e==null?void 0:e.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(s=e==null?void 0:e.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?Ht.GCM:Ht.NONE},u=new Oa({totalLength:ms((a=d.size)!==null&&a!==void 0?a:0),mimeType:d.mimeType,streamId:c,topic:d.topic,timestamp:ms(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new Rh({name:d.name})}}),h=new cn({destinationIdentities:l,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,Ke.RELIABLE);let f=0;const g=new on,v=this.engine,m=this.log,p=new WritableStream({write(E){return P(this,void 0,void 0,function*(){const y=yield g.lock();let S=0;try{for(;S<E.byteLength;){const C=E.slice(S,S+Ep),w=new cn({destinationIdentities:l,value:{case:"streamChunk",value:new Ua({content:C,streamId:c,chunkIndex:ms(f)})}});yield v.sendDataPacket(w,Ke.RELIABLE),f+=1,S+=C.byteLength}}finally{y()}})},close(){return P(this,void 0,void 0,function*(){const E=new Fa({streamId:c}),y=new cn({destinationIdentities:l,value:{case:"streamTrailer",value:E}});yield v.sendDataPacket(y,Ke.RELIABLE)})},abort(E){m.error("Sink error:",E)}});return new Ub(p,d)})}}class Mp extends Z{constructor(e,t,n,s,r){super(e,n,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ae.Muted:ae.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(ae.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),ul)),cy()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:s,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(ae.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Bb extends Mp{constructor(e,t,n,s,r,o){super(e,t,Z.Kind.Audio,n,o),this.monitorReceiver=()=>P(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=eo(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;ei()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(ei())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return P(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(qc(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&qc(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{n.connect(s),n=s}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(ae.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(ae.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return P(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const vl=100;class zb extends Mp{constructor(e,t,n,s,r){super(e,t,Z.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>P(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=eo(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=al(()=>{this.updateDimensions()},vl),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===Z.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Hs(this._mediaStreamTrack,t):Gs(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Vb(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return P(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&n!==""&&s.get(n)&&(t.mimeType=s.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;const s=this.elementInfos.reduce((c,l)=>Math.max(c,l.visibilityChangedAt||0),0),r=!((n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,o=this.elementInfos.some(c=>c.pictureInPicture),a=this.elementInfos.some(c=>c.visible)&&!r||o;if(!(this.lastVisible===a&&!e)){if(!a&&Date.now()-s<vl){Jt.setTimeout(()=>{this.updateVisibility()},vl);return}this.lastVisible=a,this.emit(ae.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let n=0,s=0;const r=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*r,c=o.height()*r;a+c>n+s&&(n=a,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:n,height:s},this.emit(ae.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Hf():t||(Hf()>2?2:1)}}class Vb{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:o}=n;r===this.element&&(this.isIntersecting=o,this.isPiP=Xr(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var n,s,r;(s=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Xr(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=Xr(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??yl(e),this.isPiP=yn()&&Xr(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=yl(this.element),this.isPiP=Xr(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,qf().observe(this.element),Wf().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,s,r;(e=qf())===null||e===void 0||e.unobserve(this.element),(t=Wf())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function Xr(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?yl(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function yl(i,e){const t=e||window;let n=i.offsetTop,s=i.offsetLeft;const r=i.offsetWidth,o=i.offsetHeight,{hidden:a}=i,{display:c}=getComputedStyle(i);for(;i.offsetParent;)i=i.offsetParent,n+=i.offsetTop,s+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&n+o>t.pageYOffset&&s+r>t.pageXOffset&&!a&&c!=="none"}class bi extends Zn.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=Ht.NONE,this.log=He,this.handleMuted=()=>{this.emit(ae.Muted)},this.handleUnmuted=()=>{this.emit(ae.Unmuted)},this.log=mi((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Vn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=Z.Source.Unknown}setTrack(e){this.track&&(this.track.off(ae.Muted,this.handleMuted),this.track.off(ae.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ae.Muted,this.handleMuted),e.on(ae.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Je(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Ht.NONE}get audioTrack(){if(ni(this.track))return this.track}get videoTrack(){if(Wi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Z.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Z.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(i.PermissionStatus||(i.PermissionStatus={}))})(bi||(bi={}));class bl extends bi{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(ae.Ended)},this.handleCpuConstrained=()=>{this.track&&Wi(this.track)&&this.emit(ae.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(ae.Ended,this.handleTrackEnded),this.track.off(ae.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ae.Ended,this.handleTrackEnded),e.on(ae.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(ni(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(jt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(jt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(jt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(jt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(jt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(jt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function io(i,e){return P(this,void 0,void 0,function*(){i??(i={});let t=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=Of(i);let o=r.audio,a=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),s&&typeof r.video=="object"&&(r.video.processor=s),i.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=Df(r,cp,lp),l=Vc(c),d=navigator.mediaDevices.getUserMedia(l);r.audio&&($t.userMediaPromiseMap.set("audioinput",d),d.catch(()=>$t.userMediaPromiseMap.delete("audioinput"))),r.video&&($t.userMediaPromiseMap.set("videoinput",d),d.catch(()=>$t.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>P(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let v;const m=f?l.audio:l.video;typeof m!="boolean"&&(v=m);const p=h.getSettings().deviceId;v!=null&&v.deviceId&&Hi(v.deviceId)!==p?v.deviceId=p:v||(v={deviceId:p});const T=mb(h,v,e);return T.kind===Z.Kind.Video?T.source=Z.Source.Camera:T.kind===Z.Kind.Audio&&(T.source=Z.Source.Microphone),T.mediaStream=u,ni(T)&&n?yield T.setProcessor(n):Wi(T)&&s&&(yield T.setProcessor(s)),T})))}catch(u){if(!t)throw u;return io(Object.assign(Object.assign({},i),{audio:o,video:a}),e)}})}function Gb(i){return P(this,void 0,void 0,function*(){return(yield io({audio:!1,video:!0}))[0]})}function Hb(i){return P(this,void 0,void 0,function*(){return(yield io({audio:!0,video:!1}))[0]})}var Ki;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(Ki||(Ki={}));function Wb(i){switch(i){case Lr.EXCELLENT:return Ki.Excellent;case Lr.GOOD:return Ki.Good;case Lr.POOR:return Ki.Poor;case Lr.LOST:return Ki.Lost;default:return Ki.Unknown}}class wp extends Zn.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Or.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Os.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,s,r,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Or.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Ki.Unknown,this.log=He,this.log=mi((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:Vn.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Dn,this.once(le.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(Z.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Z.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Z.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Os.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Os.ACTIVE&&this.emit(le.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(le.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(le.ParticipantNameChanged,e)}_setAttributes(e){const t=ly(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(le.AttributesChanged,t)}setPermissions(e){var t,n,s,r,o,a;const c=this.permissions,l=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,l&&this.emit(le.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(le.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Wb(e),t!==this._connectionQuality&&this.emit(le.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>ni(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(ae.Muted,()=>{this.emit(le.TrackMuted,e)}),e.on(ae.Unmuted,()=>{this.emit(le.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Z.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Z.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function qb(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Nh({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}class jb extends wp{constructor(e,t,n,s,r,o){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Ht.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Dn)},this.handleReconnected=()=>{var a,c;(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||c===void 0||c.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var a,c,l,d,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||c===void 0||c.call(a,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(l=this.signalConnectedFuture).reject)===null||d===void 0||d.call(l,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var c,l;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Dn),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=a=>{const{requestId:c,reason:l,message:d}=a,u=this.pendingSignalRequests.get(c);u&&(l!==Cc.OK&&u.reject(new kf(d,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let c=a.value.value,l=null,d=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(d=It.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,d);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>qb(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,c)=>{if(c===void 0&&(c=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Je(a)));return}this.engine.updateMuteStatus(a.sid,c)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Je(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Je(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const c=this.audioTrackPublications.get(a.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(a,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),Je(c))),this.emit(le.LocalTrackCpuConstrained,a,c)},this.handleSubscribedQualityUpdate=a=>P(this,void 0,void 0,function*(){var c,l,d,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(!f.videoTrack)return;const g=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var v=!0,m=gi(g),p;p=yield m.next(),c=p.done,!c;v=!0){u=p.value,v=!1;const T=u;sy(T)&&(this.log.debug("publish ".concat(T," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Je(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,T,f.options))}}catch(T){l={error:T}}finally{try{!v&&!c&&(d=m.return)&&(yield d.call(m))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=a=>{const c=this.trackPublications.get(a.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=a=>P(this,void 0,void 0,function*(){if(a.source===Z.Source.ScreenShare||a.source===Z.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Je(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(yi(a)||qi(a))try{if(yn())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:a.source===Z.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),Je(a))),c.onchange=()=>{c.state!=="denied"&&(a.isMuted||a.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Je(a))),yi(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Je(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=s,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Ht.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(ce.RemoteMute,(n,s)=>{const r=this.trackPublications.get(n);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(ce.Connected,this.handleReconnected).on(ce.SignalConnected,this.handleSignalConnected).on(ce.SignalRestarted,this.handleReconnected).on(ce.SignalResumed,this.handleReconnected).on(ce.Restarting,this.handleReconnecting).on(ce.Resuming,this.handleReconnecting).on(ce.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(ce.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(ce.Closing,this.handleClosing).on(ce.SignalRequestResponse,this.handleSignalRequestResponse).on(ce.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return P(this,arguments,void 0,function(t){var n=this;let{metadata:s,name:r,attributes:o}=t;return(function*(){return new gn((a,c)=>P(n,void 0,void 0,function*(){var l,d;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=s??this.metadata)!==null&&l!==void 0?l:"",(d=r??this.name)!==null&&d!==void 0?d:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),u=!0},values:{name:r,metadata:s,attributes:o}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!o||Object.entries(o).every(g=>{let[v,m]=g;return this.attributes[v]===m||m===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),a();return}yield Zt(50)}c(new kf("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(Z.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(Z.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(Z.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){this.encryptionType=e?Ht.GCM:Ht.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){return P(this,void 0,void 0,function*(){var r,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case Z.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case Z.Source.Microphone:c=yield this.createTracks({audio:(o=n)!==null&&o!==void 0?o:!0});break;case Z.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new vi(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(le.MediaDevicesError,l,Gc(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===Z.Source.Microphone&&ni(l)&&d.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Je(u))),l.push(this.publishTrack(u,s));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===Z.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(Z.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return P(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(Z.Source.Camera)||this.pendingPublishing.has(Z.Source.Microphone))){this.pendingPublishing.add(Z.Source.Camera),this.pendingPublishing.add(Z.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(Z.Source.Camera),this.pendingPublishing.delete(Z.Source.Microphone)}}})}createTracks(e){return P(this,void 0,void 0,function*(){var t,n;e??(e={});const s=Df(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield io(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(ni(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=Z.Source.Microphone,this.emit(le.AudioStreamAcquired)),Wi(a)&&(this.cameraError=void 0,a.source=Z.Source.Camera),a))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return P(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Oc("getDisplayMedia not supported");e.resolution===void 0&&!yy()&&(e.resolution=Bc.h1080fps30.resolution);const t=ay(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new vi("no video track found");const r=new no(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Z.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const o=[r];if(n.getAudioTracks().length>0){this.emit(le.AudioStreamAcquired);const a=new to(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=Z.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){return P(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,c,l,d;yi(n)&&n.setAudioContext(r.audioContext),yield(a=r.reconnectFuture)===null||a===void 0?void 0:a.promise,r.republishPromise&&!o&&(yield r.republishPromise),qs(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let u;if(n instanceof MediaStreamTrack)u=n.getConstraints();else{u=n.constraints;let p;switch(n.source){case Z.Source.Microphone:p="audioinput";break;case Z.Source.Camera:p="videoinput"}p&&r.activeDeviceMap.has(p)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(p)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new to(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new no(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new vi("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(p=>{p.track&&p.track===n&&(h=p)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),Je(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),g="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,v=(c=f.forceStereo)!==null&&c!==void 0?c:g;v&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),Je(n))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=f.dtx)!==null&&l!==void 0||(f.dtx=!1),(d=f.red)!==null&&d!==void 0||(f.red=!1)),!_y()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},r.logContext)),f.simulcast=!1),f.source&&(n.source=f.source);const m=new Promise((p,T)=>P(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==vt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Je(n)}));let E=!1;const y=setTimeout(()=>{E=!0,n.stop(),T(new Pf("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(y),E)return;const S=yield this.publish(n,f,v);p(S)}else try{const E=yield this.publish(n,f,v);p(E)}catch(E){T(E)}}catch(E){T(E)}}));r.pendingPublishPromises.set(n,m);try{return yield m}catch(p){throw p}finally{r.pendingPublishPromises.delete(n)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Dn),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Je(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(s=>dy(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Je(e))),!1)}publish(e,t,n){return P(this,void 0,void 0,function*(){var s,r,o,a,c,l,d,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Pf("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(_=>qs(e)&&_.source===e.source)&&e.source!==Z.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Je(e))),t.stopMicTrackOnMute&&ni(e)&&(e.stopOnMute=!0),e.source===Z.Source.ScreenShare&&fs()&&(t.simulcast=!1),t.videoCodec==="av1"&&!my()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!gy()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=cl),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(_=>t.videoCodec===Vr(_.mime))||(t.videoCodec=Vr(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(ae.Muted,this.onTrackMuted),e.on(ae.Unmuted,this.onTrackUnmuted),e.on(ae.Ended,this.handleTrackEnded),e.on(ae.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ae.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ae.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],p=!(!((s=t.dtx)!==null&&s!==void 0)||s),T=e.getSourceTrackSettings();T.autoGainControl&&m.push(jt.TF_AUTO_GAIN_CONTROL),T.echoCancellation&&m.push(jt.TF_ECHO_CANCELLATION),T.noiseSuppression&&m.push(jt.TF_NOISE_SUPPRESSION),T.channelCount&&T.channelCount>1&&m.push(jt.TF_STEREO),p&&m.push(jt.TF_NO_DTX),yi(e)&&e.hasPreConnectBuffer&&m.push(jt.TF_PRECONNECT_BUFFER);const E=new Ur({cid:e.mediaStreamTrack.id,name:t.name,type:Z.kindToProto(e.kind),muted:e.isMuted,source:Z.sourceToProto(e.source),disableDtx:p,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:m});let y;if(e.kind===Z.Kind.Video){let _={width:0,height:0};try{_=yield e.waitForDimensions()}catch{const R=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:zr.h720.resolution;_={width:R.width,height:R.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Je(e)),{dims:_}))}E.width=_.width,E.height=_.height,qi(e)&&(Gn(v)&&(e.source===Z.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Je(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),E.simulcastCodecs=[new yc({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:cl}),t.backupCodec&&v!==t.backupCodec.codec&&E.encryption===Ht.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),E.simulcastCodecs.push(new yc({codec:t.backupCodec.codec,cid:""})))),y=pl(e.source===Z.Source.ScreenShare,E.width,E.height,t),E.layers=bp(E.width,E.height,y,Gn(t.videoCodec))}else e.kind===Z.Kind.Audio&&(y=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Ut("cannot publish track when not connected");const S=()=>P(this,void 0,void 0,function*(){var _,x,R;if(!this.engine.pcManager)throw new Ut("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),this.emit(le.LocalSenderCreated,e.sender,e),qi(e)&&((_=t.degradationPreference)!==null&&_!==void 0||(t.degradationPreference=Eb(e)),e.setDegradationPreference(t.degradationPreference)),y)if(fs()&&e.kind===Z.Kind.Audio){let O;for(const F of this.engine.pcManager.publisher.getTransceivers())if(F.sender===e.sender){O=F;break}O&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:O,codec:"opus",maxbr:!((x=y[0])===null||x===void 0)&&x.maxBitrate?y[0].maxBitrate/1e3:0})}else e.codec&&Gn(e.codec)&&(!((R=y[0])===null||R===void 0)&&R.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:E.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let C;const w=new Promise((_,x)=>P(this,void 0,void 0,function*(){var R;try{C=yield this.engine.addTrack(E),_(C)}catch(O){e.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(F=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),Je(e)),{error:F}))})),x(O)}}));if(this.enabledPublishVideoCodecs.length>0)C=(yield Promise.all([w,S()]))[0];else{C=yield w;let _;if(C.codecs.forEach(x=>{_===void 0&&(_=x.mimeType)}),_&&e.kind===Z.Kind.Video){const x=Vr(_);x!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Je(e)),{codec:x})),t.videoCodec=x,y=pl(e.source===Z.Source.ScreenShare,E.width,E.height,t))}yield S()}const k=new bl(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(k.on(ae.CpuConstrained,_=>this.onTrackCpuConstrained(_,k)),k.options=t,e.sid=C.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:C})),qi(e)?e.startMonitor(this.engine.client):yi(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(le.LocalTrackPublished,k),yi(e)&&C.audioFeatures.includes(jt.TF_PRECONNECT_BUFFER)){const _=e.getPreConnectBuffer(),x=e.getPreConnectBufferMimeType();this.on(le.LocalTrackSubscribed,R=>{if(R.trackSid===C.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),Je(e))),e.stopPreConnectBuffer()}}),_&&new Promise((O,F)=>P(this,void 0,void 0,function*(){var q,K,G,W,te,ye;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Je(e)));const Ve=setTimeout(()=>{F(new Error("agent not active within 10 seconds"))},1e4),Mt=yield this.waitUntilActiveAgentPresent();clearTimeout(Ve),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Je(e)));const pt=yield this.streamBytes({name:"preconnect-buffer",mimeType:x,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Mt.identity],attributes:{trackId:k.trackSid,sampleRate:String((te=T.sampleRate)!==null&&te!==void 0?te:"48000"),channels:String((ye=T.channelCount)!==null&&ye!==void 0?ye:"1")}});try{for(var de=!0,_e=gi(_),Ge;Ge=yield _e.next(),q=Ge.done,!q;de=!0){W=Ge.value,de=!1;const Y=W;yield pt.write(Y)}}catch(Y){K={error:Y}}finally{try{!de&&!q&&(G=_e.return)&&(yield G.call(_e))}finally{if(K)throw K.error}}yield pt.close(),O()}catch(Ve){F(Ve)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Je(e)))}).catch(O=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Je(e)),{error:O}))})}return k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return P(this,void 0,void 0,function*(){var s;if(this.encryptionType!==Ht.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new vi("track is not published");if(!qi(e))throw new vi("track is not a video track");const o=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),n),a=xb(e,t,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Je(e)));return}const c=e.addSimulcastTrack(t,a);if(!c)return;const l=new Ur({cid:c.mediaStreamTrack.id,type:Z.kindToProto(e.kind),muted:e.isMuted,source:Z.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=bp(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new Ut("cannot publish track when not connected");const d=()=>P(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,t){return P(this,void 0,void 0,function*(){var n,s;if(qs(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Je(e))),yield l)}const r=this.getPublicationForTrack(e),o=r?Je(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=r.track,e.off(ae.Muted,this.onTrackMuted),e.off(ae.Unmuted,this.onTrackUnmuted),e.off(ae.Ended,this.handleTrackEnded),e.off(ae.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ae.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ae.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<kt.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),qi(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case Z.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Z.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(le.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return P(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new gn((r,o)=>P(n,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),a.push(c))}),yield Promise.all(a.map(c=>P(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),s&&!l.isMuted&&l.source!==Z.Source.ScreenShare&&l.source!==Z.Source.ScreenShareAudio&&(yi(l)||qi(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),r()}catch(a){a instanceof Error?o(a):o(new Error(String(a)))}finally{this.republishPromise=void 0}})),yield n.republishPromise})()})}publishData(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?Ke.RELIABLE:Ke.LOSSY,o=s.destinationIdentities,a=s.topic;let c=new hc({participantIdentity:n.identity,payload:t,destinationIdentities:o,topic:a});const l=new cn({kind:r,value:{case:"user",value:c}});yield n.engine.sendDataPacket(l,r)})()})}publishDtmf(e,t){return P(this,void 0,void 0,function*(){const n=new cn({kind:Ke.RELIABLE,value:{case:"sipDtmf",value:new yh({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Ke.RELIABLE)})}sendChatMessage(e,t){return P(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new cn({value:{case:"chatMessage",value:new Na(Object.assign(Object.assign({},n),{timestamp:wt.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,Ke.RELIABLE),this.emit(le.ChatMessage,n),n})}editChatMessage(e,t){return P(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new cn({value:{case:"chatMessage",value:new Na(Object.assign(Object.assign({},n),{timestamp:wt.parse(n.timestamp),editTimestamp:wt.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,Ke.RELIABLE),this.emit(le.ChatMessage,n),n})}sendText(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:n,payload:s,responseTimeout:r=15e3}=e;const o=7e3,a=o+1e3;return new gn((c,l)=>P(this,void 0,void 0,function*(){var d,u,h,f;if(dl(s)>up){l(It.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||u===void 0)&&u.version&&ti((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){l(It.builtIn("UNSUPPORTED_SERVER"));return}const g=Math.max(r,a),v=crypto.randomUUID();yield this.publishRpcRequest(t,v,n,s,g);const m=setTimeout(()=>{this.pendingAcks.delete(v),l(It.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(p)},o);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(m)},participantIdentity:t});const p=setTimeout(()=>{this.pendingResponses.delete(v),l(It.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(T,E)=>{clearTimeout(p),this.pendingAcks.has(v)&&(this.log.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(m)),E?l(E):c(T??"")},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const s=this.pendingResponses.get(e);s?(s.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,s,r){return P(this,void 0,void 0,function*(){const o=new cn({destinationIdentities:[e],kind:Ke.RELIABLE,value:{case:"rpcRequest",value:new fc({id:t,method:n,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(o,Ke.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:s}]of this.pendingResponses)n===e&&(s(null,It.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var n,s;const r=this.trackPublications.get(t.sid);if(r){const o=r.isMuted||((s=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&s!==void 0?s:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Je(r)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0):!1}setActiveAgent(e){var t,n,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||n===void 0||n.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Dn),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(yi(s)||qi(s))&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}waitForPendingPublicationOfSource(e){return P(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[o]=r;return o.source===e});if(s)return s[1];yield Zt(20)}})}}class $b extends bi{constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(ae.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new Va({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new _h({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ae.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?bi.SubscriptionStatus.Unsubscribed:super.isSubscribed?bi.SubscriptionStatus.Subscribed:bi.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?bi.PermissionStatus.Allowed:bi.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.height)===e.height||(Jc(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Jc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:En.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(ae.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(ae.VisibilityChanged,this.handleVisibilityChange),s.off(ae.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(ae.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ae.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ae.VisibilityChanged,this.handleVisibilityChange),e.on(ae.Ended,this.handleEnded),this.emit(ae.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(ae.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?ae.Muted:ae.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(ae.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ae.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Jc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new kh({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Z.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Uf(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const n=uy(this.trackInfo,this.requestedMaxQuality);n&&Uf(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:En.HIGH})),e.quality=En.HIGH)}this.emit(ae.UpdateSettings,e)}}class so extends wp{static fromParticipantInfo(e,t,n){return new so(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,s,r,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Or.STANDARD;super(t,n||"",s,r,o,a,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(ae.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Je(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(ae.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(ae.SubscriptionPermissionChanged,t=>{this.emit(le.TrackSubscriptionPermissionChanged,e,t)}),e.on(ae.SubscriptionStatusChanged,t=>{this.emit(le.TrackSubscriptionStatusChanged,e,t)}),e.on(ae.Subscribed,t=>{this.emit(le.TrackSubscribed,t,e)}),e.on(ae.Unsubscribed,t=>{this.emit(le.TrackUnsubscribed,t,e)}),e.on(ae.SubscriptionFailed,t=>{this.emit(le.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Z.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Z.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,s,r,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(d=>{!a&&e.kind===d.kind.toString()&&(a=d)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(le.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,s,r,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Je(a))),this.emit(le.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new zb(e,t,s,r):l=new Bb(e,t,s,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(n),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&Yc(l)&&ni(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(s=>{var r,o;let a=this.getTrackPublicationBySid(s.sid);if(a)a.updateInfo(s);else{const c=Z.kindFromProto(s.type);if(!c)return;a=new $b(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(s),n.set(s.sid,a);const l=Array.from(this.trackPublications.values()).find(d=>d.source===(a==null?void 0:a.source));l&&a.source!==Z.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Je(l),newTrack:Je(a)})),this.addTrackPublication(a)}t.set(s.sid,a)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Je(s))),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(le.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case Z.Kind.Audio:this.audioTrackPublications.delete(e);break;case Z.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(le.TrackUnpublished,n)}setAudioOutput(e){return P(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;ni(n.track)&&Yc(n.track)&&t.push(n.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var ot;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(ot||(ot={}));const Xb=4*1e3;class Ks extends Zn.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,n,s,r,o;if(super(),t=this,this.state=ot.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=He,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(a,c,l)=>P(this,void 0,void 0,function*(){var d;if(!vy())throw ei()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===ot.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(ot.Connecting),((d=this.regionUrlProvider)===null||d===void 0?void 0:d.getServerUrl().toString())!==Xf(a)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ws(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new et(a,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(g=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(g)}).catch(g=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:g}))}));const h=(g,v,m)=>P(this,void 0,void 0,function*(){var p,T;this.abortController&&this.abortController.abort();const E=new AbortController;this.abortController=E,u==null||u();try{if(yield js.getInstance().getBackOffPromise(a),E.signal.aborted)throw Ne.cancelled("Connection attempt aborted");yield this.attemptConnection(m??a,c,l,E),this.abortController=void 0,g()}catch(y){if(this.regionUrlProvider&&y instanceof Ne&&y.reason!==gt.Cancelled&&y.reason!==gt.NotAllowed){let S=null;try{this.log.debug("Fetching next region"),S=yield this.regionUrlProvider.getNextBestRegionUrl((p=this.abortController)===null||p===void 0?void 0:p.signal)}catch(C){if(C instanceof Ne&&(C.status===401||C.reason===gt.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(C);return}}[gt.InternalError,gt.ServerUnreachable,gt.Timeout].includes(y.reason)&&(this.log.debug("Adding failed connection attempt to back off"),js.getInstance().addFailedConnectionAttempt(a)),S&&!(!((T=this.abortController)===null||T===void 0)&&T.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(y.message,". Retrying with another region: ").concat(S),this.logContext),this.recreateEngine(),yield h(g,v,S)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,$f(y)),v(y))}else{let S=Bn.UNKNOWN_REASON;y instanceof Ne&&(S=$f(y)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,S),v(y)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Dn((g,v)=>{h(g,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,c,l,d,u,h)=>P(this,void 0,void 0,function*(){var f,g,v;const m=yield l.join(a,c,{autoSubscribe:d.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:d.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:d.websocketTimeout},h.signal,!u.singlePeerConnection);let p=m.serverInfo;if(p||(p={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=p,this.log.debug("connected to Livekit Server ".concat(Object.entries(p).map(T=>{let[E,y]=T;return"".concat(E,": ").concat(y)}).join(", ")),{room:(f=m.room)===null||f===void 0?void 0:f.name,roomSid:(g=m.room)===null||g===void 0?void 0:g.sid,identity:(v=m.participant)===null||v===void 0?void 0:v.identity}),!p.version)throw new Q0("unknown server version");return p.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),m}),this.applyJoinResponse=a=>{const c=a.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([c,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,c,l,d)=>P(this,void 0,void 0,function*(){var u,h;this.state===ot.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ll),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(a,c,this.engine,this.connOptions,this.options,d);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(ne.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const g=d.signal.aborted?Ne.cancelled("Signal connection aborted"):Ne.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(g.message="".concat(g.message,": ").concat(f.message)),f instanceof Ne&&(g.reason=f.reason,g.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),g}if(d.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),Ne.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,d)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}yn()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),yn()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ot.Connected),this.emit(ne.Connected),js.getInstance().resetFailedConnectionAttempts(a),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];return P(t,[...c],void 0,function(){var d=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,g;const v=yield d.disconnectLock.lock();try{if(d.state===ot.Disconnected){d.log.debug("already disconnected",d.logContext);return}if(d.log.info("disconnect from room",Object.assign({},d.logContext)),d.state===ot.Connecting||d.state===ot.Reconnecting||d.isResuming){const m="Abort connection attempt due to user initiated disconnect";d.log.warn(m,d.logContext),(h=d.abortController)===null||h===void 0||h.abort(m),(g=(f=d.connectFuture)===null||f===void 0?void 0:f.reject)===null||g===void 0||g.call(f,Ne.cancelled("Client initiated disconnect")),d.connectFuture=void 0}d.engine&&(d.engine.client.isDisconnected||(yield d.engine.client.sendLeave()),yield d.engine.close()),d.handleDisconnect(u,Bn.CLIENT_INITIATED),d.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>P(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>P(this,void 0,void 0,function*(){const a=[],c=vn();if(c&&c.os==="iOS"){const l="livekit-dummy-audio-el";let d=document.getElementById(l);if(!d){d=document.createElement("audio"),d.id=l,d.autoplay=!0,d.hidden=!0;const u=Kc();u.enabled=!0;const h=new MediaStream([u]);d.srcObject=h,document.addEventListener("visibilitychange",()=>{d&&(d.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(d),this.once(ne.Disconnected,()=>{d==null||d.remove(),d=null})}a.push(d)}this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(d=>{d.track&&d.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>P(this,void 0,void 0,function*(){const a=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(l=>{var d;(d=l.track)===null||d===void 0||d.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(ot.Reconnecting)&&this.emit(ne.Reconnecting)},this.handleSignalRestarted=a=>P(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(ot.Connected),this.emit(ne.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(c=>{var l;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(l=this.sidToIdentity.get(c.sid))!==null&&l!==void 0?l:"");let d=this.remoteParticipants.get(c.identity);c.state===Os.DISCONNECTED?this.handleParticipantDisconnected(c.identity,d):d=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=a=>{const c=[],l={};a.forEach(d=>{if(l[d.sid]=!0,d.sid===this.localParticipant.sid)this.localParticipant.audioLevel=d.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(d.sid);u&&(u.audioLevel=d.level,u.setIsSpeaking(!0),c.push(u))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(d=>{l[d.sid]||(d.audioLevel=0,d.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(ne.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=a=>{const c=new Map;this.activeSpeakers.forEach(d=>{const u=this.remoteParticipants.get(d.identity);u&&u.sid!==d.sid||c.set(d.sid,d)}),a.forEach(d=>{let u=this.getRemoteParticipantBySid(d.sid);d.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=d.level,u.setIsSpeaking(d.active),d.active?c.set(d.sid,u):c.delete(d.sid))});const l=Array.from(c.values());l.sort((d,u)=>u.audioLevel-d.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(ne.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(c=>{const l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;const d=l.getTrackPublicationBySid(c.trackSid);if(!d||!d.track)return;const u=Z.streamStateFromProto(c.state);d.track.setStreamState(u),u!==d.track.streamState&&(l.emit(le.TrackStreamStateChanged,d,d.track.streamState),this.emitWhenConnected(ne.TrackStreamStateChanged,d,d.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);l&&l.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const c=Array.from(this.remoteParticipants.values()).find(d=>d.trackPublications.has(a.trackSid));if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);l&&l.setSubscriptionError(a.err)},this.handleDataPacket=(a,c)=>{const l=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(l,a.value.value,a.kind,c);else if(a.value.case==="transcription")this.handleTranscription(l,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(l,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(l,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,l);else if(a.value.case==="streamHeader"||a.value.case==="streamChunk"||a.value.case==="streamTrailer")this.handleDataStream(a,c);else if(a.value.case==="rpcRequest"){const d=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,d.id,d.method,d.payload,d.responseTimeoutMs,d.version)}},this.handleUserPacket=(a,c,l,d)=>{this.emit(ne.DataReceived,c.payload,a,l,c.topic,d),a==null||a.emit(le.DataReceived,c.payload,l,d)},this.handleSipDtmf=(a,c)=>{this.emit(ne.SipDTMFReceived,c,a),a==null||a.emit(le.SipDTMFReceived,c)},this.handleTranscription=(a,c)=>{const l=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),d=l==null?void 0:l.trackPublications.get(c.trackId),u=My(c,this.transcriptionReceivedTimes);d==null||d.emit(ae.TranscriptionReceived,u),l==null||l.emit(le.TranscriptionReceived,u,d),this.emit(ne.TranscriptionReceived,u,l,d)},this.handleChatMessage=(a,c)=>{const l=wy(c);this.emit(ne.ChatMessage,l,a)},this.handleMetrics=(a,c)=>{this.emit(ne.MetricsReceived,a,c)},this.handleDataStream=(a,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(a,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(ne.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(ne.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ne.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ne.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>P(this,void 0,void 0,function*(){var a;((a=vn())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(ne.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const c=this.roomInfo;this.roomInfo=a,c&&c.metadata!==a.metadata&&this.emitWhenConnected(ne.RoomMetadataChanged,a.metadata),(c==null?void 0:c.activeRecording)!==a.activeRecording&&this.emitWhenConnected(ne.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const l=this.getRemoteParticipantBySid(c.participantSid);l&&l.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(ne.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(ne.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(ne.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(ne.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(ne.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var c;(c=a==null?void 0:a.onPublish)===null||c===void 0||c.call(a,this)},this.onLocalTrackPublished=a=>P(this,void 0,void 0,function*(){var c,l,d,u,h,f;(c=a.track)===null||c===void 0||c.on(ae.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.on(ae.Restarted,this.onLocalTrackRestarted),(h=(u=(d=a.track)===null||d===void 0?void 0:d.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(ne.LocalTrackPublished,a,this.localParticipant),yi(a.track)&&(yield a.track.checkForSilence())&&this.emit(ne.LocalAudioSilenceDetected,a);const g=yield(f=a.track)===null||f===void 0?void 0:f.getDeviceId(!1),v=Gc(a.source);v&&g&&g!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,g),this.emit(ne.ActiveDeviceChanged,v,g))}),this.onLocalTrackUnpublished=a=>{var c,l;(c=a.track)===null||c===void 0||c.off(ae.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.off(ae.Restarted,this.onLocalTrackRestarted),this.emit(ne.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>P(this,void 0,void 0,function*(){const c=yield a.getDeviceId(!1),l=Gc(a.source);l&&c&&c!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,c),this.emit(ne.ActiveDeviceChanged,l,c))}),this.onLocalConnectionQualityChanged=a=>{this.emit(ne.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,c)=>{this.emit(ne.MediaDevicesError,a,c)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(ne.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(ne.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},rb),e),this.log=mi((n=this.options.loggerName)!==null&&n!==void 0?n:Vn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},cp),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},lp),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},sb),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Nb,this.outgoingDataStreamManager=new Fb(this.engine,this.log),this.disconnectLock=new on,this.localParticipant=new jb("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Hi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Hi(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Hi(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),yn()){const a=new AbortController;(o=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||o===void 0||o.call(r,"devicechange",this.handleDeviceChange,{signal:a.signal}),Ks.cleanupRegistry&&Ks.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&("e2eeManager"in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new Vy(n,t),this.e2eeManager.on($i.ParticipantEncryptionStatusChanged,(s,r)=>{Ry(r)&&(this.isE2EEEnabled=s),this.emit(ne.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on($i.EncryptionError,(s,r)=>{const o=r?this.getParticipantByIdentity(r):void 0;this.emit(ne.EncryptionError,s,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===ot.Disconnected?gn.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?gn.resolve(this.roomInfo.sid):new gn((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(ce.RoomUpdate,n),e(s.sid))};this.engine.on(ce.RoomUpdate,n),this.once(ne.Disconnected,()=>{this.engine.off(ce.RoomUpdate,n),t(new Ut("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new kb(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(ce.ParticipantUpdate,this.handleParticipantUpdates).on(ce.RoomUpdate,this.handleRoomUpdate).on(ce.SpeakersChanged,this.handleSpeakersChanged).on(ce.StreamStateChanged,this.handleStreamStateUpdate).on(ce.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(ce.SubscriptionError,this.handleSubscriptionError).on(ce.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(ce.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(ce.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(ce.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ce.DataPacketReceived,this.handleDataPacket).on(ce.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ot.SignalReconnecting)&&this.emit(ne.SignalReconnecting)}).on(ce.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ot.Connected)&&this.emit(ne.Reconnected)}).on(ce.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ot.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(ce.Restarting,this.handleRestarting).on(ce.SignalRestarted,this.handleSignalRestarted).on(ce.Offline,()=>{this.setAndEmitConnectionState(ot.Reconnecting)&&this.emit(ne.Reconnecting)}).on(ce.DCBufferStatusChanged,(e,t)=>{this.emit(ne.DCBufferStatusChanged,e,t)}).on(ce.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:s}=n;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(le.LocalTrackSubscribed,t),this.emitWhenConnected(ne.LocalTrackSubscribed,t,this.localParticipant)}).on(ce.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(ne.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return $t.getInstance().getDevices(e,t)}prepareConnection(e,t){return P(this,void 0,void 0,function*(){if(this.state===ot.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ws(new URL(e))&&t){this.regionUrlProvider=new et(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===ot.Disconnected&&(this.regionUrl=n,yield fetch(qr(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(qr(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return P(this,void 0,void 0,function*(){let n=()=>P(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Jn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Jn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Jn({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Jn({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Jn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Jn({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new Jn({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>P(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Ga({reason:Bn.CLIENT_INITIATED,action:Fs.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Jn({scenario:{case:"subscriberBandwidth",value:ms(t)}});break;case"leave-full-reconnect":s=new Jn({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,c,l,d,u,h,f;let g=!0,v=!1;const m=o?{exact:s}:s;if(n==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const p=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=m;const T=Array.from(r.localParticipant.audioTrackPublications.values()).filter(y=>y.source===Z.Source.Microphone);try{g=(yield Promise.all(T.map(y=>{var S;return(S=y.audioTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(y=>y===!0)}catch(y){throw r.options.audioCaptureDefaults.deviceId=p,y}const E=T.some(y=>{var S,C;return(C=(S=y.track)===null||S===void 0?void 0:S.isMuted)!==null&&C!==void 0?C:!1});g&&E&&(v=!0)}else if(n==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const p=(c=r.getActiveDevice(n))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=m;const T=Array.from(r.localParticipant.videoTrackPublications.values()).filter(y=>y.source===Z.Source.Camera);try{g=(yield Promise.all(T.map(y=>{var S;return(S=y.videoTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(y=>y===!0)}catch(y){throw r.options.videoCaptureDefaults.deviceId=p,y}const E=T.some(y=>{var S,C;return(C=(S=y.track)===null||S===void 0?void 0:S.isMuted)!==null&&C!==void 0?C:!1});g&&E&&(v=!0)}else if(n==="audiooutput"){if(v=!0,!qc()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(l=yield $t.getInstance().normalizeDeviceId("audiooutput",s))!==null&&l!==void 0?l:""),(d=(f=r.options).audioOutput)!==null&&d!==void 0||(f.audioOutput={});const p=(u=r.getActiveDevice(n))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(T=>T.setAudioOutput({deviceId:s})))}catch(T){throw r.options.audioOutput.deviceId=p,T}}return v&&(r.localParticipant.activeDeviceMap.set(n,s),r.emit(ne.ActiveDeviceChanged,n,s)),g})()})}setupLocalParticipantEvents(){this.localParticipant.on(le.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(le.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(le.AttributesChanged,this.onLocalAttributesChanged).on(le.TrackMuted,this.onLocalTrackMuted).on(le.TrackUnmuted,this.onLocalTrackUnmuted).on(le.LocalTrackPublished,this.onLocalTrackPublished).on(le.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(le.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(le.MediaDevicesError,this.onMediaDevicesError).on(le.AudioStreamAcquired,this.startAudio).on(le.ChatMessage,this.onLocalChatMessageSent).on(le.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===ot.Connecting||this.state===ot.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,n),h()},h=()=>{this.off(ne.Reconnected,u),this.off(ne.Connected,u),this.off(ne.Disconnected,h)};this.once(ne.Reconnected,u),this.once(ne.Connected,u),this.once(ne.Disconnected,h);return}if(this.state===ot.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=py(t.id),r=s[0];let o=s[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!a.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(n);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}a=u}a.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(o,", trackId: ").concat(a),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:o,trackId:a}));let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={});const d=c.addSubscribedMediaTrack(e,a,t,n,l);d!=null&&d.isEncrypted&&!this.e2eeManager&&this.emit(ne.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==ot.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(o=>{r.unpublishTrack(o.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var o,a,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((o=r.track)===null||o===void 0||o.detach(),(a=r.track)===null||a===void 0||a.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(le.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(le.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(le.AttributesChanged,this.onLocalAttributesChanged).off(le.TrackMuted,this.onLocalTrackMuted).off(le.TrackUnmuted,this.onLocalTrackUnmuted).off(le.LocalTrackPublished,this.onLocalTrackPublished).off(le.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(le.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(le.MediaDevicesError,this.onMediaDevicesError).off(le.AudioStreamAcquired,this.startAudio).off(le.ChatMessage,this.onLocalChatMessageSent).off(le.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),yn()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(n=navigator.mediaDevices)===null||n===void 0?void 0:n.removeEventListener)===null||s===void 0||s.call(n,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ot.Disconnected),this.emit(ne.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(ne.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,s,r,o){return P(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),o!==1){yield this.engine.publishRpcResponse(e,t,null,It.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(n);if(!a){yield this.engine.publishRpcResponse(e,t,null,It.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield a({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});dl(d)>up?(c=It.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(n))):l=d}catch(d){d instanceof It?c=d:(this.log.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),d),c=It.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,c)})}selectDefaultDevices(){return P(this,void 0,void 0,function*(){var e,t,n;const s=$t.getInstance().previousDevices,r=yield $t.getInstance().getDevices(void 0,!1),o=vn();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of r){const l=s.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(ne.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=ry(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((n=u[0])===null||n===void 0?void 0:n.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Hr()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Hr())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return P(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Nf())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Zt(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(ne.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=so.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new so(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(ne.ParticipantConnected,n),n.on(le.TrackPublished,s=>{this.emitWhenConnected(ne.TrackPublished,s,n)}).on(le.TrackSubscribed,(s,r)=>{s.kind===Z.Kind.Audio?(s.on(ae.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(ae.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===Z.Kind.Video&&(s.on(ae.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(ae.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(ne.TrackSubscribed,s,r,n)}).on(le.TrackUnpublished,s=>{this.emit(ne.TrackUnpublished,s,n)}).on(le.TrackUnsubscribed,(s,r)=>{this.emit(ne.TrackUnsubscribed,s,r,n)}).on(le.TrackMuted,s=>{this.emitWhenConnected(ne.TrackMuted,s,n)}).on(le.TrackUnmuted,s=>{this.emitWhenConnected(ne.TrackUnmuted,s,n)}).on(le.ParticipantMetadataChanged,s=>{this.emitWhenConnected(ne.ParticipantMetadataChanged,s,n)}).on(le.ParticipantNameChanged,s=>{this.emitWhenConnected(ne.ParticipantNameChanged,s,n)}).on(le.AttributesChanged,s=>{this.emitWhenConnected(ne.ParticipantAttributesChanged,s,n)}).on(le.ConnectionQualityChanged,s=>{this.emitWhenConnected(ne.ConnectionQualityChanged,s,n)}).on(le.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(ne.ParticipantPermissionsChanged,s,n)}).on(le.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(ne.TrackSubscriptionStatusChanged,s,r,n)}).on(le.TrackSubscriptionFailed,(s,r)=>{this.emit(ne.TrackSubscriptionFailed,s,n,r)}).on(le.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(ne.TrackSubscriptionPermissionChanged,s,r,n)}).on(le.Active,()=>{this.emitWhenConnected(ne.ParticipantActive,n),n.kind===Or.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,s)=>(n.push(...s.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Ay(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Jt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Bn.STATE_MISMATCH))):e=0},Xb)}clearConnectionReconcile(){this.connectionReconcileInterval&&Jt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(ne.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(this.state===ot.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===ot.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return P(this,void 0,void 0,function*(){var t,n,s,r;const o=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Da({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:wt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new us({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(ne.SignalConnected),this.emit(ne.Connected),this.setAndEmitConnectionState(ot.Connected),o.video){const c=new bl(Z.Kind.Video,new Us({source:Bt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Fn.AUDIO,name:"video-dummy"}),new no(o.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:jf(160*((n=a.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(le.LocalTrackPublished,c)}if(o.audio){const c=new bl(Z.Kind.Audio,new Us({source:Bt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Fn.AUDIO}),new to(o.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Kc(),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(le.LocalTrackPublished,c)}for(let c=0;c<a.count-1;c+=1){let l=new us({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:Os.ACTIVE,tracks:[],joinedAt:wt.parse(Date.now())});const d=this.getOrCreateParticipant(l.identity,l);if(a.video){const u=jf(160*((r=a.aspectRatios[c%a.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new Us({source:Bt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Fn.AUDIO});d.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),l.tracks=[...l.tracks,h]}if(a.audio){const u=Kc(),h=new Us({source:Bt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Fn.AUDIO});d.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),l.tracks=[...l.tracks,h]}d.updateInfo(l)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(e!==ne.ActiveSpeakersChanged&&e!==ne.TranscriptionReceived){const r=Ap(n).filter(o=>o!==void 0);(e===ne.TrackSubscribed||e===ne.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}Ks.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(i=>{i()});function Ap(i){return i.map(e=>{if(e)return Array.isArray(e)?Ap(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Wn;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(Wn||(Wn={}));class Yi extends Zn.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Wn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Ks(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return P(this,void 0,void 0,function*(){if(this.status!==Wn.IDLE)throw Error("check is running already");this.setStatus(Wn.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Wn.SKIPPED&&this.setStatus(this.isSuccess()?Wn.SUCCESS:Wn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return P(this,void 0,void 0,function*(){return this.room.state===ot.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return P(this,void 0,void 0,function*(){this.room&&this.room.state!==ot.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Wn.SKIPPED)}switchProtocol(e){return P(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(ne.Reconnecting,()=>{t=!0}),this.room.once(ne.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(n)return;yield Zt(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Kb extends Yi{get description(){return"Cloud regions"}perform(){return P(this,void 0,void 0,function*(){const e=new et(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let r=0;r<3;r++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(n.has(o))continue;n.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),t.push(a)}t.sort((r,o)=>(r.duration-o.duration)*.5+(r.rtt-o.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return P(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),d=Date.now();for(let g=0;g<c;g++)yield r.write(l);yield r.close();const u=Date.now(),h=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),f={region:s,rtt:1e4,duration:u-d};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const _l=1e4;class Yb extends Yi{get description(){return"Connection via UDP vs TCP"}perform(){return P(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(_l/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(_l/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return P(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,n.fillStyle="hsl(".concat(s,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const a=t.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>P(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(d.packetsSent=f.packetsSent,d.qualityLimitationDurations=f.qualityLimitationDurations,d.bitrateTotal+=f.targetBitrate,d.count++):f.type==="remote-inbound-rtp"&&(d.packetsLost=f.packetsLost,d.rttTotal+=f.roundTripTime,d.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,_l)),clearInterval(u),a.stop(),t.remove(),yield this.disconnect(),d})}}class Jb extends Yi{get description(){return"Can publish audio"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Hb();if(yield Lf(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let o=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class Zb extends Yi{get description(){return"Can publish video"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Gb();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,5e3));const s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(r+=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return P(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise(s=>{n.onplay=()=>{setTimeout(()=>{var r,o,a,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(o=(r=d.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=d.height)!==null&&a!==void 0?a:n.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=h;const f=l.getContext("2d");f.drawImage(n,0,0);const v=f.getImageData(0,0,l.width,l.height).data;let m=!0;for(let p=0;p<v.length;p+=4)if(v[p]!==0||v[p+1]!==0||v[p+2]!==0){m=!1;break}m?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},n.play()}),t.getTracks().forEach(s=>s.stop()),n.remove()})}}class Qb extends Yi{get description(){return"Resuming connection after interruption"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,s=!1,r;const o=new Promise(l=>{setTimeout(l,5e3),r=l}),a=()=>{n=!0};t.on(ne.SignalReconnecting,a).on(ne.Reconnecting,a).on(ne.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield o,n){if(!s||t.state!==ot.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 e_ extends Yi{get description(){return"Can connect via TURN"}perform(){return P(this,void 0,void 0,function*(){var e,t,n;Ws(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new et(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new tl,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,a=!1,c=!1;for(let l of r.iceServers)for(let d of l.urls)d.startsWith("turn:")?(a=!0,c=!0):d.startsWith("turns:")&&(a=!0,c=!0,o=!0),d.startsWith("stun:")&&(c=!0);c?a&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((n=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||n===void 0)&&n.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(l=>setTimeout(l,0)))})}}class t_ extends Yi{get description(){return"Establishing WebRTC connection"}perform(){return P(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(ne.SignalConnected,()=>{var n;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,o)=>{if(r.candidate){const a=new RTCIceCandidate(r);let c="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(n_(a.address)?c+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,c+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,o)},!((n=this.room.engine.pcManager)===null||n===void 0)&&n.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),He.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function n_(i){const e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class i_ extends Yi{get description(){return"Connecting to signal connection via WebSocket"}perform(){return P(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new tl,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(o){if(Ws(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const c=yield new et(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===xh.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class DM extends Zn.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Wn.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Wn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return P(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),s=o=>{this.updateCheck(t,o)};n.on("update",s);const r=yield n.run();return n.off("update",s),r})}checkWebsocket(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(i_)})}checkWebRTC(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(t_)})}checkTURN(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(e_)})}checkReconnect(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Qb)})}checkPublishAudio(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Jb)})}checkPublishVideo(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Zb)})}checkConnectionProtocol(){return P(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Yb);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Kb)})}}function Ze(i,e,t){return(e=r_(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function s_(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function r_(i){var e=s_(i,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class dn extends Error{constructor(e,t){var n;super(e,t),Ze(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(n=Error.captureStackTrace)===null||n===void 0||n.call(Error,this,this.constructor)}}Ze(dn,"code","ERR_JOSE_GENERIC");class a_ extends dn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:s,payload:t}}),Ze(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Ze(this,"claim",void 0),Ze(this,"reason",void 0),Ze(this,"payload",void 0),this.claim=n,this.reason=s,this.payload=t}}Ze(a_,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class o_ extends dn{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:s,payload:t}}),Ze(this,"code","ERR_JWT_EXPIRED"),Ze(this,"claim",void 0),Ze(this,"reason",void 0),Ze(this,"payload",void 0),this.claim=n,this.reason=s,this.payload=t}}Ze(o_,"code","ERR_JWT_EXPIRED");class c_ extends dn{constructor(){super(...arguments),Ze(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Ze(c_,"code","ERR_JOSE_ALG_NOT_ALLOWED");class l_ extends dn{constructor(){super(...arguments),Ze(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Ze(l_,"code","ERR_JOSE_NOT_SUPPORTED");class d_ extends dn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ze(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Ze(d_,"code","ERR_JWE_DECRYPTION_FAILED");class u_ extends dn{constructor(){super(...arguments),Ze(this,"code","ERR_JWE_INVALID")}}Ze(u_,"code","ERR_JWE_INVALID");class h_ extends dn{constructor(){super(...arguments),Ze(this,"code","ERR_JWS_INVALID")}}Ze(h_,"code","ERR_JWS_INVALID");class f_ extends dn{constructor(){super(...arguments),Ze(this,"code","ERR_JWT_INVALID")}}Ze(f_,"code","ERR_JWT_INVALID");class p_ extends dn{constructor(){super(...arguments),Ze(this,"code","ERR_JWK_INVALID")}}Ze(p_,"code","ERR_JWK_INVALID");class m_ extends dn{constructor(){super(...arguments),Ze(this,"code","ERR_JWKS_INVALID")}}Ze(m_,"code","ERR_JWKS_INVALID");class g_ extends dn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ze(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Ze(g_,"code","ERR_JWKS_NO_MATCHING_KEY");class v_ extends dn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ze(this,Symbol.asyncIterator,void 0),Ze(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Ze(v_,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class y_ extends dn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ze(this,"code","ERR_JWKS_TIMEOUT")}}Ze(y_,"code","ERR_JWKS_TIMEOUT");class b_ extends dn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ze(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Ze(b_,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");class ro extends EventTarget{constructor(){super(...arguments),this.room=null,this.callStatus="idle",this.isReady=!1,this.error=null,this.microphoneEnabled=!1,this.connectedParticipants=[],this.userIdentity="",this.roomName="",this.audioPlaybackPrompt=!1}set serviceUrl(e){this._serviceUrl=e}get serviceUrl(){return this._serviceUrl??void 0}get status(){return this.callStatus}get ready(){return this.isReady}get currentError(){return this.error}get currentRoom(){return this.room}get isMicrophoneEnabled(){return this.microphoneEnabled}get participants(){return this.connectedParticipants}get identity(){return this.userIdentity}get roomNameValue(){return this.roomName}get showAudioPrompt(){return this.audioPlaybackPrompt}updateStatus(e){this.callStatus=e,this.dispatchEvent(new CustomEvent("status-changed",{detail:e}))}async makeCall({agentId:e}){if(this.room&&this.room.state==="connected")return;let t=null;try{t=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),console.log("Microphone permission granted")}catch(n){console.warn("Microphone permission denied or not available:",n)}this.updateStatus("connecting"),this.error=null,this.isReady=!1,this.room&&(await this.room.disconnect(),this.room=null);try{const n=new Ks;this.room=n,this.setupRoomEventListeners(n);const s=await fetch(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{agent_id:e,timestamp:Date.now()}})});if(!s.ok){const l=await s.text();throw new Error(`Failed to get room token: ${s.status} ${l}`)}const{token:r,url:o,room_name:a,user_identity:c}=await s.json();this.roomName=a,this.userIdentity=c,await n.connect(o,r),this.updateStatus("connected"),this.isReady=!0,requestAnimationFrame(()=>{setTimeout(async()=>{if(t)try{await n.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")),t.getTracks().forEach(l=>l.stop()),setTimeout(()=>{const l=Array.from(n.localParticipant.audioTrackPublications.values()).find(d=>d.kind==="audio");if(l!=null&&l.track){const d=l.track.mediaStreamTrack;d&&this.dispatchEvent(new CustomEvent("local-audio-track",{detail:d}))}},100)}catch(l){console.warn("Could not enable microphone on connect:",l),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))}else this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))},50)}),this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:a,identity:c}}))}catch(n){t&&t.getTracks().forEach(s=>s.stop()),this.error=`Connection failed: ${n instanceof Error?n.message:String(n)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}setupRoomEventListeners(e){e.on(ne.Connected,()=>{this.updateStatus("connected"),this.isReady=!0}),e.on(ne.Disconnected,()=>{this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.room=null,this.isReady=!1,this.dispatchEvent(new CustomEvent("disconnected"))}),e.on(ne.ParticipantConnected,t=>{this.connectedParticipants=[...this.connectedParticipants,t.identity];const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");n&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("agent-connected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-connected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(ne.ParticipantDisconnected,t=>{this.connectedParticipants=this.connectedParticipants.filter(s=>s!==t.identity);const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");n&&(this.audioPlaybackPrompt=!1,this.updateStatus("connected"),this.dispatchEvent(new CustomEvent("agent-disconnected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-disconnected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(ne.TrackSubscribed,(t,n,s)=>{if(t.kind==="audio"){const r=t.attach();document.body.appendChild(r),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:s.identity,element:r}}));const o=t.mediaStreamTrack;o&&this.dispatchEvent(new CustomEvent("audio-track",{detail:o}))}}),e.on(ne.TrackUnsubscribed,(t,n,s)=>{t.detach(),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:s.identity}}))}),e.on(ne.MediaDevicesError,t=>{this.error=`Media device error: ${t.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),e.on(ne.AudioPlaybackStatusChanged,async()=>{e.canPlaybackAudio||this.connectedParticipants.some(n=>n.includes("agent")||n.includes("voice-assistant")||n.includes("AJ_"))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:e.canPlaybackAudio}}))})}async toggleMicrophone(){if(this.room)try{this.microphoneEnabled?(await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))):(await this.room.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")))}catch(e){this.error=`Failed to toggle microphone: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async enableAudio(){if(this.room)try{await this.room.startAudio(),this.audioPlaybackPrompt=!1;const e=JSON.stringify({type:"audio_enabled"}),n=new TextEncoder().encode(e);await this.room.localParticipant.publishData(n,{reliable:!0}),this.dispatchEvent(new CustomEvent("audio-enabled"))}catch(e){this.error=`Failed to enable audio: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async hangUp(){if(!this.room){this.error="No active connection to end.";return}this.updateStatus("disconnecting");const e=this.room;this.room=null,this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.updateStatus("disconnected"),this.dispatchEvent(new CustomEvent("call-ended")),requestAnimationFrame(()=>{setTimeout(async()=>{try{await e.disconnect()}catch(t){console.warn("Error during room disconnect:",t)}},0)})}}/**
84
+ `},rl}var sp;function eb(){if(sp)return Hn;sp=1;var i=Zy(),e=Qy(),t=sl();return Hn.grammar=t,Hn.write=e,Hn.parse=i.parse,Hn.parseParams=i.parseParams,Hn.parseFmtpConfig=i.parseFmtpConfig,Hn.parsePayloads=i.parsePayloads,Hn.parseRemoteCandidates=i.parseRemoteCandidates,Hn.parseImageAttributes=i.parseImageAttributes,Hn.parseSimulcastStreamList=i.parseSimulcastStreamList,Hn}var Xi=eb();function al(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var o=(n=t.isImmediate)!=null&&n,a=(s=t.callback)!=null&&s,c=t.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(v,m){var p=o&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,l=Date.now(),!o){var E=i.apply(g,f);a&&a(E),d.forEach(function(y){return(0,y.resolve)(E)}),d=[]}},u()),p){var T=i.apply(g,f);return a&&a(T),v(T)}d.push({resolve:v,reject:m})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),d.forEach(function(g){return(0,g.reject)(f)}),d=[]},h}const tb=.7,nb=20,Xs={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class rp extends Zn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;super(),this.log=He,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=al(s=>P(this,void 0,void 0,function*(){this.emit(Xs.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),nb),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=mi((n=t.loggerName)!==null&&n!==void 0?n:Vn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new cn}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return P(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return P(this,void 0,void 0,function*(){var n;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:o}=ib(e);this.remoteStereoMids=r,this.remoteNackMids=o}else if(e.type==="answer"){const r=Xi.parse((n=e.sdp)!==null&&n!==void 0?n:"");r.media.forEach(o=>{const a=ol(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||a!=c.transceiver.mid)return!1;let l=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0)return!0;let d=!1;for(const u of o.fmtp)if(u.payload===l){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),d=!0;break}return d||c.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=Xi.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Xs.NegotiationComplete),e.sdp&&Xi.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Xs.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const a=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&a)yield this._pc.setRemoteDescription(a);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const o=Xi.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(o.media.forEach(a=>{op(a),a.type==="audio"?ap(a,["all"],[]):a.type==="video"&&this.trackBitrates.some(c=>{if(!a.msid||!c.cid||!a.msid.includes(c.cid))return!1;let l=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0||(Gn(c.codec)&&!ps()&&this.ensureVideoDDExtensionForSVC(a,o),!Gn(c.codec)))return!0;const d=Math.round(c.maxbr*tb);for(const u of a.fmtp)if(u.payload===l){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(d));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,Xi.write(o)),this.onOffer(r,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=Xi.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{op(s),s.type==="audio"&&ap(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Xi.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Ut("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Ut("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return P(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,s=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),n.set(a.id,a);break;case"remote-candidate":s.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const o=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return s.get(o)})}setMungedSDP(e,t,n){return P(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const o={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new zs(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,s;if(!((n=e.ext)===null||n===void 0?void 0:n.some(o=>o.uri===Ff))){if(this.ddExtID===0){let o=0;t.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Ff})}}}function ap(i,e,t){const n=ol(i.mid);let s=0;i.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(n)&&!i.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&i.rtcpFb.push({payload:s,type:"nack"}),(e.includes(n)||e.length===1&&e[0]==="all")&&i.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function ib(i){var e;const t=[],n=[],s=Xi.parse((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(o=>{var a;const c=ol(o.mid);o.type==="audio"&&(o.rtp.some(l=>l.codec==="opus"?(r=l.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(l=>l.payload===r&&l.type==="nack")&&n.push(c),o.fmtp.some(l=>l.payload===r?(l.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:n}}function op(i){if(i.connection){const e=i.connection.ip.indexOf(":")>=0;(i.connection.version===4&&e||i.connection.version===6&&!e)&&(i.connection.ip="0.0.0.0",i.connection.version=4)}}function ol(i){return typeof i=="number"?i.toFixed(0):i}const cl="vp8",sb={audioPreset:Uc.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Bc.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:cl,backupCodec:!0,preConnectBuffer:!1},cp={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},lp={deviceId:{ideal:"default"},resolution:zr.h720.resolution},rb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new U0,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},ll={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var kt;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(kt||(kt={}));class ab{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){var s;this.peerConnectionTimeout=ll.peerConnectionTimeout,this.log=He,this.updateState=()=>{var r,o;const a=this.state,c=this.requiredTransports.map(l=>l.getConnectionState());c.every(l=>l==="connected")?this.state=kt.CONNECTED:c.some(l=>l==="failed")?this.state=kt.FAILED:c.some(l=>l==="connecting")?this.state=kt.CONNECTING:c.every(l=>l==="closed")?this.state=kt.CLOSED:c.some(l=>l==="closed")?this.state=kt.CLOSING:c.every(l=>l==="new")&&(this.state=kt.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(kt[a]," to ").concat(kt[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=mi((s=n.loggerName)!==null&&s!==void 0?s:Vn.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new rp(e,n),this._mode=t,t!=="publisher-only"&&(this.subscriber=new rp(e,n),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,zn.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,r)},this.subscriber.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,zn.PUBLISHER)},this.publisher.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)},this.publisher.onOffer=(r,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r,o)},this.state=kt.NEW,this.connectionLock=new cn,this.remoteOfferLock=new cn}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return P(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return P(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return P(this,void 0,void 0,function*(){var n;t===zn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(n=this.subscriber)===null||n===void 0?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return P(this,void 0,void 0,function*(){var n,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(n=this.subscriber)===null||n===void 0?void 0:n.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),(n=this.subscriber)===null||n===void 0||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return P(this,void 0,void 0,function*(){var n;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return P(this,void 0,void 0,function*(){return new vn((t,n)=>P(this,void 0,void 0,function*(){const s=setTimeout(()=>{n(new zs("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),n(new zs("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(Xs.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Xs.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(o=>{clearTimeout(s),o instanceof Error?n(o):n(new Error(String(o)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const n=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return n==null?void 0:n.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===zn.PUBLISHER?this.publisher.getConnectedAddress():e===zn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(n.getConnectionState()!=="connected")return new Promise((c,l)=>P(r,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),Zt.clearTimeout(u),l(Ne.cancelled("room connection has been cancelled"))};s!=null&&s.signal.aborted&&d(),s==null||s.signal.addEventListener("abort",d);const u=Zt.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",d),l(Ne.internal("could not establish pc connection"))},o);for(;this.state!==kt.CONNECTED;)if(yield Qt(50),s!=null&&s.signal.aborted){l(Ne.cancelled("room connection has been cancelled"));return}Zt.clearTimeout(u),s==null||s.signal.removeEventListener("abort",d),c()}))})()})}}const dp=5e3,ob=3e4;class et{static fetchRegionSettings(e,t,n){return P(this,void 0,void 0,function*(){const s=yield et.fetchLock.lock();try{const r=yield fetch("".concat(cb(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(r.ok){const o=ky(r.headers),a=o?o*1e3:dp;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:a}}else throw r.status===401?Ne.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):Ne.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof Ne?r:n!=null&&n.aborted?Ne.cancelled("Region fetching was aborted"):Ne.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,n){return P(this,void 0,void 0,function*(){const s=et.settingsTimeouts.get(e.hostname);clearTimeout(s),et.settingsTimeouts.set(e.hostname,setTimeout(()=>P(this,void 0,void 0,function*(){try{const r=yield et.fetchRegionSettings(e,t);et.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof Ne&&r.reason===gt.NotAllowed){He.debug("token is not valid, cancelling auto region refresh");return}He.debug("auto refetching of region settings failed",{error:r}),et.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){et.cache.set(e.hostname,n),et.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=et.settingsTimeouts.get(e);t&&(clearTimeout(t),et.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=et.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const n=et.connectionTrackers.get(e);n&&n.connectionCount===0&&(He.debug("stopping region refetch after disconnect delay",{hostname:e}),et.stopRefetch(e)),n&&(n.cleanupTimeout=void 0)},ob))}static cancelCleanup(e){const t=et.connectionTrackers.get(e);t!=null&&t.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=et.connectionTrackers.get(e);t||(t={connectionCount:0},et.connectionTrackers.set(e,t)),t.connectionCount++,et.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=et.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&et.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Ws(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return P(this,void 0,void 0,function*(){return et.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return P(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=et.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),et.updateCachedRegionSettings(this.serverUrl,this.token,t));const n=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(n.length>0){const s=n[0];return this.attemptedRegions.push(s),He.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){et.updateCachedRegionSettings(this.serverUrl,this.token,e)}}et.cache=new Map,et.settingsTimeouts=new Map,et.connectionTrackers=new Map,et.fetchLock=new cn;function cb(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}class It extends Error{constructor(e,t,n){super(t),this.code=e,this.message=hp(t,It.MAX_MESSAGE_BYTES),this.data=n?hp(n,It.MAX_DATA_BYTES):void 0}static fromProto(e){return new It(e.code,e.message,e.data)}toProto(){return new bh({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new It(It.ErrorCode[e],It.ErrorMessage[e],t)}}It.MAX_MESSAGE_BYTES=256,It.MAX_DATA_BYTES=15360,It.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},It.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 up=15360;function dl(i){return new TextEncoder().encode(i).length}function hp(i,e){if(dl(i)<=e)return i;let t=0,n=i.length;const s=new TextEncoder;for(;t<n;){const r=Math.floor((t+n+1)/2);s.encode(i.slice(0,r)).length<=e?t=r:n=r-1}return i.slice(0,t)}const ul=2e3;function eo(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}const hl=typeof MediaRecorder<"u";class lb{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const db=hl?MediaRecorder:lb;class ub extends db{constructor(e,t){if(!hl)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let n,s;const r=()=>s===void 0,o=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",a),s==null||s.close(),s=void 0},a=c=>{s==null||s.error(c),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",a),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,n=l=>P(this,void 0,void 0,function*(){let d;if(l.data.arrayBuffer){const u=yield l.data.arrayBuffer();d=new Uint8Array(u)}else if(l.data.byteArray)d=l.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(d)}),this.addEventListener("dataavailable",n)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function hb(){return hl}const fb=1e3,pb=1e4;class fp extends Z{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=al(()=>P(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>P(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(ae.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new cn,this.pauseUpstreamLock=new cn,this.trackChangeLock=new cn,this.trackChangeLock.lock().then(o=>P(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Z.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return P(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Hs(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Gs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Gs(s??e,r)}))})}waitForDimensions(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:fb;return(function*(){var n;if(e.kind===Z.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=yn())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Qt(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield Qt(50)}throw new vi("unable to get track dimensions after timeout")})()})}setDeviceId(e){return P(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Hi(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Hi(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===Z.Source.ScreenShare)return;const{deviceId:n,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===Z.Kind.Audio?"audioinput":"videoinput";return t?Xt.getInstance().normalizeDeviceId(r,n,s):n})()})}mute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return P(this,void 0,void 0,function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new vi("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e){return P(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:s}=e,r=F0(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===Z.Kind.Video?o.video=n||s?{deviceId:n,facingMode:s}:!0:o.audio=n?Object.assign({deviceId:n},r):!0,this.attachedElements.forEach(l=>{Hs(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===Z.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(ae.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ae.Muted:ae.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),zf()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(ae.UpstreamPaused,this);const n=yn();if((n==null?void 0:n.name)==="Safari"&&ti(n.version,"12.0")<0)throw new Oc("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(ae.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const o=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const a=document.createElement(n.kind),c={kind:n.kind,track:n._mediaStreamTrack,element:a,audioContext:n.audioContext};if(yield t.init(c),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Gs(n._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:l})),setTimeout(()=>{a.play().catch(d=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:d}))})},100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:l}))}),n.processor=t,n.processorElement=a,n.processor.processedTrack){for(const l of n.attachedElements)l!==n.processorElement&&s&&(Hs(n._mediaStreamTrack,l),Gs(n.processor.processedTrack,l));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(ae.TrackProcessorUpdate,n.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}})()})}internalStopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var n,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(ae.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!hb()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new ub(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},pb)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class to extends fp{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,Z.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=eo(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ae.AudioTrackFeatureUpdate,this,$t.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ae.AudioTrackFeatureUpdate,this,$t.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===Z.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Hi(this._constraints.deviceId);return this.source===Z.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return P(this,void 0,void 0,function*(){let t;if(e){const n=Vc({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return P(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){bn()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ul)))}setProcessor(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!ei()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(ae.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return P(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(s=>{s.type==="outbound-rtp"&&(n={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),n})}checkForSilence(){return P(this,void 0,void 0,function*(){const e=yield Lf(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(ae.AudioSilenceDetected)),e})}}function mb(i,e,t){switch(i.kind){case"audio":return new to(i,e,!1,void 0,t);case"video":return new no(i,e,!1,t);default:throw new vi("unsupported track type: ".concat(i.kind))}}const gb=Object.values(zr),vb=Object.values(Fc),yb=Object.values(Bc),bb=[zr.h180,zr.h360],_b=[Fc.h180,Fc.h360],Sb=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new ft(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,i.encoding.priority)}),fl=["q","h","f"];function pl(i,e,t,n){var s,r;let o=n==null?void 0:n.videoEncoding;i&&(o=n==null?void 0:n.screenShareEncoding);const a=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,l=n==null?void 0:n.videoCodec;if(!o&&!a&&!c||!e||!t)return[{}];o||(o=Tb(i,e,t,l),He.debug("using video encoding",o));const d=o.maxFramerate,u=new ft(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Gn(l)){const g=new gp(c),v=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const m=yn();if(Hr()||ei()||(m==null?void 0:m.name)==="Chrome"&&ti(m==null?void 0:m.version,"113")<0){const p=g.suffix=="h"?2:3,T=by(m);for(let E=0;E<g.spatial;E+=1)v.push({rid:fl[2-E],maxBitrate:o.maxBitrate/Math.pow(p,E),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:T?Math.pow(2,E):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),He.debug("using svc encoding",{encodings:v}),v}if(!a)return[o];let h=[];i?h=(s=mp(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:pp(i,u):h=(r=mp(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:pp(i,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return ml(e,t,[g,f,u],d);if(v>=480)return ml(e,t,[g,u],d)}return ml(e,t,[u])}function xb(i,e,t){var n,s,r,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&He.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const a=i.mediaStreamTrack.getSettings(),c=(n=a.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,l=(r=a.height)!==null&&r!==void 0?r:(o=i.dimensions)===null||o===void 0?void 0:o.height;return i.source===Z.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),pl(i.source===Z.Source.ScreenShare,c,l,t)}function Tb(i,e,t,n){const s=Cb(i,e,t);let{encoding:r}=s[0];const o=Math.max(e,t);for(let a=0;a<s.length;a+=1){const c=s[a];if(r=c.encoding,c.width>=o)break}if(n)switch(n){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Cb(i,e,t){if(i)return yb;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?gb:vb}function pp(i,e){if(i)return Sb(e);const{width:t,height:n}=e,s=t>n?t/n:n/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?bb:_b}function ml(i,e,t,n){const s=[];if(t.forEach((r,o)=>{if(o>=fl.length)return;const a=Math.min(i,e),l={rid:fl[o],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},d=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=fs()||o===0;r.encoding.priority&&u&&(l.priority=r.encoding.priority,l.networkPriority=r.encoding.priority),s.push(l)}),ei()&&Gf()==="ios"){let r;s.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let o=!0;s.forEach(a=>{var c;a.maxFramerate!=r&&(o&&(o=!1,He.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),He.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),a.maxFramerate=r)})}return s}function mp(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:s}=t;return n.maxBitrate>s.maxBitrate?1:n.maxBitrate<s.maxBitrate?-1:n.maxBitrate===s.maxBitrate&&n.maxFramerate&&s.maxFramerate?n.maxFramerate>s.maxFramerate?1:-1:0})}class gp{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Eb(i){return i.source===Z.Source.ScreenShare||i.constraints.height&&Hi(i.constraints.height)>=1080?"maintain-resolution":"balanced"}const Mb=5e3;class no extends fp{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,Z.Kind.Video,t,n,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const o=new Map(r.map(c=>[c.rid,c])),a=r.some(c=>c.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(ae.CpuConstrained)),this.prevStats){let c=0;o.forEach((l,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);c+=eo(l,h)}),this._currentBitrate=c}this.prevStats=o}),this.senderLock=new cn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!bn())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ul))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=gi(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;a=!0)r=l.value,a=!1,yield(o=r.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(d){n={error:d}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=gi(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;a=!0){r=l.value,a=!1;const d=r;yield(o=d.sender)===null||o===void 0?void 0:o.replaceTrack(d.mediaStreamTrack)}}catch(d){n={error:d}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===Z.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===Z.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return P(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(s=>{var r;if(s.type==="outbound-rtp"){const o={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},a=n.get(s.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t.sort((s,r)=>{var o,a;return((o=r.frameWidth)!==null&&o!==void 0?o:0)-((a=s.frameWidth)!==null&&a!==void 0?a:0)}),t})}setPublishingQuality(e){const t=[];for(let n=Mn.LOW;n<=Mn.HIGH;n+=1)t.push(new xc({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Gn(this.codec),t)}restartTrack(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o;let a;if(e){const u=Vc({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var c=!0,l=gi(this.simulcastCodecs.values()),d;d=yield l.next(),t=d.done,!t;c=!0){r=d.value,c=!1;const u=r;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){n={error:u}}finally{try{!c&&!t&&(s=l.return)&&(yield s.call(l))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return P(this,arguments,void 0,function(n){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,c,l,d,u;if(yield t.setProcessor.call(s,n,r),!((d=s.processor)===null||d===void 0)&&d.processedTrack)try{for(var h=!0,f=gi(s.simulcastCodecs.values()),g;g=yield f.next(),o=g.done,!o;h=!0)l=g.value,h=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){a={error:v}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return P(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Mb))}setPublishingCodecs(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o,a,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Gn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,n=gi(e);s=yield n.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Gn(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of d.qualities)if(h.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield vp(u.sender,u.encodings,d.qualities,this.senderLock,Gn(d.codec),this.log,this.logContext))}}}catch(d){o={error:d}}finally{try{!t&&!r&&(a=n.return)&&(yield a.call(n))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,t){return P(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield vp(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return P(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((n,s)=>{var r;return Object.assign(Object.assign({},n),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Gn(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?n.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),zf()&&this.isInBackground&&this.source===Z.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function vp(i,e,t,n,s,r,o){return P(this,void 0,void 0,function*(){const a=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:i,qualities:t,senderEncodings:e}));try{const c=i.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var g;let v=(g=h.rid)!==null&&g!==void 0?g:"";v===""&&(v="q");const m=yp(v),p=t.find(T=>T.quality===m);p&&h.active!==p.enabled&&(d=!0,h.active=p.enabled,r.debug("setting layer ".concat(p.quality," to ").concat(h.active?"enabled":"disabled"),o),fs()&&(p.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),d&&(c.encodings=l,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield i.setParameters(c))}finally{a()}})}function yp(i){switch(i){case"f":return Mn.HIGH;case"h":return Mn.MEDIUM;case"q":return Mn.LOW;default:return Mn.HIGH}}function bp(i,e,t,n){if(!t)return[new Vi({quality:Mn.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new gp(s),o=[],a=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let l=0;l<r.spatial;l+=1)o.push(new Vi({quality:Math.min(Mn.HIGH,r.spatial-1)-l,width:Math.ceil(i/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return t.map(s=>{var r,o,a;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let l=yp((o=s.rid)!==null&&o!==void 0?o:"");return new Vi({quality:l,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(a=s.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const _p="_lossy",Sp="_reliable",wb=2*1e3,gl="leave-reconnect",Ab=3e4,Rb=8*1024,Pb=256*1024;var Ln;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Ln||(Ln={}));class kb extends Zn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ll.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ln.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=He,this.reliableDataSequence=1,this.reliableMessageBuffer=new ep,this.reliableReceivedState=new Jy(Ab),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=n=>P(this,[n],void 0,function(s){var r=this;let{channel:o}=s;return(function*(){if(o){if(o.label===Sp)r.reliableDCSub=o;else if(o.label===_p)r.lossyDCSub=o;else return;r.log.debug("on data channel ".concat(o.id,", ").concat(o.label),r.logContext),o.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=n=>P(this,void 0,void 0,function*(){var s,r,o,a,c;const l=yield this.dataProcessLock.lock();try{let d;if(n.data instanceof ArrayBuffer)d=n.data;else if(n.data instanceof Blob)d=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const u=ln.fromBinary(new Uint8Array(d));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(le.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=gh.fromBinary(h.payload),g=new ln({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((a=g.value)===null||a===void 0?void 0:a.case)==="user"&&xp(g,g.value.value),this.emit(le.DataPacketReceived,g,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&xp(u,u.value.value),this.emit(le.DataPacketReceived,u,Ht.NONE)}finally{l()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:o}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?Ke.LOSSY:Ke.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,s)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(le.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){r(o);return}n===gl&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Zt.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===Ln.Connected&&n();const r=()=>{this.off(le.Disconnected,o),n()},o=()=>{this.off(le.Restarted,r),s()};this.once(le.Restarted,r),this.once(le.Disconnected,o)}),this.updateAndEmitDCBufferStatus=n=>{if(n===Ke.RELIABLE){const r=this.dataChannelForKind(n);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(n);typeof s<"u"&&s!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,s),this.emit(le.DCBufferStatusChanged,s,n))},this.isBufferStatusLow=n=>{const s=this.dataChannelForKind(n);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>P(this,void 0,void 0,function*(){!this.url||!(yield fetch(qr(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===vt.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===vt.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(ds.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>P(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(qr(this.url),{method:"HEAD"}),Qt(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=mi((t=e.loggerName)!==null&&t!==void 0?t:Vn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new tl(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new cn,this.dataProcessLock=new cn,this.dcBufferStatus=new Map([[Ke.LOSSY,!0],[Ke.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(le.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(le.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(le.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(le.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(le.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(le.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(le.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(le.SignalRequestResponse,n)}get logContext(){var e,t,n,s,r,o;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||s===void 0?void 0:s.sid,participant:(o=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,t,n,s){return P(this,arguments,void 0,function(r,o,a,c){var l=this;let d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){l.url=r,l.token=o,l.signalOpts=a,l.maxJoinAttempts=a.maxRetries;try{l.joinAttempts+=1,l.setupSignalClientCallbacks();const u=yield l.client.join(r,o,a,c,d);return l._isClosed=!1,l.latestJoinResponse=u,l.subscriberPrimary=u.subscriberPrimary,l.pcManager||(yield l.configure(u,!d)),(!l.subscriberPrimary||u.fastPublish)&&l.negotiate().catch(h=>{He.error(h,l.logContext)}),l.registerOnLineListener(),l.clientConfiguration=u.clientConfiguration,l.emit(le.SignalConnected,u),u}catch(u){if(u instanceof Ne){if(u.reason===gt.ServerUnreachable){if(l.log.warn("Couldn't connect to server, attempt ".concat(l.joinAttempts," of ").concat(l.maxJoinAttempts),l.logContext),l.joinAttempts<l.maxJoinAttempts)return l.join(r,o,a,c,d)}else if(u.reason===gt.ServiceNotFound)return l.log.warn("Initial connection failed: ".concat(u.message," – Retrying")),l.join(r,o,a,c,!0)}throw u}})()})}close(){return P(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(le.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return P(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new ep,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return P(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new vi("a track with the same ID has already been published");return new Promise((t,n)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(Ne.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return P(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return P(this,void 0,void 0,function*(){var n,s;if(this.pcManager&&this.pcManager.currentState!==kt.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new ab(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(le.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(o,a)=>{this.client.sendIceCandidate(o,a)},this.pcManager.onPublisherOffer=(o,a)=>{this.client.sendOffer(o,a)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(o,a,c)=>P(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(o),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),o===kt.CONNECTED){const u=this.pcState===Ln.New;this.pcState=Ln.Connected,u&&this.emit(le.Connected,e)}else o===kt.FAILED&&(this.pcState===Ln.Connected||this.pcState===Ln.Reconnecting)&&(this.pcState=Ln.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?ds.RR_SUBSCRIBER_FAILED:ds.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===vt.RECONNECTING,d=[kt.FAILED,kt.CLOSING,kt.CLOSED].includes(o);l&&d&&!this._isClosed&&this.emit(le.Offline)}),this.pcManager.onTrack=o=>{o.streams.length!==0&&this.emit(le.MediaTrackAdded,o.track,o.streams[0],o.receiver)},Ib((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>P(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>P(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(le.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(le.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(le.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(le.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(le.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,n;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",ds.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:dp,regionSettings:e.regions})),e.action){case Fs.DISCONNECT:this.emit(le.Disconnected,e==null?void 0:e.reason),this.close();break;case Fs.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(gl);break;case Fs.RESUME:this.handleDisconnect(gl)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const s=[];e.iceServers.forEach(r=>{const o={urls:r.urls};r.username&&(o.username=r.username),r.credential&&(o.credential=r.credential),s.push(o)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Nr.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(_p,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Sp,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Ke.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,Rb),Pb)}},1e3))}createSender(e,t,n){return P(this,void 0,void 0,function*(){if(Hc())return yield this.createTransceiverRTCRtpSender(e,t,n);if(Wc())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Ut("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(Hc())return this.createSimulcastTransceiverSender(e,t,n,s);if(Wc())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Ut("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ut("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Wi(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ut("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ut("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return P(this,void 0,void 0,function*(){var t,n,s;if(!this._isClosed){if(this.attemptingReconnect){He.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Nr.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:kt.NEW)===kt.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let o=!0;r instanceof Ut?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),o=!1):r instanceof Vs||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",ds.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(le.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return P(this,void 0,void 0,function*(){var t,n,s;try{if(!this.url||!this.token)throw new Ut("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(le.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Vs;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(o){throw o instanceof Ne&&o.reason===gt.NotAllowed?new Ut("could not reconnect, token might be expired"):new Vs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(le.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==vt.CONNECTED)throw new Vs("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(le.Restarted)}catch(r){const o=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return P(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Ut("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ut("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(le.Resuming);let n;try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof Ne&&s.reason===gt.NotAllowed?new Ut("could not reconnect, token might be expired"):s instanceof Ne&&s.reason===gt.LeaveRequest?s:new Vs(r)}if(this.emit(le.SignalResumed),n){const s=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==vt.CONNECTED)throw new Vs("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),n!=null&&n.lastMessageSeq&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(le.Resumed)})}waitForPCInitialConnection(e,t){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ut("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return P(this,void 0,void 0,function*(){this.pcState=Ln.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Qt(wb),!this.pcManager)throw new Ut("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ln.Connected}catch(e){throw this.pcState=Ln.Disconnected,Ne.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,n,s){return P(this,void 0,void 0,function*(){const r=new ln({destinationIdentities:[e],kind:Ke.RELIABLE,value:{case:"rpcResponse",value:new mc({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,Ke.RELIABLE)})}publishRpcAck(e,t){return P(this,void 0,void 0,function*(){const n=new ln({destinationIdentities:[e],kind:Ke.RELIABLE,value:{case:"rpcAck",value:new pc({requestId:t})}});yield this.sendDataPacket(n,Ke.RELIABLE)})}sendDataPacket(e,t){return P(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=zy(e);if(r){const o=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new mh({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}t===Ke.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===Ke.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=n.byteLength}if(this.attemptingReconnect)return;s.send(n)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return P(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Ke.RELIABLE);const t=this.dataChannelForKind(Ke.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(n=>{t.send(n.data)})),this.updateAndEmitDCBufferStatus(Ke.RELIABLE)})}waitForBufferStatusLow(e){return new vn((t,n)=>P(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>n(new Ut("engine closed"));for(this.once(le.Closing,s);!this.dcBufferStatus.get(e);)yield Qt(10);this.off(le.Closing,s),t()}}))}ensureDataTransportConnected(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!n.pcManager)throw new Ut("PC manager is closed");const o=s?n.pcManager.subscriber:n.pcManager.publisher,a=s?"Subscriber":"Publisher";if(!o)throw Ne.internal("".concat(a," connection not set"));let c=!1;!s&&!n.dataChannelForKind(t,s)&&(n.createDataChannels(),c=!0),!c&&!s&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&n.negotiate().catch(u=>{He.error(u,n.logContext)});const l=n.dataChannelForKind(t,s);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<d;){if(o.isICEConnected&&((r=n.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield Qt(50)}throw Ne.internal("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()))})()})}ensurePublisherConnected(e){return P(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==kt.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return P(this,void 0,void 0,function*(){return new vn((e,t)=>P(this,void 0,void 0,function*(){if(!this.pcManager){t(new zs("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new zs("cannot negotiate on closed engine")),this.on(le.Closing,s),this.pcManager.publisher.once(Xs.RTPVideoPayloadTypes,r=>{const o=new Map;r.forEach(a=>{const c=a.codec.toLowerCase();Cy(c)&&o.set(a.payload,c)}),this.emit(le.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof zs&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ds.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(le.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===Ke.LOSSY)return this.lossyDCSub;if(e===Ke.RELIABLE)return this.reliableDCSub}else{if(e===Ke.LOSSY)return this.lossyDC;if(e===Ke.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,s,r,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const a=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=(n=this.pcManager.subscriber)===null||n===void 0?void 0:n.getRemoteDescription(),d=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(o=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,f=new Array;e.forEach(g=>{g.isDesired!==u&&h.push(g.trackSid),g.isEnabled||f.push(g.trackSid)}),this.client.sendSyncState(new Tc({answer:this.pcManager.mode==="publisher-only"?c?$s({sdp:c.sdp,type:c.type}):void 0:d?$s({sdp:d.sdp,type:d.type}):void 0,offer:this.pcManager.mode==="publisher-only"?a?$s({sdp:a.sdp,type:a.type}):void 0:l?$s({sdp:l.sdp,type:l.type}):void 0,subscription:new Va({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:oy(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((g,v)=>new Uh({publisherSid:v,lastSeq:g}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Fh({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(Ke.LOSSY),zn.PUBLISHER),t(this.dataChannelForKind(Ke.RELIABLE),zn.PUBLISHER),t(this.dataChannelForKind(Ke.LOSSY,!0),zn.SUBSCRIBER),t(this.dataChannelForKind(Ke.RELIABLE,!0),zn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Zt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){bn()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){bn()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(n){const s=Object.entries(this.midToTrackId).find(r=>{let[o]=r;return o===n});if(s)return s[1]}}}function Ib(i){return i!==void 0&&i>13}function xp(i,e){const t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;const n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}class Tp{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new In("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),dn.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new In("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),dn.LengthExceeded)}}constructor(e,t,n,s){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class Db extends Tp{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Dn,n=null,s=null;if(this.signal){const o=this.signal;s=()=>{var a;(a=t.reject)===null||a===void 0||a.call(t,o.reason)},o.addEventListener("abort",s),n=o}const r=()=>{e.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var o,a;try{const{done:c,value:l}=yield Promise.race([e.read(),t.promise,(a=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&a!==void 0?a:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw r(),c}}),return(){return P(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,s,r,o;let a=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=gi(c),u;u=yield d.next(),n=u.done,!n;l=!0){o=u.value,l=!1;const h=o;a.add(h)}}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return Array.from(a)})()})}}class Lb extends Tp{constructor(e,t,n,s){super(e,t,n,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Qa(e.chunkIndex),s=this.receivedChunks.get(n);if(s&&s.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let n=new Dn,s=null,r=null;if(this.signal){const a=this.signal;r=()=>{var c;(c=n.reject)===null||c===void 0||c.call(n,a.reason)},a.addEventListener("abort",r),s=a}const o=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var a,c;try{const{done:l,value:d}=yield Promise.race([e.read(),n.promise,(c=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(d);let u;try{u=t.decode(d.content)}catch(h){throw new In("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),dn.DecodeFailed)}return{done:!1,value:u}}}catch(l){throw o(),l}}),return(){return P(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,s,r,o;let a="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=gi(c),u;u=yield d.next(),n=u.done,!n;l=!0)o=u.value,l=!1,a+=o}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return a})()})}}class Nb{constructor(){this.log=He,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new In('A text stream handler for topic "'.concat(e,'" has already been set.'),dn.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new In('A byte stream handler for topic "'.concat(e,'" has already been set.'),dn.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,n,s,r;const o=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),a=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(o.length>0||a.length>0){const c=new In("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),dn.AbnormalEnd);for(const[l,d]of a)(n=(t=d.outOfBandFailureRejectingFuture).reject)===null||n===void 0||n.call(t,c),this.byteStreamControllers.delete(l);for(const[l,d]of o)(r=(s=d.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e,t){return P(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,n){return P(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let o;const a=new Dn;a.promise.catch(d=>{this.log.error(d)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Qa(e.timestamp),attributes:e.attributes,encryptionType:n},l=new ReadableStream({start:d=>{if(o=d,this.textStreamControllers.has(e.streamId))throw new In("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),dn.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new Db(c,l,Qa(e.totalLength),a),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o;const a=new Dn;a.promise.catch(d=>{this.log.error(d)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n},l=new ReadableStream({start:d=>{if(o=d,this.textStreamControllers.has(e.streamId))throw new In("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),dn.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:o,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});r(new Lb(c,l,Qa(e.totalLength),a),{identity:t})}})}handleStreamChunk(e,t){const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new In("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),dn.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new In("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),dn.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new In("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),dn.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new In("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),dn.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Cp{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return P(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Ob extends Cp{}class Ub extends Cp{}const Ep=15e3;class Fb{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return P(this,void 0,void 0,function*(){var n;const s=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(n=t==null?void 0:t.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(u,h)=>{var f;c[h]=u;const g=c.reduce((v,m)=>v+m,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},d=yield this.streamText({streamId:s,totalSize:o,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:a,attributes:t==null?void 0:t.attributes});return yield d.write(e),l(1,0),yield d.close(),t!=null&&t.attachments&&a&&(yield Promise.all(t.attachments.map((u,h)=>P(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{l(f,h+1)}})})))),d.info})}streamText(e){return P(this,void 0,void 0,function*(){var t,n,s;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),o={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e==null?void 0:e.topic)!==null&&n!==void 0?n:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?Ht.GCM:Ht.NONE},a=new Oa({streamId:r,mimeType:o.mimeType,topic:o.topic,timestamp:ms(o.timestamp),totalLength:ms(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new Ah({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?gc.UPDATE:gc.CREATE})}}),c=e==null?void 0:e.destinationIdentities,l=new ln({destinationIdentities:c,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(l,Ke.RELIABLE);let d=0;const u=this.engine,h=new WritableStream({write(v){return P(this,void 0,void 0,function*(){for(const m of Py(v,Ep)){const p=new Ua({content:m,streamId:r,chunkIndex:ms(d)}),T=new ln({destinationIdentities:c,value:{case:"streamChunk",value:p}});yield u.sendDataPacket(T,Ke.RELIABLE),d+=1}})},close(){return P(this,void 0,void 0,function*(){const v=new Fa({streamId:r}),m=new ln({destinationIdentities:c,value:{case:"streamTrailer",value:v}});yield u.sendDataPacket(m,Ke.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let f=()=>P(this,void 0,void 0,function*(){yield g.close()});u.once(le.Closing,f);const g=new Ob(h,o,()=>this.engine.off(le.Closing,f));return g})}sendFile(e,t){return P(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return P(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=n==null?void 0:n.mimeType)!==null&&s!==void 0?s:t.type,topic:n==null?void 0:n.topic,destinationIdentities:n==null?void 0:n.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return P(this,void 0,void 0,function*(){var t,n,s,r,o,a;const c=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),l=e==null?void 0:e.destinationIdentities,d={id:c,mimeType:(n=e==null?void 0:e.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(s=e==null?void 0:e.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?Ht.GCM:Ht.NONE},u=new Oa({totalLength:ms((a=d.size)!==null&&a!==void 0?a:0),mimeType:d.mimeType,streamId:c,topic:d.topic,timestamp:ms(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new Rh({name:d.name})}}),h=new ln({destinationIdentities:l,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,Ke.RELIABLE);let f=0;const g=new cn,v=this.engine,m=this.log,p=new WritableStream({write(E){return P(this,void 0,void 0,function*(){const y=yield g.lock();let S=0;try{for(;S<E.byteLength;){const C=E.slice(S,S+Ep),w=new ln({destinationIdentities:l,value:{case:"streamChunk",value:new Ua({content:C,streamId:c,chunkIndex:ms(f)})}});yield v.sendDataPacket(w,Ke.RELIABLE),f+=1,S+=C.byteLength}}finally{y()}})},close(){return P(this,void 0,void 0,function*(){const E=new Fa({streamId:c}),y=new ln({destinationIdentities:l,value:{case:"streamTrailer",value:E}});yield v.sendDataPacket(y,Ke.RELIABLE)})},abort(E){m.error("Sink error:",E)}});return new Ub(p,d)})}}class Mp extends Z{constructor(e,t,n,s,r){super(e,n,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ae.Muted:ae.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(ae.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),ul)),cy()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:s,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(ae.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Bb extends Mp{constructor(e,t,n,s,r,o){super(e,t,Z.Kind.Audio,n,o),this.monitorReceiver=()=>P(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=eo(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;ei()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(ei())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return P(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(qc(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&qc(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{n.connect(s),n=s}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(ae.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(ae.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return P(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const vl=100;class zb extends Mp{constructor(e,t,n,s,r){super(e,t,Z.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>P(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=eo(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=al(()=>{this.updateDimensions()},vl),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===Z.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Hs(this._mediaStreamTrack,t):Gs(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Vb(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return P(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&n!==""&&s.get(n)&&(t.mimeType=s.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;const s=this.elementInfos.reduce((c,l)=>Math.max(c,l.visibilityChangedAt||0),0),r=!((n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,o=this.elementInfos.some(c=>c.pictureInPicture),a=this.elementInfos.some(c=>c.visible)&&!r||o;if(!(this.lastVisible===a&&!e)){if(!a&&Date.now()-s<vl){Zt.setTimeout(()=>{this.updateVisibility()},vl);return}this.lastVisible=a,this.emit(ae.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let n=0,s=0;const r=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*r,c=o.height()*r;a+c>n+s&&(n=a,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:n,height:s},this.emit(ae.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Hf():t||(Hf()>2?2:1)}}class Vb{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:o}=n;r===this.element&&(this.isIntersecting=o,this.isPiP=Xr(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var n,s,r;(s=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Xr(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=Xr(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??yl(e),this.isPiP=bn()&&Xr(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=yl(this.element),this.isPiP=Xr(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,qf().observe(this.element),Wf().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,s,r;(e=qf())===null||e===void 0||e.unobserve(this.element),(t=Wf())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function Xr(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?yl(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function yl(i,e){const t=e||window;let n=i.offsetTop,s=i.offsetLeft;const r=i.offsetWidth,o=i.offsetHeight,{hidden:a}=i,{display:c}=getComputedStyle(i);for(;i.offsetParent;)i=i.offsetParent,n+=i.offsetTop,s+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&n+o>t.pageYOffset&&s+r>t.pageXOffset&&!a&&c!=="none"}class bi extends Zn.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=Ht.NONE,this.log=He,this.handleMuted=()=>{this.emit(ae.Muted)},this.handleUnmuted=()=>{this.emit(ae.Unmuted)},this.log=mi((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Vn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=Z.Source.Unknown}setTrack(e){this.track&&(this.track.off(ae.Muted,this.handleMuted),this.track.off(ae.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ae.Muted,this.handleMuted),e.on(ae.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Je(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Ht.NONE}get audioTrack(){if(ni(this.track))return this.track}get videoTrack(){if(Wi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Z.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Z.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(i.PermissionStatus||(i.PermissionStatus={}))})(bi||(bi={}));class bl extends bi{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(ae.Ended)},this.handleCpuConstrained=()=>{this.track&&Wi(this.track)&&this.emit(ae.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(ae.Ended,this.handleTrackEnded),this.track.off(ae.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ae.Ended,this.handleTrackEnded),e.on(ae.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(ni(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add($t.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add($t.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add($t.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add($t.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add($t.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add($t.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function io(i,e){return P(this,void 0,void 0,function*(){i??(i={});let t=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=Of(i);let o=r.audio,a=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),s&&typeof r.video=="object"&&(r.video.processor=s),i.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=Df(r,cp,lp),l=Vc(c),d=navigator.mediaDevices.getUserMedia(l);r.audio&&(Xt.userMediaPromiseMap.set("audioinput",d),d.catch(()=>Xt.userMediaPromiseMap.delete("audioinput"))),r.video&&(Xt.userMediaPromiseMap.set("videoinput",d),d.catch(()=>Xt.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>P(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let v;const m=f?l.audio:l.video;typeof m!="boolean"&&(v=m);const p=h.getSettings().deviceId;v!=null&&v.deviceId&&Hi(v.deviceId)!==p?v.deviceId=p:v||(v={deviceId:p});const T=mb(h,v,e);return T.kind===Z.Kind.Video?T.source=Z.Source.Camera:T.kind===Z.Kind.Audio&&(T.source=Z.Source.Microphone),T.mediaStream=u,ni(T)&&n?yield T.setProcessor(n):Wi(T)&&s&&(yield T.setProcessor(s)),T})))}catch(u){if(!t)throw u;return io(Object.assign(Object.assign({},i),{audio:o,video:a}),e)}})}function Gb(i){return P(this,void 0,void 0,function*(){return(yield io({audio:!1,video:!0}))[0]})}function Hb(i){return P(this,void 0,void 0,function*(){return(yield io({audio:!0,video:!1}))[0]})}var Ki;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(Ki||(Ki={}));function Wb(i){switch(i){case Lr.EXCELLENT:return Ki.Excellent;case Lr.GOOD:return Ki.Good;case Lr.POOR:return Ki.Poor;case Lr.LOST:return Ki.Lost;default:return Ki.Unknown}}class wp extends Zn.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Or.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Os.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,s,r,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Or.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Ki.Unknown,this.log=He,this.log=mi((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:Vn.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Dn,this.once(de.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(Z.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Z.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Z.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Os.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Os.ACTIVE&&this.emit(de.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(de.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(de.ParticipantNameChanged,e)}_setAttributes(e){const t=ly(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(de.AttributesChanged,t)}setPermissions(e){var t,n,s,r,o,a;const c=this.permissions,l=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,l&&this.emit(de.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(de.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Wb(e),t!==this._connectionQuality&&this.emit(de.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>ni(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(ae.Muted,()=>{this.emit(de.TrackMuted,e)}),e.on(ae.Unmuted,()=>{this.emit(de.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Z.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Z.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function qb(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Nh({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}class jb extends wp{constructor(e,t,n,s,r,o){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Ht.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Dn)},this.handleReconnected=()=>{var a,c;(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||c===void 0||c.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var a,c,l,d,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||c===void 0||c.call(a,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(l=this.signalConnectedFuture).reject)===null||d===void 0||d.call(l,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var c,l;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Dn),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=a=>{const{requestId:c,reason:l,message:d}=a,u=this.pendingSignalRequests.get(c);u&&(l!==Cc.OK&&u.reject(new kf(d,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let c=a.value.value,l=null,d=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(d=It.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,d);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>qb(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,c)=>{if(c===void 0&&(c=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Je(a)));return}this.engine.updateMuteStatus(a.sid,c)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Je(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Je(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const c=this.audioTrackPublications.get(a.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(a,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),Je(c))),this.emit(de.LocalTrackCpuConstrained,a,c)},this.handleSubscribedQualityUpdate=a=>P(this,void 0,void 0,function*(){var c,l,d,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(!f.videoTrack)return;const g=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var v=!0,m=gi(g),p;p=yield m.next(),c=p.done,!c;v=!0){u=p.value,v=!1;const T=u;sy(T)&&(this.log.debug("publish ".concat(T," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Je(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,T,f.options))}}catch(T){l={error:T}}finally{try{!v&&!c&&(d=m.return)&&(yield d.call(m))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=a=>{const c=this.trackPublications.get(a.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=a=>P(this,void 0,void 0,function*(){if(a.source===Z.Source.ScreenShare||a.source===Z.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Je(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(yi(a)||qi(a))try{if(bn())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:a.source===Z.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),Je(a))),c.onchange=()=>{c.state!=="denied"&&(a.isMuted||a.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Je(a))),yi(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Je(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=s,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Ht.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(le.RemoteMute,(n,s)=>{const r=this.trackPublications.get(n);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(le.Connected,this.handleReconnected).on(le.SignalConnected,this.handleSignalConnected).on(le.SignalRestarted,this.handleReconnected).on(le.SignalResumed,this.handleReconnected).on(le.Restarting,this.handleReconnecting).on(le.Resuming,this.handleReconnecting).on(le.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(le.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(le.Closing,this.handleClosing).on(le.SignalRequestResponse,this.handleSignalRequestResponse).on(le.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return P(this,arguments,void 0,function(t){var n=this;let{metadata:s,name:r,attributes:o}=t;return(function*(){return new vn((a,c)=>P(n,void 0,void 0,function*(){var l,d;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=s??this.metadata)!==null&&l!==void 0?l:"",(d=r??this.name)!==null&&d!==void 0?d:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),u=!0},values:{name:r,metadata:s,attributes:o}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!o||Object.entries(o).every(g=>{let[v,m]=g;return this.attributes[v]===m||m===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),a();return}yield Qt(50)}c(new kf("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(Z.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(Z.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(Z.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){this.encryptionType=e?Ht.GCM:Ht.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){return P(this,void 0,void 0,function*(){var r,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case Z.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case Z.Source.Microphone:c=yield this.createTracks({audio:(o=n)!==null&&o!==void 0?o:!0});break;case Z.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new vi(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(de.MediaDevicesError,l,Gc(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===Z.Source.Microphone&&ni(l)&&d.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Je(u))),l.push(this.publishTrack(u,s));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===Z.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(Z.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return P(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(Z.Source.Camera)||this.pendingPublishing.has(Z.Source.Microphone))){this.pendingPublishing.add(Z.Source.Camera),this.pendingPublishing.add(Z.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(Z.Source.Camera),this.pendingPublishing.delete(Z.Source.Microphone)}}})}createTracks(e){return P(this,void 0,void 0,function*(){var t,n;e??(e={});const s=Df(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield io(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(ni(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=Z.Source.Microphone,this.emit(de.AudioStreamAcquired)),Wi(a)&&(this.cameraError=void 0,a.source=Z.Source.Camera),a))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return P(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Oc("getDisplayMedia not supported");e.resolution===void 0&&!yy()&&(e.resolution=Bc.h1080fps30.resolution);const t=ay(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new vi("no video track found");const r=new no(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Z.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const o=[r];if(n.getAudioTracks().length>0){this.emit(de.AudioStreamAcquired);const a=new to(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=Z.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){return P(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,c,l,d;yi(n)&&n.setAudioContext(r.audioContext),yield(a=r.reconnectFuture)===null||a===void 0?void 0:a.promise,r.republishPromise&&!o&&(yield r.republishPromise),qs(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let u;if(n instanceof MediaStreamTrack)u=n.getConstraints();else{u=n.constraints;let p;switch(n.source){case Z.Source.Microphone:p="audioinput";break;case Z.Source.Camera:p="videoinput"}p&&r.activeDeviceMap.has(p)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(p)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new to(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new no(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new vi("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(p=>{p.track&&p.track===n&&(h=p)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),Je(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),g="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,v=(c=f.forceStereo)!==null&&c!==void 0?c:g;v&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),Je(n))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=f.dtx)!==null&&l!==void 0||(f.dtx=!1),(d=f.red)!==null&&d!==void 0||(f.red=!1)),!_y()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},r.logContext)),f.simulcast=!1),f.source&&(n.source=f.source);const m=new Promise((p,T)=>P(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==vt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Je(n)}));let E=!1;const y=setTimeout(()=>{E=!0,n.stop(),T(new Pf("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(y),E)return;const S=yield this.publish(n,f,v);p(S)}else try{const E=yield this.publish(n,f,v);p(E)}catch(E){T(E)}}catch(E){T(E)}}));r.pendingPublishPromises.set(n,m);try{return yield m}catch(p){throw p}finally{r.pendingPublishPromises.delete(n)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Dn),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Je(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(s=>dy(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Je(e))),!1)}publish(e,t,n){return P(this,void 0,void 0,function*(){var s,r,o,a,c,l,d,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Pf("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(_=>qs(e)&&_.source===e.source)&&e.source!==Z.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Je(e))),t.stopMicTrackOnMute&&ni(e)&&(e.stopOnMute=!0),e.source===Z.Source.ScreenShare&&fs()&&(t.simulcast=!1),t.videoCodec==="av1"&&!my()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!gy()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=cl),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(_=>t.videoCodec===Vr(_.mime))||(t.videoCodec=Vr(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(ae.Muted,this.onTrackMuted),e.on(ae.Unmuted,this.onTrackUnmuted),e.on(ae.Ended,this.handleTrackEnded),e.on(ae.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ae.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ae.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],p=!(!((s=t.dtx)!==null&&s!==void 0)||s),T=e.getSourceTrackSettings();T.autoGainControl&&m.push($t.TF_AUTO_GAIN_CONTROL),T.echoCancellation&&m.push($t.TF_ECHO_CANCELLATION),T.noiseSuppression&&m.push($t.TF_NOISE_SUPPRESSION),T.channelCount&&T.channelCount>1&&m.push($t.TF_STEREO),p&&m.push($t.TF_NO_DTX),yi(e)&&e.hasPreConnectBuffer&&m.push($t.TF_PRECONNECT_BUFFER);const E=new Ur({cid:e.mediaStreamTrack.id,name:t.name,type:Z.kindToProto(e.kind),muted:e.isMuted,source:Z.sourceToProto(e.source),disableDtx:p,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:m});let y;if(e.kind===Z.Kind.Video){let _={width:0,height:0};try{_=yield e.waitForDimensions()}catch{const R=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:zr.h720.resolution;_={width:R.width,height:R.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Je(e)),{dims:_}))}E.width=_.width,E.height=_.height,qi(e)&&(Gn(v)&&(e.source===Z.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Je(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),E.simulcastCodecs=[new yc({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:cl}),t.backupCodec&&v!==t.backupCodec.codec&&E.encryption===Ht.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),E.simulcastCodecs.push(new yc({codec:t.backupCodec.codec,cid:""})))),y=pl(e.source===Z.Source.ScreenShare,E.width,E.height,t),E.layers=bp(E.width,E.height,y,Gn(t.videoCodec))}else e.kind===Z.Kind.Audio&&(y=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Ut("cannot publish track when not connected");const S=()=>P(this,void 0,void 0,function*(){var _,x,R;if(!this.engine.pcManager)throw new Ut("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),this.emit(de.LocalSenderCreated,e.sender,e),qi(e)&&((_=t.degradationPreference)!==null&&_!==void 0||(t.degradationPreference=Eb(e)),e.setDegradationPreference(t.degradationPreference)),y)if(fs()&&e.kind===Z.Kind.Audio){let O;for(const F of this.engine.pcManager.publisher.getTransceivers())if(F.sender===e.sender){O=F;break}O&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:O,codec:"opus",maxbr:!((x=y[0])===null||x===void 0)&&x.maxBitrate?y[0].maxBitrate/1e3:0})}else e.codec&&Gn(e.codec)&&(!((R=y[0])===null||R===void 0)&&R.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:E.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let C;const w=new Promise((_,x)=>P(this,void 0,void 0,function*(){var R;try{C=yield this.engine.addTrack(E),_(C)}catch(O){e.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(F=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),Je(e)),{error:F}))})),x(O)}}));if(this.enabledPublishVideoCodecs.length>0)C=(yield Promise.all([w,S()]))[0];else{C=yield w;let _;if(C.codecs.forEach(x=>{_===void 0&&(_=x.mimeType)}),_&&e.kind===Z.Kind.Video){const x=Vr(_);x!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Je(e)),{codec:x})),t.videoCodec=x,y=pl(e.source===Z.Source.ScreenShare,E.width,E.height,t))}yield S()}const k=new bl(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(k.on(ae.CpuConstrained,_=>this.onTrackCpuConstrained(_,k)),k.options=t,e.sid=C.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:C})),qi(e)?e.startMonitor(this.engine.client):yi(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(de.LocalTrackPublished,k),yi(e)&&C.audioFeatures.includes($t.TF_PRECONNECT_BUFFER)){const _=e.getPreConnectBuffer(),x=e.getPreConnectBufferMimeType();this.on(de.LocalTrackSubscribed,R=>{if(R.trackSid===C.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),Je(e))),e.stopPreConnectBuffer()}}),_&&new Promise((O,F)=>P(this,void 0,void 0,function*(){var q,K,G,W,te,ye;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Je(e)));const Ve=setTimeout(()=>{F(new Error("agent not active within 10 seconds"))},1e4),Mt=yield this.waitUntilActiveAgentPresent();clearTimeout(Ve),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Je(e)));const pt=yield this.streamBytes({name:"preconnect-buffer",mimeType:x,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Mt.identity],attributes:{trackId:k.trackSid,sampleRate:String((te=T.sampleRate)!==null&&te!==void 0?te:"48000"),channels:String((ye=T.channelCount)!==null&&ye!==void 0?ye:"1")}});try{for(var ue=!0,_e=gi(_),Ge;Ge=yield _e.next(),q=Ge.done,!q;ue=!0){W=Ge.value,ue=!1;const Y=W;yield pt.write(Y)}}catch(Y){K={error:Y}}finally{try{!ue&&!q&&(G=_e.return)&&(yield G.call(_e))}finally{if(K)throw K.error}}yield pt.close(),O()}catch(Ve){F(Ve)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Je(e)))}).catch(O=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Je(e)),{error:O}))})}return k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return P(this,void 0,void 0,function*(){var s;if(this.encryptionType!==Ht.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new vi("track is not published");if(!qi(e))throw new vi("track is not a video track");const o=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),n),a=xb(e,t,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Je(e)));return}const c=e.addSimulcastTrack(t,a);if(!c)return;const l=new Ur({cid:c.mediaStreamTrack.id,type:Z.kindToProto(e.kind),muted:e.isMuted,source:Z.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=bp(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new Ut("cannot publish track when not connected");const d=()=>P(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,t){return P(this,void 0,void 0,function*(){var n,s;if(qs(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Je(e))),yield l)}const r=this.getPublicationForTrack(e),o=r?Je(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=r.track,e.off(ae.Muted,this.onTrackMuted),e.off(ae.Unmuted,this.onTrackUnmuted),e.off(ae.Ended,this.handleTrackEnded),e.off(ae.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ae.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ae.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<kt.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),qi(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case Z.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Z.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(de.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return P(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new vn((r,o)=>P(n,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),a.push(c))}),yield Promise.all(a.map(c=>P(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),s&&!l.isMuted&&l.source!==Z.Source.ScreenShare&&l.source!==Z.Source.ScreenShareAudio&&(yi(l)||qi(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),r()}catch(a){a instanceof Error?o(a):o(new Error(String(a)))}finally{this.republishPromise=void 0}})),yield n.republishPromise})()})}publishData(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?Ke.RELIABLE:Ke.LOSSY,o=s.destinationIdentities,a=s.topic;let c=new hc({participantIdentity:n.identity,payload:t,destinationIdentities:o,topic:a});const l=new ln({kind:r,value:{case:"user",value:c}});yield n.engine.sendDataPacket(l,r)})()})}publishDtmf(e,t){return P(this,void 0,void 0,function*(){const n=new ln({kind:Ke.RELIABLE,value:{case:"sipDtmf",value:new yh({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Ke.RELIABLE)})}sendChatMessage(e,t){return P(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new ln({value:{case:"chatMessage",value:new Na(Object.assign(Object.assign({},n),{timestamp:wt.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,Ke.RELIABLE),this.emit(de.ChatMessage,n),n})}editChatMessage(e,t){return P(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new ln({value:{case:"chatMessage",value:new Na(Object.assign(Object.assign({},n),{timestamp:wt.parse(n.timestamp),editTimestamp:wt.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,Ke.RELIABLE),this.emit(de.ChatMessage,n),n})}sendText(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:n,payload:s,responseTimeout:r=15e3}=e;const o=7e3,a=o+1e3;return new vn((c,l)=>P(this,void 0,void 0,function*(){var d,u,h,f;if(dl(s)>up){l(It.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||u===void 0)&&u.version&&ti((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){l(It.builtIn("UNSUPPORTED_SERVER"));return}const g=Math.max(r,a),v=crypto.randomUUID();yield this.publishRpcRequest(t,v,n,s,g);const m=setTimeout(()=>{this.pendingAcks.delete(v),l(It.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(p)},o);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(m)},participantIdentity:t});const p=setTimeout(()=>{this.pendingResponses.delete(v),l(It.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(T,E)=>{clearTimeout(p),this.pendingAcks.has(v)&&(this.log.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(m)),E?l(E):c(T??"")},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const s=this.pendingResponses.get(e);s?(s.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,s,r){return P(this,void 0,void 0,function*(){const o=new ln({destinationIdentities:[e],kind:Ke.RELIABLE,value:{case:"rpcRequest",value:new fc({id:t,method:n,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(o,Ke.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:s}]of this.pendingResponses)n===e&&(s(null,It.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var n,s;const r=this.trackPublications.get(t.sid);if(r){const o=r.isMuted||((s=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&s!==void 0?s:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Je(r)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0):!1}setActiveAgent(e){var t,n,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||n===void 0||n.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Dn),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(yi(s)||qi(s))&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}waitForPendingPublicationOfSource(e){return P(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[o]=r;return o.source===e});if(s)return s[1];yield Qt(20)}})}}class $b extends bi{constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(ae.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new Va({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new _h({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ae.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?bi.SubscriptionStatus.Unsubscribed:super.isSubscribed?bi.SubscriptionStatus.Subscribed:bi.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?bi.PermissionStatus.Allowed:bi.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.height)===e.height||(Jc(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Jc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Mn.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(ae.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(ae.VisibilityChanged,this.handleVisibilityChange),s.off(ae.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(ae.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ae.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ae.VisibilityChanged,this.handleVisibilityChange),e.on(ae.Ended,this.handleEnded),this.emit(ae.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(ae.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?ae.Muted:ae.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(ae.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ae.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Jc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new kh({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Z.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Uf(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const n=uy(this.trackInfo,this.requestedMaxQuality);n&&Uf(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Mn.HIGH})),e.quality=Mn.HIGH)}this.emit(ae.UpdateSettings,e)}}class so extends wp{static fromParticipantInfo(e,t,n){return new so(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,s,r,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Or.STANDARD;super(t,n||"",s,r,o,a,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(ae.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Je(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(ae.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(ae.SubscriptionPermissionChanged,t=>{this.emit(de.TrackSubscriptionPermissionChanged,e,t)}),e.on(ae.SubscriptionStatusChanged,t=>{this.emit(de.TrackSubscriptionStatusChanged,e,t)}),e.on(ae.Subscribed,t=>{this.emit(de.TrackSubscribed,t,e)}),e.on(ae.Unsubscribed,t=>{this.emit(de.TrackUnsubscribed,t,e)}),e.on(ae.SubscriptionFailed,t=>{this.emit(de.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Z.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Z.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,s,r,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(d=>{!a&&e.kind===d.kind.toString()&&(a=d)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(de.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,s,r,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Je(a))),this.emit(de.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new zb(e,t,s,r):l=new Bb(e,t,s,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(n),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&Yc(l)&&ni(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(s=>{var r,o;let a=this.getTrackPublicationBySid(s.sid);if(a)a.updateInfo(s);else{const c=Z.kindFromProto(s.type);if(!c)return;a=new $b(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(s),n.set(s.sid,a);const l=Array.from(this.trackPublications.values()).find(d=>d.source===(a==null?void 0:a.source));l&&a.source!==Z.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Je(l),newTrack:Je(a)})),this.addTrackPublication(a)}t.set(s.sid,a)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Je(s))),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(de.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case Z.Kind.Audio:this.audioTrackPublications.delete(e);break;case Z.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(de.TrackUnpublished,n)}setAudioOutput(e){return P(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;ni(n.track)&&Yc(n.track)&&t.push(n.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var ot;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(ot||(ot={}));const Xb=4*1e3;class Ks extends Zn.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,n,s,r,o;if(super(),t=this,this.state=ot.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=He,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(a,c,l)=>P(this,void 0,void 0,function*(){var d;if(!vy())throw ei()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===ot.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(ot.Connecting),((d=this.regionUrlProvider)===null||d===void 0?void 0:d.getServerUrl().toString())!==Xf(a)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ws(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new et(a,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(g=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(g)}).catch(g=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:g}))}));const h=(g,v,m)=>P(this,void 0,void 0,function*(){var p,T;this.abortController&&this.abortController.abort();const E=new AbortController;this.abortController=E,u==null||u();try{if(yield js.getInstance().getBackOffPromise(a),E.signal.aborted)throw Ne.cancelled("Connection attempt aborted");yield this.attemptConnection(m??a,c,l,E),this.abortController=void 0,g()}catch(y){if(this.regionUrlProvider&&y instanceof Ne&&y.reason!==gt.Cancelled&&y.reason!==gt.NotAllowed){let S=null;try{this.log.debug("Fetching next region"),S=yield this.regionUrlProvider.getNextBestRegionUrl((p=this.abortController)===null||p===void 0?void 0:p.signal)}catch(C){if(C instanceof Ne&&(C.status===401||C.reason===gt.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(C);return}}[gt.InternalError,gt.ServerUnreachable,gt.Timeout].includes(y.reason)&&(this.log.debug("Adding failed connection attempt to back off"),js.getInstance().addFailedConnectionAttempt(a)),S&&!(!((T=this.abortController)===null||T===void 0)&&T.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(y.message,". Retrying with another region: ").concat(S),this.logContext),this.recreateEngine(),yield h(g,v,S)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,$f(y)),v(y))}else{let S=Bn.UNKNOWN_REASON;y instanceof Ne&&(S=$f(y)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,S),v(y)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Dn((g,v)=>{h(g,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,c,l,d,u,h)=>P(this,void 0,void 0,function*(){var f,g,v;const m=yield l.join(a,c,{autoSubscribe:d.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:d.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:d.websocketTimeout},h.signal,!u.singlePeerConnection);let p=m.serverInfo;if(p||(p={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=p,this.log.debug("connected to Livekit Server ".concat(Object.entries(p).map(T=>{let[E,y]=T;return"".concat(E,": ").concat(y)}).join(", ")),{room:(f=m.room)===null||f===void 0?void 0:f.name,roomSid:(g=m.room)===null||g===void 0?void 0:g.sid,identity:(v=m.participant)===null||v===void 0?void 0:v.identity}),!p.version)throw new Q0("unknown server version");return p.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),m}),this.applyJoinResponse=a=>{const c=a.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([c,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,c,l,d)=>P(this,void 0,void 0,function*(){var u,h;this.state===ot.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ll),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(a,c,this.engine,this.connOptions,this.options,d);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(ne.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const g=d.signal.aborted?Ne.cancelled("Signal connection aborted"):Ne.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(g.message="".concat(g.message,": ").concat(f.message)),f instanceof Ne&&(g.reason=f.reason,g.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),g}if(d.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),Ne.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,d)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}bn()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),bn()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ot.Connected),this.emit(ne.Connected),js.getInstance().resetFailedConnectionAttempts(a),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];return P(t,[...c],void 0,function(){var d=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,g;const v=yield d.disconnectLock.lock();try{if(d.state===ot.Disconnected){d.log.debug("already disconnected",d.logContext);return}if(d.log.info("disconnect from room",Object.assign({},d.logContext)),d.state===ot.Connecting||d.state===ot.Reconnecting||d.isResuming){const m="Abort connection attempt due to user initiated disconnect";d.log.warn(m,d.logContext),(h=d.abortController)===null||h===void 0||h.abort(m),(g=(f=d.connectFuture)===null||f===void 0?void 0:f.reject)===null||g===void 0||g.call(f,Ne.cancelled("Client initiated disconnect")),d.connectFuture=void 0}d.engine&&(d.engine.client.isDisconnected||(yield d.engine.client.sendLeave()),yield d.engine.close()),d.handleDisconnect(u,Bn.CLIENT_INITIATED),d.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>P(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>P(this,void 0,void 0,function*(){const a=[],c=yn();if(c&&c.os==="iOS"){const l="livekit-dummy-audio-el";let d=document.getElementById(l);if(!d){d=document.createElement("audio"),d.id=l,d.autoplay=!0,d.hidden=!0;const u=Kc();u.enabled=!0;const h=new MediaStream([u]);d.srcObject=h,document.addEventListener("visibilitychange",()=>{d&&(d.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(d),this.once(ne.Disconnected,()=>{d==null||d.remove(),d=null})}a.push(d)}this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(d=>{d.track&&d.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>P(this,void 0,void 0,function*(){const a=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(l=>{var d;(d=l.track)===null||d===void 0||d.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(ot.Reconnecting)&&this.emit(ne.Reconnecting)},this.handleSignalRestarted=a=>P(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(ot.Connected),this.emit(ne.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(c=>{var l;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(l=this.sidToIdentity.get(c.sid))!==null&&l!==void 0?l:"");let d=this.remoteParticipants.get(c.identity);c.state===Os.DISCONNECTED?this.handleParticipantDisconnected(c.identity,d):d=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=a=>{const c=[],l={};a.forEach(d=>{if(l[d.sid]=!0,d.sid===this.localParticipant.sid)this.localParticipant.audioLevel=d.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(d.sid);u&&(u.audioLevel=d.level,u.setIsSpeaking(!0),c.push(u))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(d=>{l[d.sid]||(d.audioLevel=0,d.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(ne.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=a=>{const c=new Map;this.activeSpeakers.forEach(d=>{const u=this.remoteParticipants.get(d.identity);u&&u.sid!==d.sid||c.set(d.sid,d)}),a.forEach(d=>{let u=this.getRemoteParticipantBySid(d.sid);d.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=d.level,u.setIsSpeaking(d.active),d.active?c.set(d.sid,u):c.delete(d.sid))});const l=Array.from(c.values());l.sort((d,u)=>u.audioLevel-d.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(ne.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(c=>{const l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;const d=l.getTrackPublicationBySid(c.trackSid);if(!d||!d.track)return;const u=Z.streamStateFromProto(c.state);d.track.setStreamState(u),u!==d.track.streamState&&(l.emit(de.TrackStreamStateChanged,d,d.track.streamState),this.emitWhenConnected(ne.TrackStreamStateChanged,d,d.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);l&&l.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const c=Array.from(this.remoteParticipants.values()).find(d=>d.trackPublications.has(a.trackSid));if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);l&&l.setSubscriptionError(a.err)},this.handleDataPacket=(a,c)=>{const l=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(l,a.value.value,a.kind,c);else if(a.value.case==="transcription")this.handleTranscription(l,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(l,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(l,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,l);else if(a.value.case==="streamHeader"||a.value.case==="streamChunk"||a.value.case==="streamTrailer")this.handleDataStream(a,c);else if(a.value.case==="rpcRequest"){const d=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,d.id,d.method,d.payload,d.responseTimeoutMs,d.version)}},this.handleUserPacket=(a,c,l,d)=>{this.emit(ne.DataReceived,c.payload,a,l,c.topic,d),a==null||a.emit(de.DataReceived,c.payload,l,d)},this.handleSipDtmf=(a,c)=>{this.emit(ne.SipDTMFReceived,c,a),a==null||a.emit(de.SipDTMFReceived,c)},this.handleTranscription=(a,c)=>{const l=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),d=l==null?void 0:l.trackPublications.get(c.trackId),u=My(c,this.transcriptionReceivedTimes);d==null||d.emit(ae.TranscriptionReceived,u),l==null||l.emit(de.TranscriptionReceived,u,d),this.emit(ne.TranscriptionReceived,u,l,d)},this.handleChatMessage=(a,c)=>{const l=wy(c);this.emit(ne.ChatMessage,l,a)},this.handleMetrics=(a,c)=>{this.emit(ne.MetricsReceived,a,c)},this.handleDataStream=(a,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(a,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(ne.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(ne.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ne.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ne.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>P(this,void 0,void 0,function*(){var a;((a=yn())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(ne.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const c=this.roomInfo;this.roomInfo=a,c&&c.metadata!==a.metadata&&this.emitWhenConnected(ne.RoomMetadataChanged,a.metadata),(c==null?void 0:c.activeRecording)!==a.activeRecording&&this.emitWhenConnected(ne.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const l=this.getRemoteParticipantBySid(c.participantSid);l&&l.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(ne.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(ne.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(ne.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(ne.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(ne.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var c;(c=a==null?void 0:a.onPublish)===null||c===void 0||c.call(a,this)},this.onLocalTrackPublished=a=>P(this,void 0,void 0,function*(){var c,l,d,u,h,f;(c=a.track)===null||c===void 0||c.on(ae.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.on(ae.Restarted,this.onLocalTrackRestarted),(h=(u=(d=a.track)===null||d===void 0?void 0:d.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(ne.LocalTrackPublished,a,this.localParticipant),yi(a.track)&&(yield a.track.checkForSilence())&&this.emit(ne.LocalAudioSilenceDetected,a);const g=yield(f=a.track)===null||f===void 0?void 0:f.getDeviceId(!1),v=Gc(a.source);v&&g&&g!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,g),this.emit(ne.ActiveDeviceChanged,v,g))}),this.onLocalTrackUnpublished=a=>{var c,l;(c=a.track)===null||c===void 0||c.off(ae.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.off(ae.Restarted,this.onLocalTrackRestarted),this.emit(ne.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>P(this,void 0,void 0,function*(){const c=yield a.getDeviceId(!1),l=Gc(a.source);l&&c&&c!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,c),this.emit(ne.ActiveDeviceChanged,l,c))}),this.onLocalConnectionQualityChanged=a=>{this.emit(ne.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,c)=>{this.emit(ne.MediaDevicesError,a,c)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(ne.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(ne.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},rb),e),this.log=mi((n=this.options.loggerName)!==null&&n!==void 0?n:Vn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},cp),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},lp),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},sb),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Nb,this.outgoingDataStreamManager=new Fb(this.engine,this.log),this.disconnectLock=new cn,this.localParticipant=new jb("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Hi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Hi(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Hi(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),bn()){const a=new AbortController;(o=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||o===void 0||o.call(r,"devicechange",this.handleDeviceChange,{signal:a.signal}),Ks.cleanupRegistry&&Ks.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&("e2eeManager"in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new Vy(n,t),this.e2eeManager.on($i.ParticipantEncryptionStatusChanged,(s,r)=>{Ry(r)&&(this.isE2EEEnabled=s),this.emit(ne.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on($i.EncryptionError,(s,r)=>{const o=r?this.getParticipantByIdentity(r):void 0;this.emit(ne.EncryptionError,s,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===ot.Disconnected?vn.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?vn.resolve(this.roomInfo.sid):new vn((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(le.RoomUpdate,n),e(s.sid))};this.engine.on(le.RoomUpdate,n),this.once(ne.Disconnected,()=>{this.engine.off(le.RoomUpdate,n),t(new Ut("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new kb(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(le.ParticipantUpdate,this.handleParticipantUpdates).on(le.RoomUpdate,this.handleRoomUpdate).on(le.SpeakersChanged,this.handleSpeakersChanged).on(le.StreamStateChanged,this.handleStreamStateUpdate).on(le.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(le.SubscriptionError,this.handleSubscriptionError).on(le.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(le.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(le.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(le.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(le.DataPacketReceived,this.handleDataPacket).on(le.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ot.SignalReconnecting)&&this.emit(ne.SignalReconnecting)}).on(le.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ot.Connected)&&this.emit(ne.Reconnected)}).on(le.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ot.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(le.Restarting,this.handleRestarting).on(le.SignalRestarted,this.handleSignalRestarted).on(le.Offline,()=>{this.setAndEmitConnectionState(ot.Reconnecting)&&this.emit(ne.Reconnecting)}).on(le.DCBufferStatusChanged,(e,t)=>{this.emit(ne.DCBufferStatusChanged,e,t)}).on(le.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:s}=n;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(de.LocalTrackSubscribed,t),this.emitWhenConnected(ne.LocalTrackSubscribed,t,this.localParticipant)}).on(le.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(ne.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Xt.getInstance().getDevices(e,t)}prepareConnection(e,t){return P(this,void 0,void 0,function*(){if(this.state===ot.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ws(new URL(e))&&t){this.regionUrlProvider=new et(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===ot.Disconnected&&(this.regionUrl=n,yield fetch(qr(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(qr(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return P(this,void 0,void 0,function*(){let n=()=>P(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Jn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Jn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Jn({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Jn({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Jn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Jn({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new Jn({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>P(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Ga({reason:Bn.CLIENT_INITIATED,action:Fs.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Jn({scenario:{case:"subscriberBandwidth",value:ms(t)}});break;case"leave-full-reconnect":s=new Jn({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,c,l,d,u,h,f;let g=!0,v=!1;const m=o?{exact:s}:s;if(n==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const p=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=m;const T=Array.from(r.localParticipant.audioTrackPublications.values()).filter(y=>y.source===Z.Source.Microphone);try{g=(yield Promise.all(T.map(y=>{var S;return(S=y.audioTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(y=>y===!0)}catch(y){throw r.options.audioCaptureDefaults.deviceId=p,y}const E=T.some(y=>{var S,C;return(C=(S=y.track)===null||S===void 0?void 0:S.isMuted)!==null&&C!==void 0?C:!1});g&&E&&(v=!0)}else if(n==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const p=(c=r.getActiveDevice(n))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=m;const T=Array.from(r.localParticipant.videoTrackPublications.values()).filter(y=>y.source===Z.Source.Camera);try{g=(yield Promise.all(T.map(y=>{var S;return(S=y.videoTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(y=>y===!0)}catch(y){throw r.options.videoCaptureDefaults.deviceId=p,y}const E=T.some(y=>{var S,C;return(C=(S=y.track)===null||S===void 0?void 0:S.isMuted)!==null&&C!==void 0?C:!1});g&&E&&(v=!0)}else if(n==="audiooutput"){if(v=!0,!qc()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(l=yield Xt.getInstance().normalizeDeviceId("audiooutput",s))!==null&&l!==void 0?l:""),(d=(f=r.options).audioOutput)!==null&&d!==void 0||(f.audioOutput={});const p=(u=r.getActiveDevice(n))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(T=>T.setAudioOutput({deviceId:s})))}catch(T){throw r.options.audioOutput.deviceId=p,T}}return v&&(r.localParticipant.activeDeviceMap.set(n,s),r.emit(ne.ActiveDeviceChanged,n,s)),g})()})}setupLocalParticipantEvents(){this.localParticipant.on(de.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(de.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(de.AttributesChanged,this.onLocalAttributesChanged).on(de.TrackMuted,this.onLocalTrackMuted).on(de.TrackUnmuted,this.onLocalTrackUnmuted).on(de.LocalTrackPublished,this.onLocalTrackPublished).on(de.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(de.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(de.MediaDevicesError,this.onMediaDevicesError).on(de.AudioStreamAcquired,this.startAudio).on(de.ChatMessage,this.onLocalChatMessageSent).on(de.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===ot.Connecting||this.state===ot.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,n),h()},h=()=>{this.off(ne.Reconnected,u),this.off(ne.Connected,u),this.off(ne.Disconnected,h)};this.once(ne.Reconnected,u),this.once(ne.Connected,u),this.once(ne.Disconnected,h);return}if(this.state===ot.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=py(t.id),r=s[0];let o=s[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!a.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(n);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}a=u}a.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(o,", trackId: ").concat(a),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:o,trackId:a}));let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={});const d=c.addSubscribedMediaTrack(e,a,t,n,l);d!=null&&d.isEncrypted&&!this.e2eeManager&&this.emit(ne.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==ot.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(o=>{r.unpublishTrack(o.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var o,a,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((o=r.track)===null||o===void 0||o.detach(),(a=r.track)===null||a===void 0||a.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(de.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(de.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(de.AttributesChanged,this.onLocalAttributesChanged).off(de.TrackMuted,this.onLocalTrackMuted).off(de.TrackUnmuted,this.onLocalTrackUnmuted).off(de.LocalTrackPublished,this.onLocalTrackPublished).off(de.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(de.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(de.MediaDevicesError,this.onMediaDevicesError).off(de.AudioStreamAcquired,this.startAudio).off(de.ChatMessage,this.onLocalChatMessageSent).off(de.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),bn()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(n=navigator.mediaDevices)===null||n===void 0?void 0:n.removeEventListener)===null||s===void 0||s.call(n,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ot.Disconnected),this.emit(ne.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(ne.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,s,r,o){return P(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),o!==1){yield this.engine.publishRpcResponse(e,t,null,It.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(n);if(!a){yield this.engine.publishRpcResponse(e,t,null,It.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield a({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});dl(d)>up?(c=It.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(n))):l=d}catch(d){d instanceof It?c=d:(this.log.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),d),c=It.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,c)})}selectDefaultDevices(){return P(this,void 0,void 0,function*(){var e,t,n;const s=Xt.getInstance().previousDevices,r=yield Xt.getInstance().getDevices(void 0,!1),o=yn();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of r){const l=s.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(ne.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=ry(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((n=u[0])===null||n===void 0?void 0:n.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Hr()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Hr())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return P(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Nf())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Qt(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(ne.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=so.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new so(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(ne.ParticipantConnected,n),n.on(de.TrackPublished,s=>{this.emitWhenConnected(ne.TrackPublished,s,n)}).on(de.TrackSubscribed,(s,r)=>{s.kind===Z.Kind.Audio?(s.on(ae.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(ae.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===Z.Kind.Video&&(s.on(ae.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(ae.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(ne.TrackSubscribed,s,r,n)}).on(de.TrackUnpublished,s=>{this.emit(ne.TrackUnpublished,s,n)}).on(de.TrackUnsubscribed,(s,r)=>{this.emit(ne.TrackUnsubscribed,s,r,n)}).on(de.TrackMuted,s=>{this.emitWhenConnected(ne.TrackMuted,s,n)}).on(de.TrackUnmuted,s=>{this.emitWhenConnected(ne.TrackUnmuted,s,n)}).on(de.ParticipantMetadataChanged,s=>{this.emitWhenConnected(ne.ParticipantMetadataChanged,s,n)}).on(de.ParticipantNameChanged,s=>{this.emitWhenConnected(ne.ParticipantNameChanged,s,n)}).on(de.AttributesChanged,s=>{this.emitWhenConnected(ne.ParticipantAttributesChanged,s,n)}).on(de.ConnectionQualityChanged,s=>{this.emitWhenConnected(ne.ConnectionQualityChanged,s,n)}).on(de.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(ne.ParticipantPermissionsChanged,s,n)}).on(de.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(ne.TrackSubscriptionStatusChanged,s,r,n)}).on(de.TrackSubscriptionFailed,(s,r)=>{this.emit(ne.TrackSubscriptionFailed,s,n,r)}).on(de.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(ne.TrackSubscriptionPermissionChanged,s,r,n)}).on(de.Active,()=>{this.emitWhenConnected(ne.ParticipantActive,n),n.kind===Or.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,s)=>(n.push(...s.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Ay(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Zt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Bn.STATE_MISMATCH))):e=0},Xb)}clearConnectionReconcile(){this.connectionReconcileInterval&&Zt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(ne.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(this.state===ot.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===ot.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return P(this,void 0,void 0,function*(){var t,n,s,r;const o=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Da({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:wt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new us({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(ne.SignalConnected),this.emit(ne.Connected),this.setAndEmitConnectionState(ot.Connected),o.video){const c=new bl(Z.Kind.Video,new Us({source:Bt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Fn.AUDIO,name:"video-dummy"}),new no(o.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:jf(160*((n=a.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(de.LocalTrackPublished,c)}if(o.audio){const c=new bl(Z.Kind.Audio,new Us({source:Bt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Fn.AUDIO}),new to(o.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Kc(),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(de.LocalTrackPublished,c)}for(let c=0;c<a.count-1;c+=1){let l=new us({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:Os.ACTIVE,tracks:[],joinedAt:wt.parse(Date.now())});const d=this.getOrCreateParticipant(l.identity,l);if(a.video){const u=jf(160*((r=a.aspectRatios[c%a.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new Us({source:Bt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Fn.AUDIO});d.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),l.tracks=[...l.tracks,h]}if(a.audio){const u=Kc(),h=new Us({source:Bt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Fn.AUDIO});d.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),l.tracks=[...l.tracks,h]}d.updateInfo(l)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(e!==ne.ActiveSpeakersChanged&&e!==ne.TranscriptionReceived){const r=Ap(n).filter(o=>o!==void 0);(e===ne.TrackSubscribed||e===ne.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}Ks.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(i=>{i()});function Ap(i){return i.map(e=>{if(e)return Array.isArray(e)?Ap(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Wn;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(Wn||(Wn={}));class Yi extends Zn.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Wn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Ks(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return P(this,void 0,void 0,function*(){if(this.status!==Wn.IDLE)throw Error("check is running already");this.setStatus(Wn.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Wn.SKIPPED&&this.setStatus(this.isSuccess()?Wn.SUCCESS:Wn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return P(this,void 0,void 0,function*(){return this.room.state===ot.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return P(this,void 0,void 0,function*(){this.room&&this.room.state!==ot.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Wn.SKIPPED)}switchProtocol(e){return P(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(ne.Reconnecting,()=>{t=!0}),this.room.once(ne.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(n)return;yield Qt(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Kb extends Yi{get description(){return"Cloud regions"}perform(){return P(this,void 0,void 0,function*(){const e=new et(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let r=0;r<3;r++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(n.has(o))continue;n.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),t.push(a)}t.sort((r,o)=>(r.duration-o.duration)*.5+(r.rtt-o.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return P(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),d=Date.now();for(let g=0;g<c;g++)yield r.write(l);yield r.close();const u=Date.now(),h=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),f={region:s,rtt:1e4,duration:u-d};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const _l=1e4;class Yb extends Yi{get description(){return"Connection via UDP vs TCP"}perform(){return P(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(_l/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(_l/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return P(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,n.fillStyle="hsl(".concat(s,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const a=t.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>P(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(d.packetsSent=f.packetsSent,d.qualityLimitationDurations=f.qualityLimitationDurations,d.bitrateTotal+=f.targetBitrate,d.count++):f.type==="remote-inbound-rtp"&&(d.packetsLost=f.packetsLost,d.rttTotal+=f.roundTripTime,d.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,_l)),clearInterval(u),a.stop(),t.remove(),yield this.disconnect(),d})}}class Jb extends Yi{get description(){return"Can publish audio"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Hb();if(yield Lf(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let o=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class Zb extends Yi{get description(){return"Can publish video"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Gb();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,5e3));const s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(r+=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return P(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise(s=>{n.onplay=()=>{setTimeout(()=>{var r,o,a,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(o=(r=d.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=d.height)!==null&&a!==void 0?a:n.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=h;const f=l.getContext("2d");f.drawImage(n,0,0);const v=f.getImageData(0,0,l.width,l.height).data;let m=!0;for(let p=0;p<v.length;p+=4)if(v[p]!==0||v[p+1]!==0||v[p+2]!==0){m=!1;break}m?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},n.play()}),t.getTracks().forEach(s=>s.stop()),n.remove()})}}class Qb extends Yi{get description(){return"Resuming connection after interruption"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,s=!1,r;const o=new Promise(l=>{setTimeout(l,5e3),r=l}),a=()=>{n=!0};t.on(ne.SignalReconnecting,a).on(ne.Reconnecting,a).on(ne.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield o,n){if(!s||t.state!==ot.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 e_ extends Yi{get description(){return"Can connect via TURN"}perform(){return P(this,void 0,void 0,function*(){var e,t,n;Ws(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new et(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new tl,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,a=!1,c=!1;for(let l of r.iceServers)for(let d of l.urls)d.startsWith("turn:")?(a=!0,c=!0):d.startsWith("turns:")&&(a=!0,c=!0,o=!0),d.startsWith("stun:")&&(c=!0);c?a&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((n=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||n===void 0)&&n.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(l=>setTimeout(l,0)))})}}class t_ extends Yi{get description(){return"Establishing WebRTC connection"}perform(){return P(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(ne.SignalConnected,()=>{var n;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,o)=>{if(r.candidate){const a=new RTCIceCandidate(r);let c="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(n_(a.address)?c+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,c+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,o)},!((n=this.room.engine.pcManager)===null||n===void 0)&&n.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),He.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function n_(i){const e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class i_ extends Yi{get description(){return"Connecting to signal connection via WebSocket"}perform(){return P(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new tl,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(o){if(Ws(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const c=yield new et(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===xh.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class DM extends Zn.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Wn.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Wn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return P(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),s=o=>{this.updateCheck(t,o)};n.on("update",s);const r=yield n.run();return n.off("update",s),r})}checkWebsocket(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(i_)})}checkWebRTC(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(t_)})}checkTURN(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(e_)})}checkReconnect(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Qb)})}checkPublishAudio(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Jb)})}checkPublishVideo(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Zb)})}checkConnectionProtocol(){return P(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Yb);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Kb)})}}function Ze(i,e,t){return(e=r_(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function s_(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function r_(i){var e=s_(i,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class un extends Error{constructor(e,t){var n;super(e,t),Ze(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(n=Error.captureStackTrace)===null||n===void 0||n.call(Error,this,this.constructor)}}Ze(un,"code","ERR_JOSE_GENERIC");class a_ extends un{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:s,payload:t}}),Ze(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Ze(this,"claim",void 0),Ze(this,"reason",void 0),Ze(this,"payload",void 0),this.claim=n,this.reason=s,this.payload=t}}Ze(a_,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class o_ extends un{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:s,payload:t}}),Ze(this,"code","ERR_JWT_EXPIRED"),Ze(this,"claim",void 0),Ze(this,"reason",void 0),Ze(this,"payload",void 0),this.claim=n,this.reason=s,this.payload=t}}Ze(o_,"code","ERR_JWT_EXPIRED");class c_ extends un{constructor(){super(...arguments),Ze(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Ze(c_,"code","ERR_JOSE_ALG_NOT_ALLOWED");class l_ extends un{constructor(){super(...arguments),Ze(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Ze(l_,"code","ERR_JOSE_NOT_SUPPORTED");class d_ extends un{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ze(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Ze(d_,"code","ERR_JWE_DECRYPTION_FAILED");class u_ extends un{constructor(){super(...arguments),Ze(this,"code","ERR_JWE_INVALID")}}Ze(u_,"code","ERR_JWE_INVALID");class h_ extends un{constructor(){super(...arguments),Ze(this,"code","ERR_JWS_INVALID")}}Ze(h_,"code","ERR_JWS_INVALID");class f_ extends un{constructor(){super(...arguments),Ze(this,"code","ERR_JWT_INVALID")}}Ze(f_,"code","ERR_JWT_INVALID");class p_ extends un{constructor(){super(...arguments),Ze(this,"code","ERR_JWK_INVALID")}}Ze(p_,"code","ERR_JWK_INVALID");class m_ extends un{constructor(){super(...arguments),Ze(this,"code","ERR_JWKS_INVALID")}}Ze(m_,"code","ERR_JWKS_INVALID");class g_ extends un{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ze(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Ze(g_,"code","ERR_JWKS_NO_MATCHING_KEY");class v_ extends un{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ze(this,Symbol.asyncIterator,void 0),Ze(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Ze(v_,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class y_ extends un{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ze(this,"code","ERR_JWKS_TIMEOUT")}}Ze(y_,"code","ERR_JWKS_TIMEOUT");class b_ extends un{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),Ze(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Ze(b_,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");class ro extends EventTarget{constructor(){super(...arguments),this.room=null,this.callStatus="idle",this.isReady=!1,this.error=null,this.microphoneEnabled=!1,this.connectedParticipants=[],this.userIdentity="",this.roomName="",this.audioPlaybackPrompt=!1}set serviceUrl(e){this._serviceUrl=e}get serviceUrl(){return this._serviceUrl??void 0}get status(){return this.callStatus}get ready(){return this.isReady}get currentError(){return this.error}get currentRoom(){return this.room}get isMicrophoneEnabled(){return this.microphoneEnabled}get participants(){return this.connectedParticipants}get identity(){return this.userIdentity}get roomNameValue(){return this.roomName}get showAudioPrompt(){return this.audioPlaybackPrompt}updateStatus(e){this.callStatus=e,this.dispatchEvent(new CustomEvent("status-changed",{detail:e}))}async makeCall({agentId:e}){if(this.room&&this.room.state==="connected")return;let t=null;try{t=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),console.log("Microphone permission granted")}catch(n){console.warn("Microphone permission denied or not available:",n)}this.updateStatus("connecting"),this.error=null,this.isReady=!1,this.room&&(await this.room.disconnect(),this.room=null);try{const n=new Ks;this.room=n,this.setupRoomEventListeners(n);const s=await fetch(`${this.serviceUrl}/create-room-token-lina`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{agent_id:e,timestamp:Date.now()}})});if(!s.ok){const l=await s.text();throw new Error(`Failed to get room token: ${s.status} ${l}`)}const{token:r,url:o,room_name:a,user_identity:c}=await s.json();this.roomName=a,this.userIdentity=c,await n.connect(o,r),this.updateStatus("connected"),this.isReady=!0,requestAnimationFrame(()=>{setTimeout(async()=>{if(t)try{await n.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")),t.getTracks().forEach(l=>l.stop()),setTimeout(()=>{const l=Array.from(n.localParticipant.audioTrackPublications.values()).find(d=>d.kind==="audio");if(l!=null&&l.track){const d=l.track.mediaStreamTrack;d&&this.dispatchEvent(new CustomEvent("local-audio-track",{detail:d}))}},100)}catch(l){console.warn("Could not enable microphone on connect:",l),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))}else this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))},50)}),this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:a,identity:c}}))}catch(n){t&&t.getTracks().forEach(s=>s.stop()),this.error=`Connection failed: ${n instanceof Error?n.message:String(n)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}setupRoomEventListeners(e){e.on(ne.Connected,()=>{this.updateStatus("connected"),this.isReady=!0}),e.on(ne.Disconnected,()=>{this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.room=null,this.isReady=!1,this.dispatchEvent(new CustomEvent("disconnected"))}),e.on(ne.ParticipantConnected,t=>{this.connectedParticipants=[...this.connectedParticipants,t.identity];const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");n&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("agent-connected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-connected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(ne.ParticipantDisconnected,t=>{this.connectedParticipants=this.connectedParticipants.filter(s=>s!==t.identity);const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");n&&(this.audioPlaybackPrompt=!1,this.updateStatus("connected"),this.dispatchEvent(new CustomEvent("agent-disconnected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-disconnected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(ne.TrackSubscribed,(t,n,s)=>{if(t.kind==="audio"){const r=t.attach();document.body.appendChild(r),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:s.identity,element:r}}));const o=t.mediaStreamTrack;o&&this.dispatchEvent(new CustomEvent("audio-track",{detail:o}))}}),e.on(ne.TrackUnsubscribed,(t,n,s)=>{t.detach(),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:s.identity}}))}),e.on(ne.MediaDevicesError,t=>{this.error=`Media device error: ${t.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),e.on(ne.AudioPlaybackStatusChanged,async()=>{e.canPlaybackAudio||this.connectedParticipants.some(n=>n.includes("agent")||n.includes("voice-assistant")||n.includes("AJ_"))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:e.canPlaybackAudio}}))})}async toggleMicrophone(){if(this.room)try{this.microphoneEnabled?(await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))):(await this.room.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")))}catch(e){this.error=`Failed to toggle microphone: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async enableAudio(){if(this.room)try{await this.room.startAudio(),this.audioPlaybackPrompt=!1;const e=JSON.stringify({type:"audio_enabled"}),n=new TextEncoder().encode(e);await this.room.localParticipant.publishData(n,{reliable:!0}),this.dispatchEvent(new CustomEvent("audio-enabled"))}catch(e){this.error=`Failed to enable audio: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async hangUp(){if(!this.room){this.error="No active connection to end.";return}this.updateStatus("disconnecting");const e=this.room;this.room=null,this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.updateStatus("disconnected"),this.dispatchEvent(new CustomEvent("call-ended")),requestAnimationFrame(()=>{setTimeout(async()=>{try{await e.disconnect()}catch(t){console.warn("Error during room disconnect:",t)}},0)})}}/**
85
85
  * @license
86
86
  * Copyright 2010-2025 Three.js Authors
87
87
  * SPDX-License-Identifier: MIT
88
- */const Sl="182",__=0,Rp=1,S_=2,ao=1,x_=2,Kr=3,_i=0,tn=1,Si=2,xi=0,Ys=1,Ji=2,Pp=3,kp=4,T_=5,gs=100,C_=101,E_=102,M_=103,w_=104,A_=200,R_=201,P_=202,k_=203,xl=204,Tl=205,I_=206,D_=207,L_=208,N_=209,O_=210,U_=211,F_=212,B_=213,z_=214,Cl=0,El=1,Ml=2,Js=3,wl=4,Al=5,Rl=6,Pl=7,Ip=0,V_=1,G_=2,ii=0,Dp=1,Lp=2,Np=3,Op=4,Up=5,Fp=6,Bp=7,zp=300,vs=301,Zs=302,kl=303,Il=304,oo=306,Dl=1e3,Ti=1001,Ll=1002,Qt=1003,H_=1004,co=1005,nn=1006,Nl=1007,ys=1008,Mn=1009,Vp=1010,Gp=1011,Yr=1012,Ol=1013,si=1014,ri=1015,Ci=1016,Ul=1017,Fl=1018,Jr=1020,Hp=35902,Wp=35899,qp=1021,jp=1022,qn=1023,Ei=1026,bs=1027,$p=1028,Bl=1029,Qs=1030,zl=1031,Vl=1033,lo=33776,uo=33777,ho=33778,fo=33779,Gl=35840,Hl=35841,Wl=35842,ql=35843,jl=36196,$l=37492,Xl=37496,Kl=37488,Yl=37489,Jl=37490,Zl=37491,Ql=37808,ed=37809,td=37810,nd=37811,id=37812,sd=37813,rd=37814,ad=37815,od=37816,cd=37817,ld=37818,dd=37819,ud=37820,hd=37821,fd=36492,pd=36494,md=36495,gd=36283,vd=36284,yd=36285,bd=36286,W_=3200,q_=0,j_=1,Zi="",Nn="srgb",er="srgb-linear",po="linear",lt="srgb",tr=7680,Xp=519,$_=512,X_=513,K_=514,_d=515,Y_=516,J_=517,Sd=518,Z_=519,Kp=35044,Yp="300 es",ai=2e3,mo=2001;function Jp(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function go(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function Q_(){const i=go("canvas");return i.style.display="block",i}const Zp={};function Qp(...i){const e="THREE."+i.shift();console.log(e,...i)}function Be(...i){const e="THREE."+i.shift();console.warn(e,...i)}function st(...i){const e="THREE."+i.shift();console.error(e,...i)}function Zr(...i){const e=i.join(" ");e in Zp||(Zp[e]=!0,Be(...i))}function eS(i,e,t){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:n()}}setTimeout(r,t)})}class nr{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const s=n[e];if(s!==void 0){const r=s.indexOf(t);r!==-1&&s.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const s=n.slice(0);for(let r=0,o=s.length;r<o;r++)s[r].call(this,e);e.target=null}}}const sn=["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"],xd=Math.PI/180,Td=180/Math.PI;function Qr(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(sn[i&255]+sn[i>>8&255]+sn[i>>16&255]+sn[i>>24&255]+"-"+sn[e&255]+sn[e>>8&255]+"-"+sn[e>>16&15|64]+sn[e>>24&255]+"-"+sn[t&63|128]+sn[t>>8&255]+"-"+sn[t>>16&255]+sn[t>>24&255]+sn[n&255]+sn[n>>8&255]+sn[n>>16&255]+sn[n>>24&255]).toLowerCase()}function Qe(i,e,t){return Math.max(e,Math.min(t,i))}function tS(i,e){return(i%e+e)%e}function Cd(i,e,t){return(1-t)*i+t*e}function ea(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function bn(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}class tt{constructor(e=0,t=0){tt.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6],this.y=s[1]*t+s[4]*n+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Qe(this.x,e.x,t.x),this.y=Qe(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Qe(this.x,e,t),this.y=Qe(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Qe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Qe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),s=Math.sin(t),r=this.x-e.x,o=this.y-e.y;return this.x=r*n-o*s+e.x,this.y=r*s+o*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ta{constructor(e=0,t=0,n=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=s}static slerpFlat(e,t,n,s,r,o,a){let c=n[s+0],l=n[s+1],d=n[s+2],u=n[s+3],h=r[o+0],f=r[o+1],g=r[o+2],v=r[o+3];if(a<=0){e[t+0]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u;return}if(a>=1){e[t+0]=h,e[t+1]=f,e[t+2]=g,e[t+3]=v;return}if(u!==v||c!==h||l!==f||d!==g){let m=c*h+l*f+d*g+u*v;m<0&&(h=-h,f=-f,g=-g,v=-v,m=-m);let p=1-a;if(m<.9995){const T=Math.acos(m),E=Math.sin(T);p=Math.sin(p*T)/E,a=Math.sin(a*T)/E,c=c*p+h*a,l=l*p+f*a,d=d*p+g*a,u=u*p+v*a}else{c=c*p+h*a,l=l*p+f*a,d=d*p+g*a,u=u*p+v*a;const T=1/Math.sqrt(c*c+l*l+d*d+u*u);c*=T,l*=T,d*=T,u*=T}}e[t]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,s,r,o){const a=n[s],c=n[s+1],l=n[s+2],d=n[s+3],u=r[o],h=r[o+1],f=r[o+2],g=r[o+3];return e[t]=a*g+d*u+c*f-l*h,e[t+1]=c*g+d*h+l*u-a*f,e[t+2]=l*g+d*f+a*h-c*u,e[t+3]=d*g-a*u-c*h-l*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,s){return this._x=e,this._y=t,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,s=e._y,r=e._z,o=e._order,a=Math.cos,c=Math.sin,l=a(n/2),d=a(s/2),u=a(r/2),h=c(n/2),f=c(s/2),g=c(r/2);switch(o){case"XYZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"YXZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"ZXY":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"ZYX":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"YZX":this._x=h*d*u+l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u-h*f*g;break;case"XZY":this._x=h*d*u-l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u+h*f*g;break;default:Be("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,s=Math.sin(n);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],s=t[4],r=t[8],o=t[1],a=t[5],c=t[9],l=t[2],d=t[6],u=t[10],h=n+a+u;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(d-c)*f,this._y=(r-l)*f,this._z=(o-s)*f}else if(n>a&&n>u){const f=2*Math.sqrt(1+n-a-u);this._w=(d-c)/f,this._x=.25*f,this._y=(s+o)/f,this._z=(r+l)/f}else if(a>u){const f=2*Math.sqrt(1+a-n-u);this._w=(r-l)/f,this._x=(s+o)/f,this._y=.25*f,this._z=(c+d)/f}else{const f=2*Math.sqrt(1+u-n-a);this._w=(o-s)/f,this._x=(r+l)/f,this._y=(c+d)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Qe(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const s=Math.min(1,t/n);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,s=e._y,r=e._z,o=e._w,a=t._x,c=t._y,l=t._z,d=t._w;return this._x=n*d+o*a+s*l-r*c,this._y=s*d+o*c+r*a-n*l,this._z=r*d+o*l+n*c-s*a,this._w=o*d-n*a-s*c-r*l,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,s=e._y,r=e._z,o=e._w,a=this.dot(e);a<0&&(n=-n,s=-s,r=-r,o=-o,a=-a);let c=1-t;if(a<.9995){const l=Math.acos(a),d=Math.sin(l);c=Math.sin(c*l)/d,t=Math.sin(t*l)/d,this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+o*t,this._onChangeCallback()}else this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+o*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(e),s*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class U{constructor(e=0,t=0,n=0){U.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(em.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(em.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*s,this.y=r[1]*t+r[4]*n+r[7]*s,this.z=r[2]*t+r[5]*n+r[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=e.elements,o=1/(r[3]*t+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*s+r[12])*o,this.y=(r[1]*t+r[5]*n+r[9]*s+r[13])*o,this.z=(r[2]*t+r[6]*n+r[10]*s+r[14])*o,this}applyQuaternion(e){const t=this.x,n=this.y,s=this.z,r=e.x,o=e.y,a=e.z,c=e.w,l=2*(o*s-a*n),d=2*(a*t-r*s),u=2*(r*n-o*t);return this.x=t+c*l+o*u-a*d,this.y=n+c*d+a*l-r*u,this.z=s+c*u+r*d-o*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*s,this.y=r[1]*t+r[5]*n+r[9]*s,this.z=r[2]*t+r[6]*n+r[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Qe(this.x,e.x,t.x),this.y=Qe(this.y,e.y,t.y),this.z=Qe(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Qe(this.x,e,t),this.y=Qe(this.y,e,t),this.z=Qe(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Qe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,s=e.y,r=e.z,o=t.x,a=t.y,c=t.z;return this.x=s*c-r*a,this.y=r*o-n*c,this.z=n*a-s*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Ed.copy(this).projectOnVector(e),this.sub(Ed)}reflect(e){return this.sub(Ed.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Qe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,s=this.z-e.z;return t*t+n*n+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const s=Math.sin(t)*e;return this.x=s*Math.sin(n),this.y=Math.cos(t)*e,this.z=s*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ed=new U,em=new ta;class We{constructor(e,t,n,s,r,o,a,c,l){We.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,o,a,c,l)}set(e,t,n,s,r,o,a,c,l){const d=this.elements;return d[0]=e,d[1]=s,d[2]=a,d[3]=t,d[4]=r,d[5]=c,d[6]=n,d[7]=o,d[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,o=n[0],a=n[3],c=n[6],l=n[1],d=n[4],u=n[7],h=n[2],f=n[5],g=n[8],v=s[0],m=s[3],p=s[6],T=s[1],E=s[4],y=s[7],S=s[2],C=s[5],w=s[8];return r[0]=o*v+a*T+c*S,r[3]=o*m+a*E+c*C,r[6]=o*p+a*y+c*w,r[1]=l*v+d*T+u*S,r[4]=l*m+d*E+u*C,r[7]=l*p+d*y+u*w,r[2]=h*v+f*T+g*S,r[5]=h*m+f*E+g*C,r[8]=h*p+f*y+g*w,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8];return t*o*d-t*a*l-n*r*d+n*a*c+s*r*l-s*o*c}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8],u=d*o-a*l,h=a*c-d*r,f=l*r-o*c,g=t*u+n*h+s*f;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return e[0]=u*v,e[1]=(s*l-d*n)*v,e[2]=(a*n-s*o)*v,e[3]=h*v,e[4]=(d*t-s*c)*v,e[5]=(s*r-a*t)*v,e[6]=f*v,e[7]=(n*c-l*t)*v,e[8]=(o*t-n*r)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,s,r,o,a){const c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*o+l*a)+o+e,-s*l,s*c,-s*(-l*o+c*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Md.makeScale(e,t)),this}rotate(e){return this.premultiply(Md.makeRotation(-e)),this}translate(e,t){return this.premultiply(Md.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<9;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Md=new We,tm=new We().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),nm=new We().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function nS(){const i={enabled:!0,workingColorSpace:er,spaces:{},convert:function(s,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===lt&&(s.r=Mi(s.r),s.g=Mi(s.g),s.b=Mi(s.b)),this.spaces[r].primaries!==this.spaces[o].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===lt&&(s.r=ir(s.r),s.g=ir(s.g),s.b=ir(s.b))),s},workingToColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},colorSpaceToWorking:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Zi?po:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,o){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,r){return Zr("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return Zr("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(s,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[er]:{primaries:e,whitePoint:n,transfer:po,toXYZ:tm,fromXYZ:nm,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Nn},outputColorSpaceConfig:{drawingBufferColorSpace:Nn}},[Nn]:{primaries:e,whitePoint:n,transfer:lt,toXYZ:tm,fromXYZ:nm,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Nn}}}),i}const nt=nS();function Mi(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function ir(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let sr;class iS{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{sr===void 0&&(sr=go("canvas")),sr.width=e.width,sr.height=e.height;const s=sr.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),n=sr}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=go("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const s=n.getImageData(0,0,e.width,e.height),r=s.data;for(let o=0;o<r.length;o++)r[o]=Mi(r[o]/255)*255;return n.putImageData(s,0,0),t}else if(e.data){const t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(Mi(t[n]/255)*255):t[n]=Mi(t[n]);return{data:t,width:e.width,height:e.height}}else return Be("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let sS=0;class wd{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:sS++}),this.uuid=Qr(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const n={uuid:this.uuid,url:""},s=this.data;if(s!==null){let r;if(Array.isArray(s)){r=[];for(let o=0,a=s.length;o<a;o++)s[o].isDataTexture?r.push(Ad(s[o].image)):r.push(Ad(s[o]))}else r=Ad(s);n.url=r}return t||(e.images[this.uuid]=n),n}}function Ad(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?iS.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(Be("Texture: Unable to serialize Texture."),{})}let rS=0;const Rd=new U;class un extends nr{constructor(e=un.DEFAULT_IMAGE,t=un.DEFAULT_MAPPING,n=Ti,s=Ti,r=nn,o=ys,a=qn,c=Mn,l=un.DEFAULT_ANISOTROPY,d=Zi){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:rS++}),this.uuid=Qr(),this.name="",this.source=new wd(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=s,this.magFilter=r,this.minFilter=o,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=c,this.offset=new tt(0,0),this.repeat=new tt(1,1),this.center=new tt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new We,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=d,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Rd).x}get height(){return this.source.getSize(Rd).y}get depth(){return this.source.getSize(Rd).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(n===void 0){Be(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Be(`Texture.setValues(): property '${t}' does not exist.`);continue}s&&n&&s.isVector2&&n.isVector2||s&&n&&s.isVector3&&n.isVector3||s&&n&&s.isMatrix3&&n.isMatrix3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==zp)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Dl:e.x=e.x-Math.floor(e.x);break;case Ti:e.x=e.x<0?0:1;break;case Ll:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Dl:e.y=e.y-Math.floor(e.y);break;case Ti:e.y=e.y<0?0:1;break;case Ll:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}un.DEFAULT_IMAGE=null,un.DEFAULT_MAPPING=zp,un.DEFAULT_ANISOTROPY=1;class Dt{constructor(e=0,t=0,n=0,s=1){Dt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,s){return this.x=e,this.y=t,this.z=n,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=this.w,o=e.elements;return this.x=o[0]*t+o[4]*n+o[8]*s+o[12]*r,this.y=o[1]*t+o[5]*n+o[9]*s+o[13]*r,this.z=o[2]*t+o[6]*n+o[10]*s+o[14]*r,this.w=o[3]*t+o[7]*n+o[11]*s+o[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,s,r;const c=e.elements,l=c[0],d=c[4],u=c[8],h=c[1],f=c[5],g=c[9],v=c[2],m=c[6],p=c[10];if(Math.abs(d-h)<.01&&Math.abs(u-v)<.01&&Math.abs(g-m)<.01){if(Math.abs(d+h)<.1&&Math.abs(u+v)<.1&&Math.abs(g+m)<.1&&Math.abs(l+f+p-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const E=(l+1)/2,y=(f+1)/2,S=(p+1)/2,C=(d+h)/4,w=(u+v)/4,k=(g+m)/4;return E>y&&E>S?E<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(E),s=C/n,r=w/n):y>S?y<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(y),n=C/s,r=k/s):S<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(S),n=w/r,s=k/r),this.set(n,s,r,t),this}let T=Math.sqrt((m-g)*(m-g)+(u-v)*(u-v)+(h-d)*(h-d));return Math.abs(T)<.001&&(T=1),this.x=(m-g)/T,this.y=(u-v)/T,this.z=(h-d)/T,this.w=Math.acos((l+f+p-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Qe(this.x,e.x,t.x),this.y=Qe(this.y,e.y,t.y),this.z=Qe(this.z,e.z,t.z),this.w=Qe(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Qe(this.x,e,t),this.y=Qe(this.y,e,t),this.z=Qe(this.z,e,t),this.w=Qe(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Qe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class aS extends nr{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:nn,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Dt(0,0,e,t),this.scissorTest=!1,this.viewport=new Dt(0,0,e,t);const s={width:e,height:t,depth:n.depth},r=new un(s);this.textures=[];const o=n.count;for(let a=0;a<o;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){const t={minFilter:nn,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let s=0,r=this.textures.length;s<r;s++)this.textures[s].image.width=e,this.textures[s].image.height=t,this.textures[s].image.depth=n,this.textures[s].isData3DTexture!==!0&&(this.textures[s].isArrayTexture=this.textures[s].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new wd(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class oi extends aS{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class im extends un{constructor(e=null,t=1,n=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=Qt,this.minFilter=Qt,this.wrapR=Ti,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class oS extends un{constructor(e=null,t=1,n=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=Qt,this.minFilter=Qt,this.wrapR=Ti,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class na{constructor(e=new U(1/0,1/0,1/0),t=new U(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(jn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(jn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=jn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(n!==void 0){const r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let o=0,a=r.count;o<a;o++)e.isMesh===!0?e.getVertexPosition(o,jn):jn.fromBufferAttribute(r,o),jn.applyMatrix4(e.matrixWorld),this.expandByPoint(jn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),vo.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),vo.copy(n.boundingBox)),vo.applyMatrix4(e.matrixWorld),this.union(vo)}const s=e.children;for(let r=0,o=s.length;r<o;r++)this.expandByObject(s[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,jn),jn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ia),yo.subVectors(this.max,ia),rr.subVectors(e.a,ia),ar.subVectors(e.b,ia),or.subVectors(e.c,ia),Qi.subVectors(ar,rr),es.subVectors(or,ar),_s.subVectors(rr,or);let t=[0,-Qi.z,Qi.y,0,-es.z,es.y,0,-_s.z,_s.y,Qi.z,0,-Qi.x,es.z,0,-es.x,_s.z,0,-_s.x,-Qi.y,Qi.x,0,-es.y,es.x,0,-_s.y,_s.x,0];return!Pd(t,rr,ar,or,yo)||(t=[1,0,0,0,1,0,0,0,1],!Pd(t,rr,ar,or,yo))?!1:(bo.crossVectors(Qi,es),t=[bo.x,bo.y,bo.z],Pd(t,rr,ar,or,yo))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,jn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(jn).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(wi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),wi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),wi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),wi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),wi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),wi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),wi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),wi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(wi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const wi=[new U,new U,new U,new U,new U,new U,new U,new U],jn=new U,vo=new na,rr=new U,ar=new U,or=new U,Qi=new U,es=new U,_s=new U,ia=new U,yo=new U,bo=new U,Ss=new U;function Pd(i,e,t,n,s){for(let r=0,o=i.length-3;r<=o;r+=3){Ss.fromArray(i,r);const a=s.x*Math.abs(Ss.x)+s.y*Math.abs(Ss.y)+s.z*Math.abs(Ss.z),c=e.dot(Ss),l=t.dot(Ss),d=n.dot(Ss);if(Math.max(-Math.max(c,l,d),Math.min(c,l,d))>a)return!1}return!0}const cS=new na,sa=new U,kd=new U;class ra{constructor(e=new U,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):cS.setFromPoints(e).getCenter(n);let s=0;for(let r=0,o=e.length;r<o;r++)s=Math.max(s,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(s),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;sa.subVectors(e,this.center);const t=sa.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),s=(n-this.radius)*.5;this.center.addScaledVector(sa,s/n),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(kd.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(sa.copy(e.center).add(kd)),this.expandByPoint(sa.copy(e.center).sub(kd))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const Ai=new U,Id=new U,_o=new U,ts=new U,Dd=new U,So=new U,Ld=new U;class Nd{constructor(e=new U,t=new U(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Ai)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Ai.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ai.copy(this.origin).addScaledVector(this.direction,t),Ai.distanceToSquared(e))}distanceSqToSegment(e,t,n,s){Id.copy(e).add(t).multiplyScalar(.5),_o.copy(t).sub(e).normalize(),ts.copy(this.origin).sub(Id);const r=e.distanceTo(t)*.5,o=-this.direction.dot(_o),a=ts.dot(this.direction),c=-ts.dot(_o),l=ts.lengthSq(),d=Math.abs(1-o*o);let u,h,f,g;if(d>0)if(u=o*c-a,h=o*a-c,g=r*d,u>=0)if(h>=-g)if(h<=g){const v=1/d;u*=v,h*=v,f=u*(u+o*h+2*a)+h*(o*u+h+2*c)+l}else h=r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;else h=-r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;else h<=-g?(u=Math.max(0,-(-o*r+a)),h=u>0?-r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l):h<=g?(u=0,h=Math.min(Math.max(-r,-c),r),f=h*(h+2*c)+l):(u=Math.max(0,-(o*r+a)),h=u>0?r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l);else h=o>0?-r:r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),s&&s.copy(Id).addScaledVector(_o,h),f}intersectSphere(e,t){Ai.subVectors(e.center,this.origin);const n=Ai.dot(this.direction),s=Ai.dot(Ai)-n*n,r=e.radius*e.radius;if(s>r)return null;const o=Math.sqrt(r-s),a=n-o,c=n+o;return c<0?null:a<0?this.at(c,t):this.at(a,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,s,r,o,a,c;const l=1/this.direction.x,d=1/this.direction.y,u=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,s=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,s=(e.min.x-h.x)*l),d>=0?(r=(e.min.y-h.y)*d,o=(e.max.y-h.y)*d):(r=(e.max.y-h.y)*d,o=(e.min.y-h.y)*d),n>o||r>s||((r>n||isNaN(n))&&(n=r),(o<s||isNaN(s))&&(s=o),u>=0?(a=(e.min.z-h.z)*u,c=(e.max.z-h.z)*u):(a=(e.max.z-h.z)*u,c=(e.min.z-h.z)*u),n>c||a>s)||((a>n||n!==n)&&(n=a),(c<s||s!==s)&&(s=c),s<0)?null:this.at(n>=0?n:s,t)}intersectsBox(e){return this.intersectBox(e,Ai)!==null}intersectTriangle(e,t,n,s,r){Dd.subVectors(t,e),So.subVectors(n,e),Ld.crossVectors(Dd,So);let o=this.direction.dot(Ld),a;if(o>0){if(s)return null;a=1}else if(o<0)a=-1,o=-o;else return null;ts.subVectors(this.origin,e);const c=a*this.direction.dot(So.crossVectors(ts,So));if(c<0)return null;const l=a*this.direction.dot(Dd.cross(ts));if(l<0||c+l>o)return null;const d=-a*ts.dot(Ld);return d<0?null:this.at(d/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class At{constructor(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m){At.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m)}set(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m){const p=this.elements;return p[0]=e,p[4]=t,p[8]=n,p[12]=s,p[1]=r,p[5]=o,p[9]=a,p[13]=c,p[2]=l,p[6]=d,p[10]=u,p[14]=h,p[3]=f,p[7]=g,p[11]=v,p[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new At().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();const t=this.elements,n=e.elements,s=1/cr.setFromMatrixColumn(e,0).length(),r=1/cr.setFromMatrixColumn(e,1).length(),o=1/cr.setFromMatrixColumn(e,2).length();return t[0]=n[0]*s,t[1]=n[1]*s,t[2]=n[2]*s,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*o,t[9]=n[9]*o,t[10]=n[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,s=e.y,r=e.z,o=Math.cos(n),a=Math.sin(n),c=Math.cos(s),l=Math.sin(s),d=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const h=o*d,f=o*u,g=a*d,v=a*u;t[0]=c*d,t[4]=-c*u,t[8]=l,t[1]=f+g*l,t[5]=h-v*l,t[9]=-a*c,t[2]=v-h*l,t[6]=g+f*l,t[10]=o*c}else if(e.order==="YXZ"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h+v*a,t[4]=g*a-f,t[8]=o*l,t[1]=o*u,t[5]=o*d,t[9]=-a,t[2]=f*a-g,t[6]=v+h*a,t[10]=o*c}else if(e.order==="ZXY"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h-v*a,t[4]=-o*u,t[8]=g+f*a,t[1]=f+g*a,t[5]=o*d,t[9]=v-h*a,t[2]=-o*l,t[6]=a,t[10]=o*c}else if(e.order==="ZYX"){const h=o*d,f=o*u,g=a*d,v=a*u;t[0]=c*d,t[4]=g*l-f,t[8]=h*l+v,t[1]=c*u,t[5]=v*l+h,t[9]=f*l-g,t[2]=-l,t[6]=a*c,t[10]=o*c}else if(e.order==="YZX"){const h=o*c,f=o*l,g=a*c,v=a*l;t[0]=c*d,t[4]=v-h*u,t[8]=g*u+f,t[1]=u,t[5]=o*d,t[9]=-a*d,t[2]=-l*d,t[6]=f*u+g,t[10]=h-v*u}else if(e.order==="XZY"){const h=o*c,f=o*l,g=a*c,v=a*l;t[0]=c*d,t[4]=-u,t[8]=l*d,t[1]=h*u+v,t[5]=o*d,t[9]=f*u-g,t[2]=g*u-f,t[6]=a*d,t[10]=v*u+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(lS,e,dS)}lookAt(e,t,n){const s=this.elements;return wn.subVectors(e,t),wn.lengthSq()===0&&(wn.z=1),wn.normalize(),ns.crossVectors(n,wn),ns.lengthSq()===0&&(Math.abs(n.z)===1?wn.x+=1e-4:wn.z+=1e-4,wn.normalize(),ns.crossVectors(n,wn)),ns.normalize(),xo.crossVectors(wn,ns),s[0]=ns.x,s[4]=xo.x,s[8]=wn.x,s[1]=ns.y,s[5]=xo.y,s[9]=wn.y,s[2]=ns.z,s[6]=xo.z,s[10]=wn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,o=n[0],a=n[4],c=n[8],l=n[12],d=n[1],u=n[5],h=n[9],f=n[13],g=n[2],v=n[6],m=n[10],p=n[14],T=n[3],E=n[7],y=n[11],S=n[15],C=s[0],w=s[4],k=s[8],_=s[12],x=s[1],R=s[5],O=s[9],F=s[13],q=s[2],K=s[6],G=s[10],W=s[14],te=s[3],ye=s[7],de=s[11],_e=s[15];return r[0]=o*C+a*x+c*q+l*te,r[4]=o*w+a*R+c*K+l*ye,r[8]=o*k+a*O+c*G+l*de,r[12]=o*_+a*F+c*W+l*_e,r[1]=d*C+u*x+h*q+f*te,r[5]=d*w+u*R+h*K+f*ye,r[9]=d*k+u*O+h*G+f*de,r[13]=d*_+u*F+h*W+f*_e,r[2]=g*C+v*x+m*q+p*te,r[6]=g*w+v*R+m*K+p*ye,r[10]=g*k+v*O+m*G+p*de,r[14]=g*_+v*F+m*W+p*_e,r[3]=T*C+E*x+y*q+S*te,r[7]=T*w+E*R+y*K+S*ye,r[11]=T*k+E*O+y*G+S*de,r[15]=T*_+E*F+y*W+S*_e,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],s=e[8],r=e[12],o=e[1],a=e[5],c=e[9],l=e[13],d=e[2],u=e[6],h=e[10],f=e[14],g=e[3],v=e[7],m=e[11],p=e[15],T=c*f-l*h,E=a*f-l*u,y=a*h-c*u,S=o*f-l*d,C=o*h-c*d,w=o*u-a*d;return t*(v*T-m*E+p*y)-n*(g*T-m*S+p*C)+s*(g*E-v*S+p*w)-r*(g*y-v*C+m*w)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8],u=e[9],h=e[10],f=e[11],g=e[12],v=e[13],m=e[14],p=e[15],T=u*m*l-v*h*l+v*c*f-a*m*f-u*c*p+a*h*p,E=g*h*l-d*m*l-g*c*f+o*m*f+d*c*p-o*h*p,y=d*v*l-g*u*l+g*a*f-o*v*f-d*a*p+o*u*p,S=g*u*c-d*v*c-g*a*h+o*v*h+d*a*m-o*u*m,C=t*T+n*E+s*y+r*S;if(C===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/C;return e[0]=T*w,e[1]=(v*h*r-u*m*r-v*s*f+n*m*f+u*s*p-n*h*p)*w,e[2]=(a*m*r-v*c*r+v*s*l-n*m*l-a*s*p+n*c*p)*w,e[3]=(u*c*r-a*h*r-u*s*l+n*h*l+a*s*f-n*c*f)*w,e[4]=E*w,e[5]=(d*m*r-g*h*r+g*s*f-t*m*f-d*s*p+t*h*p)*w,e[6]=(g*c*r-o*m*r-g*s*l+t*m*l+o*s*p-t*c*p)*w,e[7]=(o*h*r-d*c*r+d*s*l-t*h*l-o*s*f+t*c*f)*w,e[8]=y*w,e[9]=(g*u*r-d*v*r-g*n*f+t*v*f+d*n*p-t*u*p)*w,e[10]=(o*v*r-g*a*r+g*n*l-t*v*l-o*n*p+t*a*p)*w,e[11]=(d*a*r-o*u*r-d*n*l+t*u*l+o*n*f-t*a*f)*w,e[12]=S*w,e[13]=(d*v*s-g*u*s+g*n*h-t*v*h-d*n*m+t*u*m)*w,e[14]=(g*a*s-o*v*s-g*n*c+t*v*c+o*n*m-t*a*m)*w,e[15]=(o*u*s-d*a*s+d*n*c-t*u*c-o*n*h+t*a*h)*w,this}scale(e){const t=this.elements,n=e.x,s=e.y,r=e.z;return t[0]*=n,t[4]*=s,t[8]*=r,t[1]*=n,t[5]*=s,t[9]*=r,t[2]*=n,t[6]*=s,t[10]*=r,t[3]*=n,t[7]*=s,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,s))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),s=Math.sin(t),r=1-n,o=e.x,a=e.y,c=e.z,l=r*o,d=r*a;return this.set(l*o+n,l*a-s*c,l*c+s*a,0,l*a+s*c,d*a+n,d*c-s*o,0,l*c-s*a,d*c+s*o,r*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,s,r,o){return this.set(1,n,r,0,e,1,o,0,t,s,1,0,0,0,0,1),this}compose(e,t,n){const s=this.elements,r=t._x,o=t._y,a=t._z,c=t._w,l=r+r,d=o+o,u=a+a,h=r*l,f=r*d,g=r*u,v=o*d,m=o*u,p=a*u,T=c*l,E=c*d,y=c*u,S=n.x,C=n.y,w=n.z;return s[0]=(1-(v+p))*S,s[1]=(f+y)*S,s[2]=(g-E)*S,s[3]=0,s[4]=(f-y)*C,s[5]=(1-(h+p))*C,s[6]=(m+T)*C,s[7]=0,s[8]=(g+E)*w,s[9]=(m-T)*w,s[10]=(1-(h+v))*w,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,n){const s=this.elements;if(e.x=s[12],e.y=s[13],e.z=s[14],this.determinant()===0)return n.set(1,1,1),t.identity(),this;let r=cr.set(s[0],s[1],s[2]).length();const o=cr.set(s[4],s[5],s[6]).length(),a=cr.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),$n.copy(this);const l=1/r,d=1/o,u=1/a;return $n.elements[0]*=l,$n.elements[1]*=l,$n.elements[2]*=l,$n.elements[4]*=d,$n.elements[5]*=d,$n.elements[6]*=d,$n.elements[8]*=u,$n.elements[9]*=u,$n.elements[10]*=u,t.setFromRotationMatrix($n),n.x=r,n.y=o,n.z=a,this}makePerspective(e,t,n,s,r,o,a=ai,c=!1){const l=this.elements,d=2*r/(t-e),u=2*r/(n-s),h=(t+e)/(t-e),f=(n+s)/(n-s);let g,v;if(c)g=r/(o-r),v=o*r/(o-r);else if(a===ai)g=-(o+r)/(o-r),v=-2*o*r/(o-r);else if(a===mo)g=-o/(o-r),v=-o*r/(o-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=d,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,s,r,o,a=ai,c=!1){const l=this.elements,d=2/(t-e),u=2/(n-s),h=-(t+e)/(t-e),f=-(n+s)/(n-s);let g,v;if(c)g=1/(o-r),v=o/(o-r);else if(a===ai)g=-2/(o-r),v=-(o+r)/(o-r);else if(a===mo)g=-1/(o-r),v=-r/(o-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=d,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<16;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const cr=new U,$n=new At,lS=new U(0,0,0),dS=new U(1,1,1),ns=new U,xo=new U,wn=new U,sm=new At,rm=new ta;class Ri{constructor(e=0,t=0,n=0,s=Ri.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,s=this._order){return this._x=e,this._y=t,this._z=n,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const s=e.elements,r=s[0],o=s[4],a=s[8],c=s[1],l=s[5],d=s[9],u=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(Qe(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-d,f),this._z=Math.atan2(-o,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Qe(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(a,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Qe(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-Qe(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(Qe(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-d,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,f));break;case"XZY":this._z=Math.asin(-Qe(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-d,f),this._y=0);break;default:Be("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return sm.makeRotationFromQuaternion(e),this.setFromRotationMatrix(sm,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return rm.setFromEuler(this),this.setFromQuaternion(rm,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Ri.DEFAULT_ORDER="XYZ";class am{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let uS=0;const om=new U,lr=new ta,Pi=new At,To=new U,aa=new U,hS=new U,fS=new ta,cm=new U(1,0,0),lm=new U(0,1,0),dm=new U(0,0,1),um={type:"added"},pS={type:"removed"},dr={type:"childadded",child:null},Od={type:"childremoved",child:null};class Xt extends nr{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:uS++}),this.uuid=Qr(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Xt.DEFAULT_UP.clone();const e=new U,t=new Ri,n=new ta,s=new U(1,1,1);function r(){n.setFromEuler(t,!1)}function o(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new At},normalMatrix:{value:new We}}),this.matrix=new At,this.matrixWorld=new At,this.matrixAutoUpdate=Xt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Xt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new am,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return lr.setFromAxisAngle(e,t),this.quaternion.multiply(lr),this}rotateOnWorldAxis(e,t){return lr.setFromAxisAngle(e,t),this.quaternion.premultiply(lr),this}rotateX(e){return this.rotateOnAxis(cm,e)}rotateY(e){return this.rotateOnAxis(lm,e)}rotateZ(e){return this.rotateOnAxis(dm,e)}translateOnAxis(e,t){return om.copy(e).applyQuaternion(this.quaternion),this.position.add(om.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(cm,e)}translateY(e){return this.translateOnAxis(lm,e)}translateZ(e){return this.translateOnAxis(dm,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Pi.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?To.copy(e):To.set(e,t,n);const s=this.parent;this.updateWorldMatrix(!0,!1),aa.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Pi.lookAt(aa,To,this.up):Pi.lookAt(To,aa,this.up),this.quaternion.setFromRotationMatrix(Pi),s&&(Pi.extractRotation(s.matrixWorld),lr.setFromRotationMatrix(Pi),this.quaternion.premultiply(lr.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(st("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(um),dr.child=e,this.dispatchEvent(dr),dr.child=null):st("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(pS),Od.child=e,this.dispatchEvent(Od),Od.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Pi.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Pi.multiply(e.parent.matrixWorld)),e.applyMatrix4(Pi),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(um),dr.child=e,this.dispatchEvent(dr),dr.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,s=this.children.length;n<s;n++){const o=this.children[n].getObjectByProperty(e,t);if(o!==void 0)return o}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const s=this.children;for(let r=0,o=s.length;r<o;r++)s[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(aa,e,hS),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(aa,fS,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const s=this.children;for(let r=0,o=s.length;r<o;r++)s[r].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const s={};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.castShadow===!0&&(s.castShadow=!0),this.receiveShadow===!0&&(s.receiveShadow=!0),this.visible===!1&&(s.visible=!1),this.frustumCulled===!1&&(s.frustumCulled=!1),this.renderOrder!==0&&(s.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(a=>({...a})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function r(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,d=c.length;l<d;l++){const u=c[l];r(e.shapes,u)}else r(e.shapes,c)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(r(e.materials,this.material[c]));s.material=a}else s.material=r(e.materials,this.material);if(this.children.length>0){s.children=[];for(let a=0;a<this.children.length;a++)s.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){s.animations=[];for(let a=0;a<this.animations.length;a++){const c=this.animations[a];s.animations.push(r(e.animations,c))}}if(t){const a=o(e.geometries),c=o(e.materials),l=o(e.textures),d=o(e.images),u=o(e.shapes),h=o(e.skeletons),f=o(e.animations),g=o(e.nodes);a.length>0&&(n.geometries=a),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),d.length>0&&(n.images=d),u.length>0&&(n.shapes=u),h.length>0&&(n.skeletons=h),f.length>0&&(n.animations=f),g.length>0&&(n.nodes=g)}return n.object=s,n;function o(a){const c=[];for(const l in a){const d=a[l];delete d.metadata,c.push(d)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){const s=e.children[n];this.add(s.clone())}return this}}Xt.DEFAULT_UP=new U(0,1,0),Xt.DEFAULT_MATRIX_AUTO_UPDATE=!0,Xt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Xn=new U,ki=new U,Ud=new U,Ii=new U,ur=new U,hr=new U,hm=new U,Fd=new U,Bd=new U,zd=new U,Vd=new Dt,Gd=new Dt,Hd=new Dt;class Kn{constructor(e=new U,t=new U,n=new U){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,s){s.subVectors(n,t),Xn.subVectors(e,t),s.cross(Xn);const r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(e,t,n,s,r){Xn.subVectors(s,t),ki.subVectors(n,t),Ud.subVectors(e,t);const o=Xn.dot(Xn),a=Xn.dot(ki),c=Xn.dot(Ud),l=ki.dot(ki),d=ki.dot(Ud),u=o*l-a*a;if(u===0)return r.set(0,0,0),null;const h=1/u,f=(l*c-a*d)*h,g=(o*d-a*c)*h;return r.set(1-f-g,g,f)}static containsPoint(e,t,n,s){return this.getBarycoord(e,t,n,s,Ii)===null?!1:Ii.x>=0&&Ii.y>=0&&Ii.x+Ii.y<=1}static getInterpolation(e,t,n,s,r,o,a,c){return this.getBarycoord(e,t,n,s,Ii)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(r,Ii.x),c.addScaledVector(o,Ii.y),c.addScaledVector(a,Ii.z),c)}static getInterpolatedAttribute(e,t,n,s,r,o){return Vd.setScalar(0),Gd.setScalar(0),Hd.setScalar(0),Vd.fromBufferAttribute(e,t),Gd.fromBufferAttribute(e,n),Hd.fromBufferAttribute(e,s),o.setScalar(0),o.addScaledVector(Vd,r.x),o.addScaledVector(Gd,r.y),o.addScaledVector(Hd,r.z),o}static isFrontFacing(e,t,n,s){return Xn.subVectors(n,t),ki.subVectors(e,t),Xn.cross(ki).dot(s)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,s){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,n,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Xn.subVectors(this.c,this.b),ki.subVectors(this.a,this.b),Xn.cross(ki).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Kn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Kn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,s,r){return Kn.getInterpolation(e,this.a,this.b,this.c,t,n,s,r)}containsPoint(e){return Kn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Kn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,s=this.b,r=this.c;let o,a;ur.subVectors(s,n),hr.subVectors(r,n),Fd.subVectors(e,n);const c=ur.dot(Fd),l=hr.dot(Fd);if(c<=0&&l<=0)return t.copy(n);Bd.subVectors(e,s);const d=ur.dot(Bd),u=hr.dot(Bd);if(d>=0&&u<=d)return t.copy(s);const h=c*u-d*l;if(h<=0&&c>=0&&d<=0)return o=c/(c-d),t.copy(n).addScaledVector(ur,o);zd.subVectors(e,r);const f=ur.dot(zd),g=hr.dot(zd);if(g>=0&&f<=g)return t.copy(r);const v=f*l-c*g;if(v<=0&&l>=0&&g<=0)return a=l/(l-g),t.copy(n).addScaledVector(hr,a);const m=d*g-f*u;if(m<=0&&u-d>=0&&f-g>=0)return hm.subVectors(r,s),a=(u-d)/(u-d+(f-g)),t.copy(s).addScaledVector(hm,a);const p=1/(m+v+h);return o=v*p,a=h*p,t.copy(n).addScaledVector(ur,o).addScaledVector(hr,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const fm={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},is={h:0,s:0,l:0},Co={h:0,s:0,l:0};function Wd(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}class Fe{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Nn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,nt.colorSpaceToWorking(this,t),this}setRGB(e,t,n,s=nt.workingColorSpace){return this.r=e,this.g=t,this.b=n,nt.colorSpaceToWorking(this,s),this}setHSL(e,t,n,s=nt.workingColorSpace){if(e=tS(e,1),t=Qe(t,0,1),n=Qe(n,0,1),t===0)this.r=this.g=this.b=n;else{const r=n<=.5?n*(1+t):n+t-n*t,o=2*n-r;this.r=Wd(o,r,e+1/3),this.g=Wd(o,r,e),this.b=Wd(o,r,e-1/3)}return nt.colorSpaceToWorking(this,s),this}setStyle(e,t=Nn){function n(r){r!==void 0&&parseFloat(r)<1&&Be("Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const o=s[1],a=s[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Be("Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=s[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(r,16),t);Be("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Nn){const n=fm[e.toLowerCase()];return n!==void 0?this.setHex(n,t):Be("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Mi(e.r),this.g=Mi(e.g),this.b=Mi(e.b),this}copyLinearToSRGB(e){return this.r=ir(e.r),this.g=ir(e.g),this.b=ir(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Nn){return nt.workingToColorSpace(rn.copy(this),e),Math.round(Qe(rn.r*255,0,255))*65536+Math.round(Qe(rn.g*255,0,255))*256+Math.round(Qe(rn.b*255,0,255))}getHexString(e=Nn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=nt.workingColorSpace){nt.workingToColorSpace(rn.copy(this),t);const n=rn.r,s=rn.g,r=rn.b,o=Math.max(n,s,r),a=Math.min(n,s,r);let c,l;const d=(a+o)/2;if(a===o)c=0,l=0;else{const u=o-a;switch(l=d<=.5?u/(o+a):u/(2-o-a),o){case n:c=(s-r)/u+(s<r?6:0);break;case s:c=(r-n)/u+2;break;case r:c=(n-s)/u+4;break}c/=6}return e.h=c,e.s=l,e.l=d,e}getRGB(e,t=nt.workingColorSpace){return nt.workingToColorSpace(rn.copy(this),t),e.r=rn.r,e.g=rn.g,e.b=rn.b,e}getStyle(e=Nn){nt.workingToColorSpace(rn.copy(this),e);const t=rn.r,n=rn.g,s=rn.b;return e!==Nn?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(s*255)})`}offsetHSL(e,t,n){return this.getHSL(is),this.setHSL(is.h+e,is.s+t,is.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(is),e.getHSL(Co);const n=Cd(is.h,Co.h,t),s=Cd(is.s,Co.s,t),r=Cd(is.l,Co.l,t);return this.setHSL(n,s,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,s=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*s,this.g=r[1]*t+r[4]*n+r[7]*s,this.b=r[2]*t+r[5]*n+r[8]*s,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const rn=new Fe;Fe.NAMES=fm;let mS=0;class fr extends nr{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:mS++}),this.uuid=Qr(),this.name="",this.type="Material",this.blending=Ys,this.side=_i,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=xl,this.blendDst=Tl,this.blendEquation=gs,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Fe(0,0,0),this.blendAlpha=0,this.depthFunc=Js,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Xp,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=tr,this.stencilZFail=tr,this.stencilZPass=tr,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){Be(`Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Be(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==Ys&&(n.blending=this.blending),this.side!==_i&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==xl&&(n.blendSrc=this.blendSrc),this.blendDst!==Tl&&(n.blendDst=this.blendDst),this.blendEquation!==gs&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==Js&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Xp&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==tr&&(n.stencilFail=this.stencilFail),this.stencilZFail!==tr&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==tr&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){const o=[];for(const a in r){const c=r[a];delete c.metadata,o.push(c)}return o}if(t){const r=s(e.textures),o=s(e.images);r.length>0&&(n.textures=r),o.length>0&&(n.images=o)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const s=t.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class pm extends fr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Fe(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 Ri,this.combine=Ip,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const zt=new U,Eo=new tt;let gS=0;class _n{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:gS++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Kp,this.updateRanges=[],this.gpuType=ri,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let s=0,r=this.itemSize;s<r;s++)this.array[e+s]=t.array[n+s];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Eo.fromBufferAttribute(this,t),Eo.applyMatrix3(e),this.setXY(t,Eo.x,Eo.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)zt.fromBufferAttribute(this,t),zt.applyMatrix3(e),this.setXYZ(t,zt.x,zt.y,zt.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)zt.fromBufferAttribute(this,t),zt.applyMatrix4(e),this.setXYZ(t,zt.x,zt.y,zt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)zt.fromBufferAttribute(this,t),zt.applyNormalMatrix(e),this.setXYZ(t,zt.x,zt.y,zt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)zt.fromBufferAttribute(this,t),zt.transformDirection(e),this.setXYZ(t,zt.x,zt.y,zt.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=ea(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=bn(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=ea(t,this.array)),t}setX(e,t){return this.normalized&&(t=bn(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=ea(t,this.array)),t}setY(e,t){return this.normalized&&(t=bn(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=ea(t,this.array)),t}setZ(e,t){return this.normalized&&(t=bn(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=ea(t,this.array)),t}setW(e,t){return this.normalized&&(t=bn(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=bn(t,this.array),n=bn(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,s){return e*=this.itemSize,this.normalized&&(t=bn(t,this.array),n=bn(n,this.array),s=bn(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this}setXYZW(e,t,n,s,r){return e*=this.itemSize,this.normalized&&(t=bn(t,this.array),n=bn(n,this.array),s=bn(s,this.array),r=bn(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Kp&&(e.usage=this.usage),e}}class mm extends _n{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class gm extends _n{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class an extends _n{constructor(e,t,n){super(new Float32Array(e),t,n)}}let vS=0;const On=new At,qd=new Xt,pr=new U,An=new na,oa=new na,Kt=new U;class hn extends nr{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:vS++}),this.uuid=Qr(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Jp(e)?gm:mm)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const r=new We().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}const s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(e),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return On.makeRotationFromQuaternion(e),this.applyMatrix4(On),this}rotateX(e){return On.makeRotationX(e),this.applyMatrix4(On),this}rotateY(e){return On.makeRotationY(e),this.applyMatrix4(On),this}rotateZ(e){return On.makeRotationZ(e),this.applyMatrix4(On),this}translate(e,t,n){return On.makeTranslation(e,t,n),this.applyMatrix4(On),this}scale(e,t,n){return On.makeScale(e,t,n),this.applyMatrix4(On),this}lookAt(e){return qd.lookAt(e),qd.updateMatrix(),this.applyMatrix4(qd.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(pr).negate(),this.translate(pr.x,pr.y,pr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const n=[];for(let s=0,r=e.length;s<r;s++){const o=e[s];n.push(o.x,o.y,o.z||0)}this.setAttribute("position",new an(n,3))}else{const n=Math.min(e.length,t.count);for(let s=0;s<n;s++){const r=e[s];t.setXYZ(s,r.x,r.y,r.z||0)}e.length>t.count&&Be("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new na);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){st("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new U(-1/0,-1/0,-1/0),new U(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,s=t.length;n<s;n++){const r=t[n];An.setFromBufferAttribute(r),this.morphTargetsRelative?(Kt.addVectors(this.boundingBox.min,An.min),this.boundingBox.expandByPoint(Kt),Kt.addVectors(this.boundingBox.max,An.max),this.boundingBox.expandByPoint(Kt)):(this.boundingBox.expandByPoint(An.min),this.boundingBox.expandByPoint(An.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&st('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 ra);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){st("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new U,1/0);return}if(e){const n=this.boundingSphere.center;if(An.setFromBufferAttribute(e),t)for(let r=0,o=t.length;r<o;r++){const a=t[r];oa.setFromBufferAttribute(a),this.morphTargetsRelative?(Kt.addVectors(An.min,oa.min),An.expandByPoint(Kt),Kt.addVectors(An.max,oa.max),An.expandByPoint(Kt)):(An.expandByPoint(oa.min),An.expandByPoint(oa.max))}An.getCenter(n);let s=0;for(let r=0,o=e.count;r<o;r++)Kt.fromBufferAttribute(e,r),s=Math.max(s,n.distanceToSquared(Kt));if(t)for(let r=0,o=t.length;r<o;r++){const a=t[r],c=this.morphTargetsRelative;for(let l=0,d=a.count;l<d;l++)Kt.fromBufferAttribute(a,l),c&&(pr.fromBufferAttribute(e,l),Kt.add(pr)),s=Math.max(s,n.distanceToSquared(Kt))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&st('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){st("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const n=t.position,s=t.normal,r=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new _n(new Float32Array(4*n.count),4));const o=this.getAttribute("tangent"),a=[],c=[];for(let k=0;k<n.count;k++)a[k]=new U,c[k]=new U;const l=new U,d=new U,u=new U,h=new tt,f=new tt,g=new tt,v=new U,m=new U;function p(k,_,x){l.fromBufferAttribute(n,k),d.fromBufferAttribute(n,_),u.fromBufferAttribute(n,x),h.fromBufferAttribute(r,k),f.fromBufferAttribute(r,_),g.fromBufferAttribute(r,x),d.sub(l),u.sub(l),f.sub(h),g.sub(h);const R=1/(f.x*g.y-g.x*f.y);isFinite(R)&&(v.copy(d).multiplyScalar(g.y).addScaledVector(u,-f.y).multiplyScalar(R),m.copy(u).multiplyScalar(f.x).addScaledVector(d,-g.x).multiplyScalar(R),a[k].add(v),a[_].add(v),a[x].add(v),c[k].add(m),c[_].add(m),c[x].add(m))}let T=this.groups;T.length===0&&(T=[{start:0,count:e.count}]);for(let k=0,_=T.length;k<_;++k){const x=T[k],R=x.start,O=x.count;for(let F=R,q=R+O;F<q;F+=3)p(e.getX(F+0),e.getX(F+1),e.getX(F+2))}const E=new U,y=new U,S=new U,C=new U;function w(k){S.fromBufferAttribute(s,k),C.copy(S);const _=a[k];E.copy(_),E.sub(S.multiplyScalar(S.dot(_))).normalize(),y.crossVectors(C,_);const R=y.dot(c[k])<0?-1:1;o.setXYZW(k,E.x,E.y,E.z,R)}for(let k=0,_=T.length;k<_;++k){const x=T[k],R=x.start,O=x.count;for(let F=R,q=R+O;F<q;F+=3)w(e.getX(F+0)),w(e.getX(F+1)),w(e.getX(F+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new _n(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let h=0,f=n.count;h<f;h++)n.setXYZ(h,0,0,0);const s=new U,r=new U,o=new U,a=new U,c=new U,l=new U,d=new U,u=new U;if(e)for(let h=0,f=e.count;h<f;h+=3){const g=e.getX(h+0),v=e.getX(h+1),m=e.getX(h+2);s.fromBufferAttribute(t,g),r.fromBufferAttribute(t,v),o.fromBufferAttribute(t,m),d.subVectors(o,r),u.subVectors(s,r),d.cross(u),a.fromBufferAttribute(n,g),c.fromBufferAttribute(n,v),l.fromBufferAttribute(n,m),a.add(d),c.add(d),l.add(d),n.setXYZ(g,a.x,a.y,a.z),n.setXYZ(v,c.x,c.y,c.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let h=0,f=t.count;h<f;h+=3)s.fromBufferAttribute(t,h+0),r.fromBufferAttribute(t,h+1),o.fromBufferAttribute(t,h+2),d.subVectors(o,r),u.subVectors(s,r),d.cross(u),n.setXYZ(h+0,d.x,d.y,d.z),n.setXYZ(h+1,d.x,d.y,d.z),n.setXYZ(h+2,d.x,d.y,d.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Kt.fromBufferAttribute(e,t),Kt.normalize(),e.setXYZ(t,Kt.x,Kt.y,Kt.z)}toNonIndexed(){function e(a,c){const l=a.array,d=a.itemSize,u=a.normalized,h=new l.constructor(c.length*d);let f=0,g=0;for(let v=0,m=c.length;v<m;v++){a.isInterleavedBufferAttribute?f=c[v]*a.data.stride+a.offset:f=c[v]*d;for(let p=0;p<d;p++)h[g++]=l[f++]}return new _n(h,d,u)}if(this.index===null)return Be("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new hn,n=this.index.array,s=this.attributes;for(const a in s){const c=s[a],l=e(c,n);t.setAttribute(a,l)}const r=this.morphAttributes;for(const a in r){const c=[],l=r[a];for(let d=0,u=l.length;d<u;d++){const h=l[d],f=e(h,n);c.push(f)}t.morphAttributes[a]=c}t.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let a=0,c=o.length;a<c;a++){const l=o[a];t.addGroup(l.start,l.count,l.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const l=n[c];e.data.attributes[c]=l.toJSON(e.data)}const s={};let r=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],d=[];for(let u=0,h=l.length;u<h;u++){const f=l[u];d.push(f.toJSON(e.data))}d.length>0&&(s[c]=d,r=!0)}r&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere=a.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone());const s=e.attributes;for(const l in s){const d=s[l];this.setAttribute(l,d.clone(t))}const r=e.morphAttributes;for(const l in r){const d=[],u=r[l];for(let h=0,f=u.length;h<f;h++)d.push(u[h].clone(t));this.morphAttributes[l]=d}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let l=0,d=o.length;l<d;l++){const u=o[l];this.addGroup(u.start,u.count,u.materialIndex)}const a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const vm=new At,xs=new Nd,Mo=new ra,ym=new U,wo=new U,Ao=new U,Ro=new U,jd=new U,Po=new U,bm=new U,ko=new U;class Sn extends Xt{constructor(e=new hn,t=new pm){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r<o;r++){const a=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}getVertexPosition(e,t){const n=this.geometry,s=n.attributes.position,r=n.morphAttributes.position,o=n.morphTargetsRelative;t.fromBufferAttribute(s,e);const a=this.morphTargetInfluences;if(r&&a){Po.set(0,0,0);for(let c=0,l=r.length;c<l;c++){const d=a[c],u=r[c];d!==0&&(jd.fromBufferAttribute(u,e),o?Po.addScaledVector(jd,d):Po.addScaledVector(jd.sub(t),d))}t.add(Po)}return t}raycast(e,t){const n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Mo.copy(n.boundingSphere),Mo.applyMatrix4(r),xs.copy(e.ray).recast(e.near),!(Mo.containsPoint(xs.origin)===!1&&(xs.intersectSphere(Mo,ym)===null||xs.origin.distanceToSquared(ym)>(e.far-e.near)**2))&&(vm.copy(r).invert(),xs.copy(e.ray).applyMatrix4(vm),!(n.boundingBox!==null&&xs.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,xs)))}_computeIntersections(e,t,n){let s;const r=this.geometry,o=this.material,a=r.index,c=r.attributes.position,l=r.attributes.uv,d=r.attributes.uv1,u=r.attributes.normal,h=r.groups,f=r.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=o[m.materialIndex],T=Math.max(m.start,f.start),E=Math.min(a.count,Math.min(m.start+m.count,f.start+f.count));for(let y=T,S=E;y<S;y+=3){const C=a.getX(y),w=a.getX(y+1),k=a.getX(y+2);s=Io(this,p,e,n,l,d,u,C,w,k),s&&(s.faceIndex=Math.floor(y/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(a.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const T=a.getX(m),E=a.getX(m+1),y=a.getX(m+2);s=Io(this,o,e,n,l,d,u,T,E,y),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}else if(c!==void 0)if(Array.isArray(o))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=o[m.materialIndex],T=Math.max(m.start,f.start),E=Math.min(c.count,Math.min(m.start+m.count,f.start+f.count));for(let y=T,S=E;y<S;y+=3){const C=y,w=y+1,k=y+2;s=Io(this,p,e,n,l,d,u,C,w,k),s&&(s.faceIndex=Math.floor(y/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(c.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const T=m,E=m+1,y=m+2;s=Io(this,o,e,n,l,d,u,T,E,y),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}}}function yS(i,e,t,n,s,r,o,a){let c;if(e.side===tn?c=n.intersectTriangle(o,r,s,!0,a):c=n.intersectTriangle(s,r,o,e.side===_i,a),c===null)return null;ko.copy(a),ko.applyMatrix4(i.matrixWorld);const l=t.ray.origin.distanceTo(ko);return l<t.near||l>t.far?null:{distance:l,point:ko.clone(),object:i}}function Io(i,e,t,n,s,r,o,a,c,l){i.getVertexPosition(a,wo),i.getVertexPosition(c,Ao),i.getVertexPosition(l,Ro);const d=yS(i,e,t,n,wo,Ao,Ro,bm);if(d){const u=new U;Kn.getBarycoord(bm,wo,Ao,Ro,u),s&&(d.uv=Kn.getInterpolatedAttribute(s,a,c,l,u,new tt)),r&&(d.uv1=Kn.getInterpolatedAttribute(r,a,c,l,u,new tt)),o&&(d.normal=Kn.getInterpolatedAttribute(o,a,c,l,u,new U),d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1));const h={a,b:c,c:l,normal:new U,materialIndex:0};Kn.getNormal(wo,Ao,Ro,h.normal),d.face=h,d.barycoord=u}return d}class ca extends hn{constructor(e=1,t=1,n=1,s=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:s,heightSegments:r,depthSegments:o};const a=this;s=Math.floor(s),r=Math.floor(r),o=Math.floor(o);const c=[],l=[],d=[],u=[];let h=0,f=0;g("z","y","x",-1,-1,n,t,e,o,r,0),g("z","y","x",1,-1,n,t,-e,o,r,1),g("x","z","y",1,1,e,n,t,s,o,2),g("x","z","y",1,-1,e,n,-t,s,o,3),g("x","y","z",1,-1,e,t,n,s,r,4),g("x","y","z",-1,-1,e,t,-n,s,r,5),this.setIndex(c),this.setAttribute("position",new an(l,3)),this.setAttribute("normal",new an(d,3)),this.setAttribute("uv",new an(u,2));function g(v,m,p,T,E,y,S,C,w,k,_){const x=y/w,R=S/k,O=y/2,F=S/2,q=C/2,K=w+1,G=k+1;let W=0,te=0;const ye=new U;for(let de=0;de<G;de++){const _e=de*R-F;for(let Ge=0;Ge<K;Ge++){const Ve=Ge*x-O;ye[v]=Ve*T,ye[m]=_e*E,ye[p]=q,l.push(ye.x,ye.y,ye.z),ye[v]=0,ye[m]=0,ye[p]=C>0?1:-1,d.push(ye.x,ye.y,ye.z),u.push(Ge/w),u.push(1-de/k),W+=1}}for(let de=0;de<k;de++)for(let _e=0;_e<w;_e++){const Ge=h+_e+K*de,Ve=h+_e+K*(de+1),Mt=h+(_e+1)+K*(de+1),pt=h+(_e+1)+K*de;c.push(Ge,Ve,pt),c.push(Ve,Mt,pt),te+=6}a.addGroup(f,te,_),f+=te,h+=W}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ca(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function mr(i){const e={};for(const t in i){e[t]={};for(const n in i[t]){const s=i[t][n];s&&(s.isColor||s.isMatrix3||s.isMatrix4||s.isVector2||s.isVector3||s.isVector4||s.isTexture||s.isQuaternion)?s.isRenderTargetTexture?(Be("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=s.clone():Array.isArray(s)?e[t][n]=s.slice():e[t][n]=s}}return e}function fn(i){const e={};for(let t=0;t<i.length;t++){const n=mr(i[t]);for(const s in n)e[s]=n[s]}return e}function bS(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function _m(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:nt.workingColorSpace}const _S={clone:mr,merge:fn};var SS=`void main() {
88
+ */const Sl="182",__=0,Rp=1,S_=2,ao=1,x_=2,Kr=3,_i=0,nn=1,Si=2,xi=0,Ys=1,Ji=2,Pp=3,kp=4,T_=5,gs=100,C_=101,E_=102,M_=103,w_=104,A_=200,R_=201,P_=202,k_=203,xl=204,Tl=205,I_=206,D_=207,L_=208,N_=209,O_=210,U_=211,F_=212,B_=213,z_=214,Cl=0,El=1,Ml=2,Js=3,wl=4,Al=5,Rl=6,Pl=7,Ip=0,V_=1,G_=2,ii=0,Dp=1,Lp=2,Np=3,Op=4,Up=5,Fp=6,Bp=7,zp=300,vs=301,Zs=302,kl=303,Il=304,oo=306,Dl=1e3,Ti=1001,Ll=1002,en=1003,H_=1004,co=1005,sn=1006,Nl=1007,ys=1008,wn=1009,Vp=1010,Gp=1011,Yr=1012,Ol=1013,si=1014,ri=1015,Ci=1016,Ul=1017,Fl=1018,Jr=1020,Hp=35902,Wp=35899,qp=1021,jp=1022,qn=1023,Ei=1026,bs=1027,$p=1028,Bl=1029,Qs=1030,zl=1031,Vl=1033,lo=33776,uo=33777,ho=33778,fo=33779,Gl=35840,Hl=35841,Wl=35842,ql=35843,jl=36196,$l=37492,Xl=37496,Kl=37488,Yl=37489,Jl=37490,Zl=37491,Ql=37808,ed=37809,td=37810,nd=37811,id=37812,sd=37813,rd=37814,ad=37815,od=37816,cd=37817,ld=37818,dd=37819,ud=37820,hd=37821,fd=36492,pd=36494,md=36495,gd=36283,vd=36284,yd=36285,bd=36286,W_=3200,q_=0,j_=1,Zi="",Nn="srgb",er="srgb-linear",po="linear",lt="srgb",tr=7680,Xp=519,$_=512,X_=513,K_=514,_d=515,Y_=516,J_=517,Sd=518,Z_=519,Kp=35044,Yp="300 es",ai=2e3,mo=2001;function Jp(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function go(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function Q_(){const i=go("canvas");return i.style.display="block",i}const Zp={};function Qp(...i){const e="THREE."+i.shift();console.log(e,...i)}function Be(...i){const e="THREE."+i.shift();console.warn(e,...i)}function st(...i){const e="THREE."+i.shift();console.error(e,...i)}function Zr(...i){const e=i.join(" ");e in Zp||(Zp[e]=!0,Be(...i))}function eS(i,e,t){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:n()}}setTimeout(r,t)})}class nr{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const s=n[e];if(s!==void 0){const r=s.indexOf(t);r!==-1&&s.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const s=n.slice(0);for(let r=0,o=s.length;r<o;r++)s[r].call(this,e);e.target=null}}}const rn=["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"],xd=Math.PI/180,Td=180/Math.PI;function Qr(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(rn[i&255]+rn[i>>8&255]+rn[i>>16&255]+rn[i>>24&255]+"-"+rn[e&255]+rn[e>>8&255]+"-"+rn[e>>16&15|64]+rn[e>>24&255]+"-"+rn[t&63|128]+rn[t>>8&255]+"-"+rn[t>>16&255]+rn[t>>24&255]+rn[n&255]+rn[n>>8&255]+rn[n>>16&255]+rn[n>>24&255]).toLowerCase()}function Qe(i,e,t){return Math.max(e,Math.min(t,i))}function tS(i,e){return(i%e+e)%e}function Cd(i,e,t){return(1-t)*i+t*e}function ea(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function _n(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}class tt{constructor(e=0,t=0){tt.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6],this.y=s[1]*t+s[4]*n+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Qe(this.x,e.x,t.x),this.y=Qe(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Qe(this.x,e,t),this.y=Qe(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Qe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Qe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),s=Math.sin(t),r=this.x-e.x,o=this.y-e.y;return this.x=r*n-o*s+e.x,this.y=r*s+o*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ta{constructor(e=0,t=0,n=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=s}static slerpFlat(e,t,n,s,r,o,a){let c=n[s+0],l=n[s+1],d=n[s+2],u=n[s+3],h=r[o+0],f=r[o+1],g=r[o+2],v=r[o+3];if(a<=0){e[t+0]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u;return}if(a>=1){e[t+0]=h,e[t+1]=f,e[t+2]=g,e[t+3]=v;return}if(u!==v||c!==h||l!==f||d!==g){let m=c*h+l*f+d*g+u*v;m<0&&(h=-h,f=-f,g=-g,v=-v,m=-m);let p=1-a;if(m<.9995){const T=Math.acos(m),E=Math.sin(T);p=Math.sin(p*T)/E,a=Math.sin(a*T)/E,c=c*p+h*a,l=l*p+f*a,d=d*p+g*a,u=u*p+v*a}else{c=c*p+h*a,l=l*p+f*a,d=d*p+g*a,u=u*p+v*a;const T=1/Math.sqrt(c*c+l*l+d*d+u*u);c*=T,l*=T,d*=T,u*=T}}e[t]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,s,r,o){const a=n[s],c=n[s+1],l=n[s+2],d=n[s+3],u=r[o],h=r[o+1],f=r[o+2],g=r[o+3];return e[t]=a*g+d*u+c*f-l*h,e[t+1]=c*g+d*h+l*u-a*f,e[t+2]=l*g+d*f+a*h-c*u,e[t+3]=d*g-a*u-c*h-l*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,s){return this._x=e,this._y=t,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,s=e._y,r=e._z,o=e._order,a=Math.cos,c=Math.sin,l=a(n/2),d=a(s/2),u=a(r/2),h=c(n/2),f=c(s/2),g=c(r/2);switch(o){case"XYZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"YXZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"ZXY":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"ZYX":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"YZX":this._x=h*d*u+l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u-h*f*g;break;case"XZY":this._x=h*d*u-l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u+h*f*g;break;default:Be("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,s=Math.sin(n);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],s=t[4],r=t[8],o=t[1],a=t[5],c=t[9],l=t[2],d=t[6],u=t[10],h=n+a+u;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(d-c)*f,this._y=(r-l)*f,this._z=(o-s)*f}else if(n>a&&n>u){const f=2*Math.sqrt(1+n-a-u);this._w=(d-c)/f,this._x=.25*f,this._y=(s+o)/f,this._z=(r+l)/f}else if(a>u){const f=2*Math.sqrt(1+a-n-u);this._w=(r-l)/f,this._x=(s+o)/f,this._y=.25*f,this._z=(c+d)/f}else{const f=2*Math.sqrt(1+u-n-a);this._w=(o-s)/f,this._x=(r+l)/f,this._y=(c+d)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Qe(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const s=Math.min(1,t/n);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,s=e._y,r=e._z,o=e._w,a=t._x,c=t._y,l=t._z,d=t._w;return this._x=n*d+o*a+s*l-r*c,this._y=s*d+o*c+r*a-n*l,this._z=r*d+o*l+n*c-s*a,this._w=o*d-n*a-s*c-r*l,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,s=e._y,r=e._z,o=e._w,a=this.dot(e);a<0&&(n=-n,s=-s,r=-r,o=-o,a=-a);let c=1-t;if(a<.9995){const l=Math.acos(a),d=Math.sin(l);c=Math.sin(c*l)/d,t=Math.sin(t*l)/d,this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+o*t,this._onChangeCallback()}else this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+o*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(e),s*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class U{constructor(e=0,t=0,n=0){U.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(em.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(em.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*s,this.y=r[1]*t+r[4]*n+r[7]*s,this.z=r[2]*t+r[5]*n+r[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=e.elements,o=1/(r[3]*t+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*s+r[12])*o,this.y=(r[1]*t+r[5]*n+r[9]*s+r[13])*o,this.z=(r[2]*t+r[6]*n+r[10]*s+r[14])*o,this}applyQuaternion(e){const t=this.x,n=this.y,s=this.z,r=e.x,o=e.y,a=e.z,c=e.w,l=2*(o*s-a*n),d=2*(a*t-r*s),u=2*(r*n-o*t);return this.x=t+c*l+o*u-a*d,this.y=n+c*d+a*l-r*u,this.z=s+c*u+r*d-o*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*s,this.y=r[1]*t+r[5]*n+r[9]*s,this.z=r[2]*t+r[6]*n+r[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Qe(this.x,e.x,t.x),this.y=Qe(this.y,e.y,t.y),this.z=Qe(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Qe(this.x,e,t),this.y=Qe(this.y,e,t),this.z=Qe(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Qe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,s=e.y,r=e.z,o=t.x,a=t.y,c=t.z;return this.x=s*c-r*a,this.y=r*o-n*c,this.z=n*a-s*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Ed.copy(this).projectOnVector(e),this.sub(Ed)}reflect(e){return this.sub(Ed.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Qe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,s=this.z-e.z;return t*t+n*n+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const s=Math.sin(t)*e;return this.x=s*Math.sin(n),this.y=Math.cos(t)*e,this.z=s*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ed=new U,em=new ta;class We{constructor(e,t,n,s,r,o,a,c,l){We.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,o,a,c,l)}set(e,t,n,s,r,o,a,c,l){const d=this.elements;return d[0]=e,d[1]=s,d[2]=a,d[3]=t,d[4]=r,d[5]=c,d[6]=n,d[7]=o,d[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,o=n[0],a=n[3],c=n[6],l=n[1],d=n[4],u=n[7],h=n[2],f=n[5],g=n[8],v=s[0],m=s[3],p=s[6],T=s[1],E=s[4],y=s[7],S=s[2],C=s[5],w=s[8];return r[0]=o*v+a*T+c*S,r[3]=o*m+a*E+c*C,r[6]=o*p+a*y+c*w,r[1]=l*v+d*T+u*S,r[4]=l*m+d*E+u*C,r[7]=l*p+d*y+u*w,r[2]=h*v+f*T+g*S,r[5]=h*m+f*E+g*C,r[8]=h*p+f*y+g*w,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8];return t*o*d-t*a*l-n*r*d+n*a*c+s*r*l-s*o*c}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8],u=d*o-a*l,h=a*c-d*r,f=l*r-o*c,g=t*u+n*h+s*f;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return e[0]=u*v,e[1]=(s*l-d*n)*v,e[2]=(a*n-s*o)*v,e[3]=h*v,e[4]=(d*t-s*c)*v,e[5]=(s*r-a*t)*v,e[6]=f*v,e[7]=(n*c-l*t)*v,e[8]=(o*t-n*r)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,s,r,o,a){const c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*o+l*a)+o+e,-s*l,s*c,-s*(-l*o+c*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Md.makeScale(e,t)),this}rotate(e){return this.premultiply(Md.makeRotation(-e)),this}translate(e,t){return this.premultiply(Md.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<9;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Md=new We,tm=new We().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),nm=new We().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function nS(){const i={enabled:!0,workingColorSpace:er,spaces:{},convert:function(s,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===lt&&(s.r=Mi(s.r),s.g=Mi(s.g),s.b=Mi(s.b)),this.spaces[r].primaries!==this.spaces[o].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===lt&&(s.r=ir(s.r),s.g=ir(s.g),s.b=ir(s.b))),s},workingToColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},colorSpaceToWorking:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Zi?po:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,o){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,r){return Zr("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return Zr("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(s,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[er]:{primaries:e,whitePoint:n,transfer:po,toXYZ:tm,fromXYZ:nm,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Nn},outputColorSpaceConfig:{drawingBufferColorSpace:Nn}},[Nn]:{primaries:e,whitePoint:n,transfer:lt,toXYZ:tm,fromXYZ:nm,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Nn}}}),i}const nt=nS();function Mi(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function ir(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let sr;class iS{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{sr===void 0&&(sr=go("canvas")),sr.width=e.width,sr.height=e.height;const s=sr.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),n=sr}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=go("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const s=n.getImageData(0,0,e.width,e.height),r=s.data;for(let o=0;o<r.length;o++)r[o]=Mi(r[o]/255)*255;return n.putImageData(s,0,0),t}else if(e.data){const t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(Mi(t[n]/255)*255):t[n]=Mi(t[n]);return{data:t,width:e.width,height:e.height}}else return Be("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let sS=0;class wd{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:sS++}),this.uuid=Qr(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const n={uuid:this.uuid,url:""},s=this.data;if(s!==null){let r;if(Array.isArray(s)){r=[];for(let o=0,a=s.length;o<a;o++)s[o].isDataTexture?r.push(Ad(s[o].image)):r.push(Ad(s[o]))}else r=Ad(s);n.url=r}return t||(e.images[this.uuid]=n),n}}function Ad(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?iS.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(Be("Texture: Unable to serialize Texture."),{})}let rS=0;const Rd=new U;class hn extends nr{constructor(e=hn.DEFAULT_IMAGE,t=hn.DEFAULT_MAPPING,n=Ti,s=Ti,r=sn,o=ys,a=qn,c=wn,l=hn.DEFAULT_ANISOTROPY,d=Zi){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:rS++}),this.uuid=Qr(),this.name="",this.source=new wd(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=s,this.magFilter=r,this.minFilter=o,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=c,this.offset=new tt(0,0),this.repeat=new tt(1,1),this.center=new tt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new We,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=d,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Rd).x}get height(){return this.source.getSize(Rd).y}get depth(){return this.source.getSize(Rd).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(n===void 0){Be(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Be(`Texture.setValues(): property '${t}' does not exist.`);continue}s&&n&&s.isVector2&&n.isVector2||s&&n&&s.isVector3&&n.isVector3||s&&n&&s.isMatrix3&&n.isMatrix3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==zp)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Dl:e.x=e.x-Math.floor(e.x);break;case Ti:e.x=e.x<0?0:1;break;case Ll:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Dl:e.y=e.y-Math.floor(e.y);break;case Ti:e.y=e.y<0?0:1;break;case Ll:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}hn.DEFAULT_IMAGE=null,hn.DEFAULT_MAPPING=zp,hn.DEFAULT_ANISOTROPY=1;class Dt{constructor(e=0,t=0,n=0,s=1){Dt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,s){return this.x=e,this.y=t,this.z=n,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=this.w,o=e.elements;return this.x=o[0]*t+o[4]*n+o[8]*s+o[12]*r,this.y=o[1]*t+o[5]*n+o[9]*s+o[13]*r,this.z=o[2]*t+o[6]*n+o[10]*s+o[14]*r,this.w=o[3]*t+o[7]*n+o[11]*s+o[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,s,r;const c=e.elements,l=c[0],d=c[4],u=c[8],h=c[1],f=c[5],g=c[9],v=c[2],m=c[6],p=c[10];if(Math.abs(d-h)<.01&&Math.abs(u-v)<.01&&Math.abs(g-m)<.01){if(Math.abs(d+h)<.1&&Math.abs(u+v)<.1&&Math.abs(g+m)<.1&&Math.abs(l+f+p-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const E=(l+1)/2,y=(f+1)/2,S=(p+1)/2,C=(d+h)/4,w=(u+v)/4,k=(g+m)/4;return E>y&&E>S?E<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(E),s=C/n,r=w/n):y>S?y<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(y),n=C/s,r=k/s):S<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(S),n=w/r,s=k/r),this.set(n,s,r,t),this}let T=Math.sqrt((m-g)*(m-g)+(u-v)*(u-v)+(h-d)*(h-d));return Math.abs(T)<.001&&(T=1),this.x=(m-g)/T,this.y=(u-v)/T,this.z=(h-d)/T,this.w=Math.acos((l+f+p-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Qe(this.x,e.x,t.x),this.y=Qe(this.y,e.y,t.y),this.z=Qe(this.z,e.z,t.z),this.w=Qe(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Qe(this.x,e,t),this.y=Qe(this.y,e,t),this.z=Qe(this.z,e,t),this.w=Qe(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Qe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class aS extends nr{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:sn,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Dt(0,0,e,t),this.scissorTest=!1,this.viewport=new Dt(0,0,e,t);const s={width:e,height:t,depth:n.depth},r=new hn(s);this.textures=[];const o=n.count;for(let a=0;a<o;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){const t={minFilter:sn,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let s=0,r=this.textures.length;s<r;s++)this.textures[s].image.width=e,this.textures[s].image.height=t,this.textures[s].image.depth=n,this.textures[s].isData3DTexture!==!0&&(this.textures[s].isArrayTexture=this.textures[s].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new wd(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class oi extends aS{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class im extends hn{constructor(e=null,t=1,n=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=en,this.minFilter=en,this.wrapR=Ti,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class oS extends hn{constructor(e=null,t=1,n=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=en,this.minFilter=en,this.wrapR=Ti,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class na{constructor(e=new U(1/0,1/0,1/0),t=new U(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(jn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(jn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=jn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(n!==void 0){const r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let o=0,a=r.count;o<a;o++)e.isMesh===!0?e.getVertexPosition(o,jn):jn.fromBufferAttribute(r,o),jn.applyMatrix4(e.matrixWorld),this.expandByPoint(jn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),vo.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),vo.copy(n.boundingBox)),vo.applyMatrix4(e.matrixWorld),this.union(vo)}const s=e.children;for(let r=0,o=s.length;r<o;r++)this.expandByObject(s[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,jn),jn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ia),yo.subVectors(this.max,ia),rr.subVectors(e.a,ia),ar.subVectors(e.b,ia),or.subVectors(e.c,ia),Qi.subVectors(ar,rr),es.subVectors(or,ar),_s.subVectors(rr,or);let t=[0,-Qi.z,Qi.y,0,-es.z,es.y,0,-_s.z,_s.y,Qi.z,0,-Qi.x,es.z,0,-es.x,_s.z,0,-_s.x,-Qi.y,Qi.x,0,-es.y,es.x,0,-_s.y,_s.x,0];return!Pd(t,rr,ar,or,yo)||(t=[1,0,0,0,1,0,0,0,1],!Pd(t,rr,ar,or,yo))?!1:(bo.crossVectors(Qi,es),t=[bo.x,bo.y,bo.z],Pd(t,rr,ar,or,yo))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,jn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(jn).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(wi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),wi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),wi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),wi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),wi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),wi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),wi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),wi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(wi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const wi=[new U,new U,new U,new U,new U,new U,new U,new U],jn=new U,vo=new na,rr=new U,ar=new U,or=new U,Qi=new U,es=new U,_s=new U,ia=new U,yo=new U,bo=new U,Ss=new U;function Pd(i,e,t,n,s){for(let r=0,o=i.length-3;r<=o;r+=3){Ss.fromArray(i,r);const a=s.x*Math.abs(Ss.x)+s.y*Math.abs(Ss.y)+s.z*Math.abs(Ss.z),c=e.dot(Ss),l=t.dot(Ss),d=n.dot(Ss);if(Math.max(-Math.max(c,l,d),Math.min(c,l,d))>a)return!1}return!0}const cS=new na,sa=new U,kd=new U;class ra{constructor(e=new U,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):cS.setFromPoints(e).getCenter(n);let s=0;for(let r=0,o=e.length;r<o;r++)s=Math.max(s,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(s),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;sa.subVectors(e,this.center);const t=sa.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),s=(n-this.radius)*.5;this.center.addScaledVector(sa,s/n),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(kd.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(sa.copy(e.center).add(kd)),this.expandByPoint(sa.copy(e.center).sub(kd))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const Ai=new U,Id=new U,_o=new U,ts=new U,Dd=new U,So=new U,Ld=new U;class Nd{constructor(e=new U,t=new U(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Ai)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Ai.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ai.copy(this.origin).addScaledVector(this.direction,t),Ai.distanceToSquared(e))}distanceSqToSegment(e,t,n,s){Id.copy(e).add(t).multiplyScalar(.5),_o.copy(t).sub(e).normalize(),ts.copy(this.origin).sub(Id);const r=e.distanceTo(t)*.5,o=-this.direction.dot(_o),a=ts.dot(this.direction),c=-ts.dot(_o),l=ts.lengthSq(),d=Math.abs(1-o*o);let u,h,f,g;if(d>0)if(u=o*c-a,h=o*a-c,g=r*d,u>=0)if(h>=-g)if(h<=g){const v=1/d;u*=v,h*=v,f=u*(u+o*h+2*a)+h*(o*u+h+2*c)+l}else h=r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;else h=-r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;else h<=-g?(u=Math.max(0,-(-o*r+a)),h=u>0?-r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l):h<=g?(u=0,h=Math.min(Math.max(-r,-c),r),f=h*(h+2*c)+l):(u=Math.max(0,-(o*r+a)),h=u>0?r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l);else h=o>0?-r:r,u=Math.max(0,-(o*h+a)),f=-u*u+h*(h+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),s&&s.copy(Id).addScaledVector(_o,h),f}intersectSphere(e,t){Ai.subVectors(e.center,this.origin);const n=Ai.dot(this.direction),s=Ai.dot(Ai)-n*n,r=e.radius*e.radius;if(s>r)return null;const o=Math.sqrt(r-s),a=n-o,c=n+o;return c<0?null:a<0?this.at(c,t):this.at(a,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,s,r,o,a,c;const l=1/this.direction.x,d=1/this.direction.y,u=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,s=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,s=(e.min.x-h.x)*l),d>=0?(r=(e.min.y-h.y)*d,o=(e.max.y-h.y)*d):(r=(e.max.y-h.y)*d,o=(e.min.y-h.y)*d),n>o||r>s||((r>n||isNaN(n))&&(n=r),(o<s||isNaN(s))&&(s=o),u>=0?(a=(e.min.z-h.z)*u,c=(e.max.z-h.z)*u):(a=(e.max.z-h.z)*u,c=(e.min.z-h.z)*u),n>c||a>s)||((a>n||n!==n)&&(n=a),(c<s||s!==s)&&(s=c),s<0)?null:this.at(n>=0?n:s,t)}intersectsBox(e){return this.intersectBox(e,Ai)!==null}intersectTriangle(e,t,n,s,r){Dd.subVectors(t,e),So.subVectors(n,e),Ld.crossVectors(Dd,So);let o=this.direction.dot(Ld),a;if(o>0){if(s)return null;a=1}else if(o<0)a=-1,o=-o;else return null;ts.subVectors(this.origin,e);const c=a*this.direction.dot(So.crossVectors(ts,So));if(c<0)return null;const l=a*this.direction.dot(Dd.cross(ts));if(l<0||c+l>o)return null;const d=-a*ts.dot(Ld);return d<0?null:this.at(d/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class At{constructor(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m){At.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m)}set(e,t,n,s,r,o,a,c,l,d,u,h,f,g,v,m){const p=this.elements;return p[0]=e,p[4]=t,p[8]=n,p[12]=s,p[1]=r,p[5]=o,p[9]=a,p[13]=c,p[2]=l,p[6]=d,p[10]=u,p[14]=h,p[3]=f,p[7]=g,p[11]=v,p[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new At().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();const t=this.elements,n=e.elements,s=1/cr.setFromMatrixColumn(e,0).length(),r=1/cr.setFromMatrixColumn(e,1).length(),o=1/cr.setFromMatrixColumn(e,2).length();return t[0]=n[0]*s,t[1]=n[1]*s,t[2]=n[2]*s,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*o,t[9]=n[9]*o,t[10]=n[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,s=e.y,r=e.z,o=Math.cos(n),a=Math.sin(n),c=Math.cos(s),l=Math.sin(s),d=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const h=o*d,f=o*u,g=a*d,v=a*u;t[0]=c*d,t[4]=-c*u,t[8]=l,t[1]=f+g*l,t[5]=h-v*l,t[9]=-a*c,t[2]=v-h*l,t[6]=g+f*l,t[10]=o*c}else if(e.order==="YXZ"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h+v*a,t[4]=g*a-f,t[8]=o*l,t[1]=o*u,t[5]=o*d,t[9]=-a,t[2]=f*a-g,t[6]=v+h*a,t[10]=o*c}else if(e.order==="ZXY"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h-v*a,t[4]=-o*u,t[8]=g+f*a,t[1]=f+g*a,t[5]=o*d,t[9]=v-h*a,t[2]=-o*l,t[6]=a,t[10]=o*c}else if(e.order==="ZYX"){const h=o*d,f=o*u,g=a*d,v=a*u;t[0]=c*d,t[4]=g*l-f,t[8]=h*l+v,t[1]=c*u,t[5]=v*l+h,t[9]=f*l-g,t[2]=-l,t[6]=a*c,t[10]=o*c}else if(e.order==="YZX"){const h=o*c,f=o*l,g=a*c,v=a*l;t[0]=c*d,t[4]=v-h*u,t[8]=g*u+f,t[1]=u,t[5]=o*d,t[9]=-a*d,t[2]=-l*d,t[6]=f*u+g,t[10]=h-v*u}else if(e.order==="XZY"){const h=o*c,f=o*l,g=a*c,v=a*l;t[0]=c*d,t[4]=-u,t[8]=l*d,t[1]=h*u+v,t[5]=o*d,t[9]=f*u-g,t[2]=g*u-f,t[6]=a*d,t[10]=v*u+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(lS,e,dS)}lookAt(e,t,n){const s=this.elements;return An.subVectors(e,t),An.lengthSq()===0&&(An.z=1),An.normalize(),ns.crossVectors(n,An),ns.lengthSq()===0&&(Math.abs(n.z)===1?An.x+=1e-4:An.z+=1e-4,An.normalize(),ns.crossVectors(n,An)),ns.normalize(),xo.crossVectors(An,ns),s[0]=ns.x,s[4]=xo.x,s[8]=An.x,s[1]=ns.y,s[5]=xo.y,s[9]=An.y,s[2]=ns.z,s[6]=xo.z,s[10]=An.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,o=n[0],a=n[4],c=n[8],l=n[12],d=n[1],u=n[5],h=n[9],f=n[13],g=n[2],v=n[6],m=n[10],p=n[14],T=n[3],E=n[7],y=n[11],S=n[15],C=s[0],w=s[4],k=s[8],_=s[12],x=s[1],R=s[5],O=s[9],F=s[13],q=s[2],K=s[6],G=s[10],W=s[14],te=s[3],ye=s[7],ue=s[11],_e=s[15];return r[0]=o*C+a*x+c*q+l*te,r[4]=o*w+a*R+c*K+l*ye,r[8]=o*k+a*O+c*G+l*ue,r[12]=o*_+a*F+c*W+l*_e,r[1]=d*C+u*x+h*q+f*te,r[5]=d*w+u*R+h*K+f*ye,r[9]=d*k+u*O+h*G+f*ue,r[13]=d*_+u*F+h*W+f*_e,r[2]=g*C+v*x+m*q+p*te,r[6]=g*w+v*R+m*K+p*ye,r[10]=g*k+v*O+m*G+p*ue,r[14]=g*_+v*F+m*W+p*_e,r[3]=T*C+E*x+y*q+S*te,r[7]=T*w+E*R+y*K+S*ye,r[11]=T*k+E*O+y*G+S*ue,r[15]=T*_+E*F+y*W+S*_e,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],s=e[8],r=e[12],o=e[1],a=e[5],c=e[9],l=e[13],d=e[2],u=e[6],h=e[10],f=e[14],g=e[3],v=e[7],m=e[11],p=e[15],T=c*f-l*h,E=a*f-l*u,y=a*h-c*u,S=o*f-l*d,C=o*h-c*d,w=o*u-a*d;return t*(v*T-m*E+p*y)-n*(g*T-m*S+p*C)+s*(g*E-v*S+p*w)-r*(g*y-v*C+m*w)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],d=e[8],u=e[9],h=e[10],f=e[11],g=e[12],v=e[13],m=e[14],p=e[15],T=u*m*l-v*h*l+v*c*f-a*m*f-u*c*p+a*h*p,E=g*h*l-d*m*l-g*c*f+o*m*f+d*c*p-o*h*p,y=d*v*l-g*u*l+g*a*f-o*v*f-d*a*p+o*u*p,S=g*u*c-d*v*c-g*a*h+o*v*h+d*a*m-o*u*m,C=t*T+n*E+s*y+r*S;if(C===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/C;return e[0]=T*w,e[1]=(v*h*r-u*m*r-v*s*f+n*m*f+u*s*p-n*h*p)*w,e[2]=(a*m*r-v*c*r+v*s*l-n*m*l-a*s*p+n*c*p)*w,e[3]=(u*c*r-a*h*r-u*s*l+n*h*l+a*s*f-n*c*f)*w,e[4]=E*w,e[5]=(d*m*r-g*h*r+g*s*f-t*m*f-d*s*p+t*h*p)*w,e[6]=(g*c*r-o*m*r-g*s*l+t*m*l+o*s*p-t*c*p)*w,e[7]=(o*h*r-d*c*r+d*s*l-t*h*l-o*s*f+t*c*f)*w,e[8]=y*w,e[9]=(g*u*r-d*v*r-g*n*f+t*v*f+d*n*p-t*u*p)*w,e[10]=(o*v*r-g*a*r+g*n*l-t*v*l-o*n*p+t*a*p)*w,e[11]=(d*a*r-o*u*r-d*n*l+t*u*l+o*n*f-t*a*f)*w,e[12]=S*w,e[13]=(d*v*s-g*u*s+g*n*h-t*v*h-d*n*m+t*u*m)*w,e[14]=(g*a*s-o*v*s-g*n*c+t*v*c+o*n*m-t*a*m)*w,e[15]=(o*u*s-d*a*s+d*n*c-t*u*c-o*n*h+t*a*h)*w,this}scale(e){const t=this.elements,n=e.x,s=e.y,r=e.z;return t[0]*=n,t[4]*=s,t[8]*=r,t[1]*=n,t[5]*=s,t[9]*=r,t[2]*=n,t[6]*=s,t[10]*=r,t[3]*=n,t[7]*=s,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,s))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),s=Math.sin(t),r=1-n,o=e.x,a=e.y,c=e.z,l=r*o,d=r*a;return this.set(l*o+n,l*a-s*c,l*c+s*a,0,l*a+s*c,d*a+n,d*c-s*o,0,l*c-s*a,d*c+s*o,r*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,s,r,o){return this.set(1,n,r,0,e,1,o,0,t,s,1,0,0,0,0,1),this}compose(e,t,n){const s=this.elements,r=t._x,o=t._y,a=t._z,c=t._w,l=r+r,d=o+o,u=a+a,h=r*l,f=r*d,g=r*u,v=o*d,m=o*u,p=a*u,T=c*l,E=c*d,y=c*u,S=n.x,C=n.y,w=n.z;return s[0]=(1-(v+p))*S,s[1]=(f+y)*S,s[2]=(g-E)*S,s[3]=0,s[4]=(f-y)*C,s[5]=(1-(h+p))*C,s[6]=(m+T)*C,s[7]=0,s[8]=(g+E)*w,s[9]=(m-T)*w,s[10]=(1-(h+v))*w,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,n){const s=this.elements;if(e.x=s[12],e.y=s[13],e.z=s[14],this.determinant()===0)return n.set(1,1,1),t.identity(),this;let r=cr.set(s[0],s[1],s[2]).length();const o=cr.set(s[4],s[5],s[6]).length(),a=cr.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),$n.copy(this);const l=1/r,d=1/o,u=1/a;return $n.elements[0]*=l,$n.elements[1]*=l,$n.elements[2]*=l,$n.elements[4]*=d,$n.elements[5]*=d,$n.elements[6]*=d,$n.elements[8]*=u,$n.elements[9]*=u,$n.elements[10]*=u,t.setFromRotationMatrix($n),n.x=r,n.y=o,n.z=a,this}makePerspective(e,t,n,s,r,o,a=ai,c=!1){const l=this.elements,d=2*r/(t-e),u=2*r/(n-s),h=(t+e)/(t-e),f=(n+s)/(n-s);let g,v;if(c)g=r/(o-r),v=o*r/(o-r);else if(a===ai)g=-(o+r)/(o-r),v=-2*o*r/(o-r);else if(a===mo)g=-o/(o-r),v=-o*r/(o-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=d,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,s,r,o,a=ai,c=!1){const l=this.elements,d=2/(t-e),u=2/(n-s),h=-(t+e)/(t-e),f=-(n+s)/(n-s);let g,v;if(c)g=1/(o-r),v=o/(o-r);else if(a===ai)g=-2/(o-r),v=-(o+r)/(o-r);else if(a===mo)g=-1/(o-r),v=-r/(o-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=d,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<16;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const cr=new U,$n=new At,lS=new U(0,0,0),dS=new U(1,1,1),ns=new U,xo=new U,An=new U,sm=new At,rm=new ta;class Ri{constructor(e=0,t=0,n=0,s=Ri.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,s=this._order){return this._x=e,this._y=t,this._z=n,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const s=e.elements,r=s[0],o=s[4],a=s[8],c=s[1],l=s[5],d=s[9],u=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(Qe(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-d,f),this._z=Math.atan2(-o,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Qe(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(a,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Qe(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-Qe(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(Qe(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-d,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,f));break;case"XZY":this._z=Math.asin(-Qe(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-d,f),this._y=0);break;default:Be("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return sm.makeRotationFromQuaternion(e),this.setFromRotationMatrix(sm,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return rm.setFromEuler(this),this.setFromQuaternion(rm,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Ri.DEFAULT_ORDER="XYZ";class am{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let uS=0;const om=new U,lr=new ta,Pi=new At,To=new U,aa=new U,hS=new U,fS=new ta,cm=new U(1,0,0),lm=new U(0,1,0),dm=new U(0,0,1),um={type:"added"},pS={type:"removed"},dr={type:"childadded",child:null},Od={type:"childremoved",child:null};class Kt extends nr{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:uS++}),this.uuid=Qr(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Kt.DEFAULT_UP.clone();const e=new U,t=new Ri,n=new ta,s=new U(1,1,1);function r(){n.setFromEuler(t,!1)}function o(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new At},normalMatrix:{value:new We}}),this.matrix=new At,this.matrixWorld=new At,this.matrixAutoUpdate=Kt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Kt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new am,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return lr.setFromAxisAngle(e,t),this.quaternion.multiply(lr),this}rotateOnWorldAxis(e,t){return lr.setFromAxisAngle(e,t),this.quaternion.premultiply(lr),this}rotateX(e){return this.rotateOnAxis(cm,e)}rotateY(e){return this.rotateOnAxis(lm,e)}rotateZ(e){return this.rotateOnAxis(dm,e)}translateOnAxis(e,t){return om.copy(e).applyQuaternion(this.quaternion),this.position.add(om.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(cm,e)}translateY(e){return this.translateOnAxis(lm,e)}translateZ(e){return this.translateOnAxis(dm,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Pi.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?To.copy(e):To.set(e,t,n);const s=this.parent;this.updateWorldMatrix(!0,!1),aa.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Pi.lookAt(aa,To,this.up):Pi.lookAt(To,aa,this.up),this.quaternion.setFromRotationMatrix(Pi),s&&(Pi.extractRotation(s.matrixWorld),lr.setFromRotationMatrix(Pi),this.quaternion.premultiply(lr.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(st("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(um),dr.child=e,this.dispatchEvent(dr),dr.child=null):st("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(pS),Od.child=e,this.dispatchEvent(Od),Od.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Pi.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Pi.multiply(e.parent.matrixWorld)),e.applyMatrix4(Pi),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(um),dr.child=e,this.dispatchEvent(dr),dr.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,s=this.children.length;n<s;n++){const o=this.children[n].getObjectByProperty(e,t);if(o!==void 0)return o}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const s=this.children;for(let r=0,o=s.length;r<o;r++)s[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(aa,e,hS),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(aa,fS,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const s=this.children;for(let r=0,o=s.length;r<o;r++)s[r].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const s={};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.castShadow===!0&&(s.castShadow=!0),this.receiveShadow===!0&&(s.receiveShadow=!0),this.visible===!1&&(s.visible=!1),this.frustumCulled===!1&&(s.frustumCulled=!1),this.renderOrder!==0&&(s.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(a=>({...a})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function r(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,d=c.length;l<d;l++){const u=c[l];r(e.shapes,u)}else r(e.shapes,c)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(r(e.materials,this.material[c]));s.material=a}else s.material=r(e.materials,this.material);if(this.children.length>0){s.children=[];for(let a=0;a<this.children.length;a++)s.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){s.animations=[];for(let a=0;a<this.animations.length;a++){const c=this.animations[a];s.animations.push(r(e.animations,c))}}if(t){const a=o(e.geometries),c=o(e.materials),l=o(e.textures),d=o(e.images),u=o(e.shapes),h=o(e.skeletons),f=o(e.animations),g=o(e.nodes);a.length>0&&(n.geometries=a),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),d.length>0&&(n.images=d),u.length>0&&(n.shapes=u),h.length>0&&(n.skeletons=h),f.length>0&&(n.animations=f),g.length>0&&(n.nodes=g)}return n.object=s,n;function o(a){const c=[];for(const l in a){const d=a[l];delete d.metadata,c.push(d)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){const s=e.children[n];this.add(s.clone())}return this}}Kt.DEFAULT_UP=new U(0,1,0),Kt.DEFAULT_MATRIX_AUTO_UPDATE=!0,Kt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Xn=new U,ki=new U,Ud=new U,Ii=new U,ur=new U,hr=new U,hm=new U,Fd=new U,Bd=new U,zd=new U,Vd=new Dt,Gd=new Dt,Hd=new Dt;class Kn{constructor(e=new U,t=new U,n=new U){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,s){s.subVectors(n,t),Xn.subVectors(e,t),s.cross(Xn);const r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(e,t,n,s,r){Xn.subVectors(s,t),ki.subVectors(n,t),Ud.subVectors(e,t);const o=Xn.dot(Xn),a=Xn.dot(ki),c=Xn.dot(Ud),l=ki.dot(ki),d=ki.dot(Ud),u=o*l-a*a;if(u===0)return r.set(0,0,0),null;const h=1/u,f=(l*c-a*d)*h,g=(o*d-a*c)*h;return r.set(1-f-g,g,f)}static containsPoint(e,t,n,s){return this.getBarycoord(e,t,n,s,Ii)===null?!1:Ii.x>=0&&Ii.y>=0&&Ii.x+Ii.y<=1}static getInterpolation(e,t,n,s,r,o,a,c){return this.getBarycoord(e,t,n,s,Ii)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(r,Ii.x),c.addScaledVector(o,Ii.y),c.addScaledVector(a,Ii.z),c)}static getInterpolatedAttribute(e,t,n,s,r,o){return Vd.setScalar(0),Gd.setScalar(0),Hd.setScalar(0),Vd.fromBufferAttribute(e,t),Gd.fromBufferAttribute(e,n),Hd.fromBufferAttribute(e,s),o.setScalar(0),o.addScaledVector(Vd,r.x),o.addScaledVector(Gd,r.y),o.addScaledVector(Hd,r.z),o}static isFrontFacing(e,t,n,s){return Xn.subVectors(n,t),ki.subVectors(e,t),Xn.cross(ki).dot(s)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,s){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,n,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Xn.subVectors(this.c,this.b),ki.subVectors(this.a,this.b),Xn.cross(ki).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Kn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Kn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,s,r){return Kn.getInterpolation(e,this.a,this.b,this.c,t,n,s,r)}containsPoint(e){return Kn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Kn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,s=this.b,r=this.c;let o,a;ur.subVectors(s,n),hr.subVectors(r,n),Fd.subVectors(e,n);const c=ur.dot(Fd),l=hr.dot(Fd);if(c<=0&&l<=0)return t.copy(n);Bd.subVectors(e,s);const d=ur.dot(Bd),u=hr.dot(Bd);if(d>=0&&u<=d)return t.copy(s);const h=c*u-d*l;if(h<=0&&c>=0&&d<=0)return o=c/(c-d),t.copy(n).addScaledVector(ur,o);zd.subVectors(e,r);const f=ur.dot(zd),g=hr.dot(zd);if(g>=0&&f<=g)return t.copy(r);const v=f*l-c*g;if(v<=0&&l>=0&&g<=0)return a=l/(l-g),t.copy(n).addScaledVector(hr,a);const m=d*g-f*u;if(m<=0&&u-d>=0&&f-g>=0)return hm.subVectors(r,s),a=(u-d)/(u-d+(f-g)),t.copy(s).addScaledVector(hm,a);const p=1/(m+v+h);return o=v*p,a=h*p,t.copy(n).addScaledVector(ur,o).addScaledVector(hr,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const fm={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},is={h:0,s:0,l:0},Co={h:0,s:0,l:0};function Wd(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}class Fe{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Nn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,nt.colorSpaceToWorking(this,t),this}setRGB(e,t,n,s=nt.workingColorSpace){return this.r=e,this.g=t,this.b=n,nt.colorSpaceToWorking(this,s),this}setHSL(e,t,n,s=nt.workingColorSpace){if(e=tS(e,1),t=Qe(t,0,1),n=Qe(n,0,1),t===0)this.r=this.g=this.b=n;else{const r=n<=.5?n*(1+t):n+t-n*t,o=2*n-r;this.r=Wd(o,r,e+1/3),this.g=Wd(o,r,e),this.b=Wd(o,r,e-1/3)}return nt.colorSpaceToWorking(this,s),this}setStyle(e,t=Nn){function n(r){r!==void 0&&parseFloat(r)<1&&Be("Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const o=s[1],a=s[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Be("Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=s[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(r,16),t);Be("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Nn){const n=fm[e.toLowerCase()];return n!==void 0?this.setHex(n,t):Be("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Mi(e.r),this.g=Mi(e.g),this.b=Mi(e.b),this}copyLinearToSRGB(e){return this.r=ir(e.r),this.g=ir(e.g),this.b=ir(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Nn){return nt.workingToColorSpace(an.copy(this),e),Math.round(Qe(an.r*255,0,255))*65536+Math.round(Qe(an.g*255,0,255))*256+Math.round(Qe(an.b*255,0,255))}getHexString(e=Nn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=nt.workingColorSpace){nt.workingToColorSpace(an.copy(this),t);const n=an.r,s=an.g,r=an.b,o=Math.max(n,s,r),a=Math.min(n,s,r);let c,l;const d=(a+o)/2;if(a===o)c=0,l=0;else{const u=o-a;switch(l=d<=.5?u/(o+a):u/(2-o-a),o){case n:c=(s-r)/u+(s<r?6:0);break;case s:c=(r-n)/u+2;break;case r:c=(n-s)/u+4;break}c/=6}return e.h=c,e.s=l,e.l=d,e}getRGB(e,t=nt.workingColorSpace){return nt.workingToColorSpace(an.copy(this),t),e.r=an.r,e.g=an.g,e.b=an.b,e}getStyle(e=Nn){nt.workingToColorSpace(an.copy(this),e);const t=an.r,n=an.g,s=an.b;return e!==Nn?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(s*255)})`}offsetHSL(e,t,n){return this.getHSL(is),this.setHSL(is.h+e,is.s+t,is.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(is),e.getHSL(Co);const n=Cd(is.h,Co.h,t),s=Cd(is.s,Co.s,t),r=Cd(is.l,Co.l,t);return this.setHSL(n,s,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,s=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*s,this.g=r[1]*t+r[4]*n+r[7]*s,this.b=r[2]*t+r[5]*n+r[8]*s,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const an=new Fe;Fe.NAMES=fm;let mS=0;class fr extends nr{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:mS++}),this.uuid=Qr(),this.name="",this.type="Material",this.blending=Ys,this.side=_i,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=xl,this.blendDst=Tl,this.blendEquation=gs,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Fe(0,0,0),this.blendAlpha=0,this.depthFunc=Js,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Xp,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=tr,this.stencilZFail=tr,this.stencilZPass=tr,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){Be(`Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Be(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==Ys&&(n.blending=this.blending),this.side!==_i&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==xl&&(n.blendSrc=this.blendSrc),this.blendDst!==Tl&&(n.blendDst=this.blendDst),this.blendEquation!==gs&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==Js&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Xp&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==tr&&(n.stencilFail=this.stencilFail),this.stencilZFail!==tr&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==tr&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){const o=[];for(const a in r){const c=r[a];delete c.metadata,o.push(c)}return o}if(t){const r=s(e.textures),o=s(e.images);r.length>0&&(n.textures=r),o.length>0&&(n.images=o)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const s=t.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class pm extends fr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Fe(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 Ri,this.combine=Ip,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const zt=new U,Eo=new tt;let gS=0;class Sn{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:gS++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Kp,this.updateRanges=[],this.gpuType=ri,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let s=0,r=this.itemSize;s<r;s++)this.array[e+s]=t.array[n+s];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Eo.fromBufferAttribute(this,t),Eo.applyMatrix3(e),this.setXY(t,Eo.x,Eo.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)zt.fromBufferAttribute(this,t),zt.applyMatrix3(e),this.setXYZ(t,zt.x,zt.y,zt.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)zt.fromBufferAttribute(this,t),zt.applyMatrix4(e),this.setXYZ(t,zt.x,zt.y,zt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)zt.fromBufferAttribute(this,t),zt.applyNormalMatrix(e),this.setXYZ(t,zt.x,zt.y,zt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)zt.fromBufferAttribute(this,t),zt.transformDirection(e),this.setXYZ(t,zt.x,zt.y,zt.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=ea(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=_n(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=ea(t,this.array)),t}setX(e,t){return this.normalized&&(t=_n(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=ea(t,this.array)),t}setY(e,t){return this.normalized&&(t=_n(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=ea(t,this.array)),t}setZ(e,t){return this.normalized&&(t=_n(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=ea(t,this.array)),t}setW(e,t){return this.normalized&&(t=_n(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=_n(t,this.array),n=_n(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,s){return e*=this.itemSize,this.normalized&&(t=_n(t,this.array),n=_n(n,this.array),s=_n(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this}setXYZW(e,t,n,s,r){return e*=this.itemSize,this.normalized&&(t=_n(t,this.array),n=_n(n,this.array),s=_n(s,this.array),r=_n(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Kp&&(e.usage=this.usage),e}}class mm extends Sn{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class gm extends Sn{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class on extends Sn{constructor(e,t,n){super(new Float32Array(e),t,n)}}let vS=0;const On=new At,qd=new Kt,pr=new U,Rn=new na,oa=new na,Yt=new U;class fn extends nr{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:vS++}),this.uuid=Qr(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Jp(e)?gm:mm)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const r=new We().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}const s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(e),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return On.makeRotationFromQuaternion(e),this.applyMatrix4(On),this}rotateX(e){return On.makeRotationX(e),this.applyMatrix4(On),this}rotateY(e){return On.makeRotationY(e),this.applyMatrix4(On),this}rotateZ(e){return On.makeRotationZ(e),this.applyMatrix4(On),this}translate(e,t,n){return On.makeTranslation(e,t,n),this.applyMatrix4(On),this}scale(e,t,n){return On.makeScale(e,t,n),this.applyMatrix4(On),this}lookAt(e){return qd.lookAt(e),qd.updateMatrix(),this.applyMatrix4(qd.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(pr).negate(),this.translate(pr.x,pr.y,pr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const n=[];for(let s=0,r=e.length;s<r;s++){const o=e[s];n.push(o.x,o.y,o.z||0)}this.setAttribute("position",new on(n,3))}else{const n=Math.min(e.length,t.count);for(let s=0;s<n;s++){const r=e[s];t.setXYZ(s,r.x,r.y,r.z||0)}e.length>t.count&&Be("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new na);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){st("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new U(-1/0,-1/0,-1/0),new U(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,s=t.length;n<s;n++){const r=t[n];Rn.setFromBufferAttribute(r),this.morphTargetsRelative?(Yt.addVectors(this.boundingBox.min,Rn.min),this.boundingBox.expandByPoint(Yt),Yt.addVectors(this.boundingBox.max,Rn.max),this.boundingBox.expandByPoint(Yt)):(this.boundingBox.expandByPoint(Rn.min),this.boundingBox.expandByPoint(Rn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&st('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 ra);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){st("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new U,1/0);return}if(e){const n=this.boundingSphere.center;if(Rn.setFromBufferAttribute(e),t)for(let r=0,o=t.length;r<o;r++){const a=t[r];oa.setFromBufferAttribute(a),this.morphTargetsRelative?(Yt.addVectors(Rn.min,oa.min),Rn.expandByPoint(Yt),Yt.addVectors(Rn.max,oa.max),Rn.expandByPoint(Yt)):(Rn.expandByPoint(oa.min),Rn.expandByPoint(oa.max))}Rn.getCenter(n);let s=0;for(let r=0,o=e.count;r<o;r++)Yt.fromBufferAttribute(e,r),s=Math.max(s,n.distanceToSquared(Yt));if(t)for(let r=0,o=t.length;r<o;r++){const a=t[r],c=this.morphTargetsRelative;for(let l=0,d=a.count;l<d;l++)Yt.fromBufferAttribute(a,l),c&&(pr.fromBufferAttribute(e,l),Yt.add(pr)),s=Math.max(s,n.distanceToSquared(Yt))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&st('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){st("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const n=t.position,s=t.normal,r=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Sn(new Float32Array(4*n.count),4));const o=this.getAttribute("tangent"),a=[],c=[];for(let k=0;k<n.count;k++)a[k]=new U,c[k]=new U;const l=new U,d=new U,u=new U,h=new tt,f=new tt,g=new tt,v=new U,m=new U;function p(k,_,x){l.fromBufferAttribute(n,k),d.fromBufferAttribute(n,_),u.fromBufferAttribute(n,x),h.fromBufferAttribute(r,k),f.fromBufferAttribute(r,_),g.fromBufferAttribute(r,x),d.sub(l),u.sub(l),f.sub(h),g.sub(h);const R=1/(f.x*g.y-g.x*f.y);isFinite(R)&&(v.copy(d).multiplyScalar(g.y).addScaledVector(u,-f.y).multiplyScalar(R),m.copy(u).multiplyScalar(f.x).addScaledVector(d,-g.x).multiplyScalar(R),a[k].add(v),a[_].add(v),a[x].add(v),c[k].add(m),c[_].add(m),c[x].add(m))}let T=this.groups;T.length===0&&(T=[{start:0,count:e.count}]);for(let k=0,_=T.length;k<_;++k){const x=T[k],R=x.start,O=x.count;for(let F=R,q=R+O;F<q;F+=3)p(e.getX(F+0),e.getX(F+1),e.getX(F+2))}const E=new U,y=new U,S=new U,C=new U;function w(k){S.fromBufferAttribute(s,k),C.copy(S);const _=a[k];E.copy(_),E.sub(S.multiplyScalar(S.dot(_))).normalize(),y.crossVectors(C,_);const R=y.dot(c[k])<0?-1:1;o.setXYZW(k,E.x,E.y,E.z,R)}for(let k=0,_=T.length;k<_;++k){const x=T[k],R=x.start,O=x.count;for(let F=R,q=R+O;F<q;F+=3)w(e.getX(F+0)),w(e.getX(F+1)),w(e.getX(F+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new Sn(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let h=0,f=n.count;h<f;h++)n.setXYZ(h,0,0,0);const s=new U,r=new U,o=new U,a=new U,c=new U,l=new U,d=new U,u=new U;if(e)for(let h=0,f=e.count;h<f;h+=3){const g=e.getX(h+0),v=e.getX(h+1),m=e.getX(h+2);s.fromBufferAttribute(t,g),r.fromBufferAttribute(t,v),o.fromBufferAttribute(t,m),d.subVectors(o,r),u.subVectors(s,r),d.cross(u),a.fromBufferAttribute(n,g),c.fromBufferAttribute(n,v),l.fromBufferAttribute(n,m),a.add(d),c.add(d),l.add(d),n.setXYZ(g,a.x,a.y,a.z),n.setXYZ(v,c.x,c.y,c.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let h=0,f=t.count;h<f;h+=3)s.fromBufferAttribute(t,h+0),r.fromBufferAttribute(t,h+1),o.fromBufferAttribute(t,h+2),d.subVectors(o,r),u.subVectors(s,r),d.cross(u),n.setXYZ(h+0,d.x,d.y,d.z),n.setXYZ(h+1,d.x,d.y,d.z),n.setXYZ(h+2,d.x,d.y,d.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Yt.fromBufferAttribute(e,t),Yt.normalize(),e.setXYZ(t,Yt.x,Yt.y,Yt.z)}toNonIndexed(){function e(a,c){const l=a.array,d=a.itemSize,u=a.normalized,h=new l.constructor(c.length*d);let f=0,g=0;for(let v=0,m=c.length;v<m;v++){a.isInterleavedBufferAttribute?f=c[v]*a.data.stride+a.offset:f=c[v]*d;for(let p=0;p<d;p++)h[g++]=l[f++]}return new Sn(h,d,u)}if(this.index===null)return Be("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new fn,n=this.index.array,s=this.attributes;for(const a in s){const c=s[a],l=e(c,n);t.setAttribute(a,l)}const r=this.morphAttributes;for(const a in r){const c=[],l=r[a];for(let d=0,u=l.length;d<u;d++){const h=l[d],f=e(h,n);c.push(f)}t.morphAttributes[a]=c}t.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let a=0,c=o.length;a<c;a++){const l=o[a];t.addGroup(l.start,l.count,l.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const l=n[c];e.data.attributes[c]=l.toJSON(e.data)}const s={};let r=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],d=[];for(let u=0,h=l.length;u<h;u++){const f=l[u];d.push(f.toJSON(e.data))}d.length>0&&(s[c]=d,r=!0)}r&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere=a.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone());const s=e.attributes;for(const l in s){const d=s[l];this.setAttribute(l,d.clone(t))}const r=e.morphAttributes;for(const l in r){const d=[],u=r[l];for(let h=0,f=u.length;h<f;h++)d.push(u[h].clone(t));this.morphAttributes[l]=d}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let l=0,d=o.length;l<d;l++){const u=o[l];this.addGroup(u.start,u.count,u.materialIndex)}const a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const vm=new At,xs=new Nd,Mo=new ra,ym=new U,wo=new U,Ao=new U,Ro=new U,jd=new U,Po=new U,bm=new U,ko=new U;class xn extends Kt{constructor(e=new fn,t=new pm){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r<o;r++){const a=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}getVertexPosition(e,t){const n=this.geometry,s=n.attributes.position,r=n.morphAttributes.position,o=n.morphTargetsRelative;t.fromBufferAttribute(s,e);const a=this.morphTargetInfluences;if(r&&a){Po.set(0,0,0);for(let c=0,l=r.length;c<l;c++){const d=a[c],u=r[c];d!==0&&(jd.fromBufferAttribute(u,e),o?Po.addScaledVector(jd,d):Po.addScaledVector(jd.sub(t),d))}t.add(Po)}return t}raycast(e,t){const n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Mo.copy(n.boundingSphere),Mo.applyMatrix4(r),xs.copy(e.ray).recast(e.near),!(Mo.containsPoint(xs.origin)===!1&&(xs.intersectSphere(Mo,ym)===null||xs.origin.distanceToSquared(ym)>(e.far-e.near)**2))&&(vm.copy(r).invert(),xs.copy(e.ray).applyMatrix4(vm),!(n.boundingBox!==null&&xs.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,xs)))}_computeIntersections(e,t,n){let s;const r=this.geometry,o=this.material,a=r.index,c=r.attributes.position,l=r.attributes.uv,d=r.attributes.uv1,u=r.attributes.normal,h=r.groups,f=r.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=o[m.materialIndex],T=Math.max(m.start,f.start),E=Math.min(a.count,Math.min(m.start+m.count,f.start+f.count));for(let y=T,S=E;y<S;y+=3){const C=a.getX(y),w=a.getX(y+1),k=a.getX(y+2);s=Io(this,p,e,n,l,d,u,C,w,k),s&&(s.faceIndex=Math.floor(y/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(a.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const T=a.getX(m),E=a.getX(m+1),y=a.getX(m+2);s=Io(this,o,e,n,l,d,u,T,E,y),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}else if(c!==void 0)if(Array.isArray(o))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=o[m.materialIndex],T=Math.max(m.start,f.start),E=Math.min(c.count,Math.min(m.start+m.count,f.start+f.count));for(let y=T,S=E;y<S;y+=3){const C=y,w=y+1,k=y+2;s=Io(this,p,e,n,l,d,u,C,w,k),s&&(s.faceIndex=Math.floor(y/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(c.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const T=m,E=m+1,y=m+2;s=Io(this,o,e,n,l,d,u,T,E,y),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}}}function yS(i,e,t,n,s,r,o,a){let c;if(e.side===nn?c=n.intersectTriangle(o,r,s,!0,a):c=n.intersectTriangle(s,r,o,e.side===_i,a),c===null)return null;ko.copy(a),ko.applyMatrix4(i.matrixWorld);const l=t.ray.origin.distanceTo(ko);return l<t.near||l>t.far?null:{distance:l,point:ko.clone(),object:i}}function Io(i,e,t,n,s,r,o,a,c,l){i.getVertexPosition(a,wo),i.getVertexPosition(c,Ao),i.getVertexPosition(l,Ro);const d=yS(i,e,t,n,wo,Ao,Ro,bm);if(d){const u=new U;Kn.getBarycoord(bm,wo,Ao,Ro,u),s&&(d.uv=Kn.getInterpolatedAttribute(s,a,c,l,u,new tt)),r&&(d.uv1=Kn.getInterpolatedAttribute(r,a,c,l,u,new tt)),o&&(d.normal=Kn.getInterpolatedAttribute(o,a,c,l,u,new U),d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1));const h={a,b:c,c:l,normal:new U,materialIndex:0};Kn.getNormal(wo,Ao,Ro,h.normal),d.face=h,d.barycoord=u}return d}class ca extends fn{constructor(e=1,t=1,n=1,s=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:s,heightSegments:r,depthSegments:o};const a=this;s=Math.floor(s),r=Math.floor(r),o=Math.floor(o);const c=[],l=[],d=[],u=[];let h=0,f=0;g("z","y","x",-1,-1,n,t,e,o,r,0),g("z","y","x",1,-1,n,t,-e,o,r,1),g("x","z","y",1,1,e,n,t,s,o,2),g("x","z","y",1,-1,e,n,-t,s,o,3),g("x","y","z",1,-1,e,t,n,s,r,4),g("x","y","z",-1,-1,e,t,-n,s,r,5),this.setIndex(c),this.setAttribute("position",new on(l,3)),this.setAttribute("normal",new on(d,3)),this.setAttribute("uv",new on(u,2));function g(v,m,p,T,E,y,S,C,w,k,_){const x=y/w,R=S/k,O=y/2,F=S/2,q=C/2,K=w+1,G=k+1;let W=0,te=0;const ye=new U;for(let ue=0;ue<G;ue++){const _e=ue*R-F;for(let Ge=0;Ge<K;Ge++){const Ve=Ge*x-O;ye[v]=Ve*T,ye[m]=_e*E,ye[p]=q,l.push(ye.x,ye.y,ye.z),ye[v]=0,ye[m]=0,ye[p]=C>0?1:-1,d.push(ye.x,ye.y,ye.z),u.push(Ge/w),u.push(1-ue/k),W+=1}}for(let ue=0;ue<k;ue++)for(let _e=0;_e<w;_e++){const Ge=h+_e+K*ue,Ve=h+_e+K*(ue+1),Mt=h+(_e+1)+K*(ue+1),pt=h+(_e+1)+K*ue;c.push(Ge,Ve,pt),c.push(Ve,Mt,pt),te+=6}a.addGroup(f,te,_),f+=te,h+=W}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ca(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function mr(i){const e={};for(const t in i){e[t]={};for(const n in i[t]){const s=i[t][n];s&&(s.isColor||s.isMatrix3||s.isMatrix4||s.isVector2||s.isVector3||s.isVector4||s.isTexture||s.isQuaternion)?s.isRenderTargetTexture?(Be("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=s.clone():Array.isArray(s)?e[t][n]=s.slice():e[t][n]=s}}return e}function pn(i){const e={};for(let t=0;t<i.length;t++){const n=mr(i[t]);for(const s in n)e[s]=n[s]}return e}function bS(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function _m(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:nt.workingColorSpace}const _S={clone:mr,merge:pn};var SS=`void main() {
89
89
  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
90
90
  }`,xS=`void main() {
91
91
  gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
92
- }`;class en extends fr{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=SS,this.fragmentShader=xS,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=mr(e.uniforms),this.uniformsGroups=bS(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const o=this.uniforms[s].value;o&&o.isTexture?t.uniforms[s]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[s]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[s]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[s]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[s]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[s]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[s]={type:"m4",value:o.toArray()}:t.uniforms[s]={value:o}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class Sm extends Xt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new At,this.projectionMatrix=new At,this.projectionMatrixInverse=new At,this.coordinateSystem=ai,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const ss=new U,xm=new tt,Tm=new tt;class xn extends Sm{constructor(e=50,t=1,n=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Td*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(xd*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Td*2*Math.atan(Math.tan(xd*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){ss.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ss.x,ss.y).multiplyScalar(-e/ss.z),ss.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ss.x,ss.y).multiplyScalar(-e/ss.z)}getViewSize(e,t){return this.getViewBounds(e,xm,Tm),t.subVectors(Tm,xm)}setViewOffset(e,t,n,s,r,o){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(xd*.5*this.fov)/this.zoom,n=2*t,s=this.aspect*n,r=-.5*s;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,l=o.fullHeight;r+=o.offsetX*s/c,t-=o.offsetY*n/l,s*=o.width/c,n*=o.height/l}const a=this.filmOffset;a!==0&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const gr=-90,vr=1;class TS extends Xt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new xn(gr,vr,e,t);s.layers=this.layers,this.add(s);const r=new xn(gr,vr,e,t);r.layers=this.layers,this.add(r);const o=new xn(gr,vr,e,t);o.layers=this.layers,this.add(o);const a=new xn(gr,vr,e,t);a.layers=this.layers,this.add(a);const c=new xn(gr,vr,e,t);c.layers=this.layers,this.add(c);const l=new xn(gr,vr,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,s,r,o,a,c]=t;for(const l of t)this.remove(l);if(e===ai)n.up.set(0,1,0),n.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===mo)n.up.set(0,-1,0),n.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,o,a,c,l,d]=this.children,u=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;const v=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,s),e.render(t,r),e.setRenderTarget(n,1,s),e.render(t,o),e.setRenderTarget(n,2,s),e.render(t,a),e.setRenderTarget(n,3,s),e.render(t,c),e.setRenderTarget(n,4,s),e.render(t,l),n.texture.generateMipmaps=v,e.setRenderTarget(n,5,s),e.render(t,d),e.setRenderTarget(u,h,f),e.xr.enabled=g,n.texture.needsPMREMUpdate=!0}}class Cm extends un{constructor(e=[],t=vs,n,s,r,o,a,c,l,d){super(e,t,n,s,r,o,a,c,l,d),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Em extends oi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},s=[n,n,n,n,n,n];this.texture=new Cm(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:`
92
+ }`;class tn extends fr{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=SS,this.fragmentShader=xS,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=mr(e.uniforms),this.uniformsGroups=bS(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const o=this.uniforms[s].value;o&&o.isTexture?t.uniforms[s]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[s]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[s]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[s]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[s]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[s]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[s]={type:"m4",value:o.toArray()}:t.uniforms[s]={value:o}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class Sm extends Kt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new At,this.projectionMatrix=new At,this.projectionMatrixInverse=new At,this.coordinateSystem=ai,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const ss=new U,xm=new tt,Tm=new tt;class Tn extends Sm{constructor(e=50,t=1,n=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Td*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(xd*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Td*2*Math.atan(Math.tan(xd*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){ss.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ss.x,ss.y).multiplyScalar(-e/ss.z),ss.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ss.x,ss.y).multiplyScalar(-e/ss.z)}getViewSize(e,t){return this.getViewBounds(e,xm,Tm),t.subVectors(Tm,xm)}setViewOffset(e,t,n,s,r,o){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(xd*.5*this.fov)/this.zoom,n=2*t,s=this.aspect*n,r=-.5*s;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,l=o.fullHeight;r+=o.offsetX*s/c,t-=o.offsetY*n/l,s*=o.width/c,n*=o.height/l}const a=this.filmOffset;a!==0&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const gr=-90,vr=1;class TS extends Kt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new Tn(gr,vr,e,t);s.layers=this.layers,this.add(s);const r=new Tn(gr,vr,e,t);r.layers=this.layers,this.add(r);const o=new Tn(gr,vr,e,t);o.layers=this.layers,this.add(o);const a=new Tn(gr,vr,e,t);a.layers=this.layers,this.add(a);const c=new Tn(gr,vr,e,t);c.layers=this.layers,this.add(c);const l=new Tn(gr,vr,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,s,r,o,a,c]=t;for(const l of t)this.remove(l);if(e===ai)n.up.set(0,1,0),n.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===mo)n.up.set(0,-1,0),n.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,o,a,c,l,d]=this.children,u=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;const v=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,s),e.render(t,r),e.setRenderTarget(n,1,s),e.render(t,o),e.setRenderTarget(n,2,s),e.render(t,a),e.setRenderTarget(n,3,s),e.render(t,c),e.setRenderTarget(n,4,s),e.render(t,l),n.texture.generateMipmaps=v,e.setRenderTarget(n,5,s),e.render(t,d),e.setRenderTarget(u,h,f),e.xr.enabled=g,n.texture.needsPMREMUpdate=!0}}class Cm extends hn{constructor(e=[],t=vs,n,s,r,o,a,c,l,d){super(e,t,n,s,r,o,a,c,l,d),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Em extends oi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},s=[n,n,n,n,n,n];this.texture=new Cm(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:`
93
93
 
94
94
  varying vec3 vWorldDirection;
95
95
 
@@ -124,7 +124,7 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
124
124
  gl_FragColor = texture2D( tEquirect, sampleUV );
125
125
 
126
126
  }
127
- `},s=new ca(5,5,5),r=new en({name:"CubemapFromEquirect",uniforms:mr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:tn,blending:xi});r.uniforms.tEquirect.value=t;const o=new Sn(s,r),a=t.minFilter;return t.minFilter===ys&&(t.minFilter=nn),new TS(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){const r=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,s);e.setRenderTarget(r)}}class Do extends Xt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const CS={type:"move"};class $d{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Do,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 Do,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new U,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new U),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Do,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new U,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new U),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let s=null,r=null,o=null;const a=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){o=!0;for(const v of e.hand.values()){const m=t.getJointPose(v,n),p=this._getHandJoint(l,v);m!==null&&(p.matrix.fromArray(m.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=m.radius),p.visible=m!==null}const d=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],h=d.position.distanceTo(u.position),f=.02,g=.005;l.inputState.pinching&&h>f+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&h<=f-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1));a!==null&&(s=t.getPose(e.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(CS)))}return a!==null&&(a.visible=s!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new Do;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class Mm extends Xt{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 Ri,this.environmentIntensity=1,this.environmentRotation=new Ri,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class ES extends un{constructor(e=null,t=1,n=1,s,r,o,a,c,l=Qt,d=Qt,u,h){super(null,o,a,c,l,d,s,r,u,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const Xd=new U,MS=new U,wS=new We;class Ts{constructor(e=new U(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,s){return this.normal.set(e,t,n),this.constant=s,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const s=Xd.subVectors(n,t).cross(MS.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(s,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(Xd),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/s;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||wS.getNormalMatrix(e),s=this.coplanarPoint(Xd).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Cs=new ra,AS=new tt(.5,.5),Lo=new U;class Kd{constructor(e=new Ts,t=new Ts,n=new Ts,s=new Ts,r=new Ts,o=new Ts){this.planes=[e,t,n,s,r,o]}set(e,t,n,s,r,o){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(s),a[4].copy(r),a[5].copy(o),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=ai,n=!1){const s=this.planes,r=e.elements,o=r[0],a=r[1],c=r[2],l=r[3],d=r[4],u=r[5],h=r[6],f=r[7],g=r[8],v=r[9],m=r[10],p=r[11],T=r[12],E=r[13],y=r[14],S=r[15];if(s[0].setComponents(l-o,f-d,p-g,S-T).normalize(),s[1].setComponents(l+o,f+d,p+g,S+T).normalize(),s[2].setComponents(l+a,f+u,p+v,S+E).normalize(),s[3].setComponents(l-a,f-u,p-v,S-E).normalize(),n)s[4].setComponents(c,h,m,y).normalize(),s[5].setComponents(l-c,f-h,p-m,S-y).normalize();else if(s[4].setComponents(l-c,f-h,p-m,S-y).normalize(),t===ai)s[5].setComponents(l+c,f+h,p+m,S+y).normalize();else if(t===mo)s[5].setComponents(c,h,m,y).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Cs.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Cs.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Cs)}intersectsSprite(e){Cs.center.set(0,0,0);const t=AS.distanceTo(e.center);return Cs.radius=.7071067811865476+t,Cs.applyMatrix4(e.matrixWorld),this.intersectsSphere(Cs)}intersectsSphere(e){const t=this.planes,n=e.center,s=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<s)return!1;return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const s=t[n];if(Lo.x=s.normal.x>0?e.max.x:e.min.x,Lo.y=s.normal.y>0?e.max.y:e.min.y,Lo.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(Lo)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class RS extends fr{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Fe(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const No=new U,Oo=new U,wm=new At,la=new Nd,Uo=new ra,Yd=new U,Am=new U;class PS extends Xt{constructor(e=new hn,t=new RS){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,n=[0];for(let s=1,r=t.count;s<r;s++)No.fromBufferAttribute(t,s-1),Oo.fromBufferAttribute(t,s),n[s]=n[s-1],n[s]+=No.distanceTo(Oo);e.setAttribute("lineDistance",new an(n,1))}else Be("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const n=this.geometry,s=this.matrixWorld,r=e.params.Line.threshold,o=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Uo.copy(n.boundingSphere),Uo.applyMatrix4(s),Uo.radius+=r,e.ray.intersectsSphere(Uo)===!1)return;wm.copy(s).invert(),la.copy(e.ray).applyMatrix4(wm);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=this.isLineSegments?2:1,d=n.index,h=n.attributes.position;if(d!==null){const f=Math.max(0,o.start),g=Math.min(d.count,o.start+o.count);for(let v=f,m=g-1;v<m;v+=l){const p=d.getX(v),T=d.getX(v+1),E=Fo(this,e,la,c,p,T,v);E&&t.push(E)}if(this.isLineLoop){const v=d.getX(g-1),m=d.getX(f),p=Fo(this,e,la,c,v,m,g-1);p&&t.push(p)}}else{const f=Math.max(0,o.start),g=Math.min(h.count,o.start+o.count);for(let v=f,m=g-1;v<m;v+=l){const p=Fo(this,e,la,c,v,v+1,v);p&&t.push(p)}if(this.isLineLoop){const v=Fo(this,e,la,c,g-1,f,g-1);v&&t.push(v)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r<o;r++){const a=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}}function Fo(i,e,t,n,s,r,o){const a=i.geometry.attributes.position;if(No.fromBufferAttribute(a,s),Oo.fromBufferAttribute(a,r),t.distanceSqToSegment(No,Oo,Yd,Am)>n)return;Yd.applyMatrix4(i.matrixWorld);const l=e.ray.origin.distanceTo(Yd);if(!(l<e.near||l>e.far))return{distance:l,point:Am.clone().applyMatrix4(i.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:i}}class kS extends fr{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Fe(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const Rm=new At,Jd=new Nd,Bo=new ra,zo=new U;class IS extends Xt{constructor(e=new hn,t=new kS){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const n=this.geometry,s=this.matrixWorld,r=e.params.Points.threshold,o=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Bo.copy(n.boundingSphere),Bo.applyMatrix4(s),Bo.radius+=r,e.ray.intersectsSphere(Bo)===!1)return;Rm.copy(s).invert(),Jd.copy(e.ray).applyMatrix4(Rm);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=n.index,u=n.attributes.position;if(l!==null){const h=Math.max(0,o.start),f=Math.min(l.count,o.start+o.count);for(let g=h,v=f;g<v;g++){const m=l.getX(g);zo.fromBufferAttribute(u,m),Pm(zo,m,c,s,e,t,this)}}else{const h=Math.max(0,o.start),f=Math.min(u.count,o.start+o.count);for(let g=h,v=f;g<v;g++)zo.fromBufferAttribute(u,g),Pm(zo,g,c,s,e,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r<o;r++){const a=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}}function Pm(i,e,t,n,s,r,o){const a=Jd.distanceSqToPoint(i);if(a<t){const c=new U;Jd.closestPointToPoint(i,c),c.applyMatrix4(n);const l=s.ray.origin.distanceTo(c);if(l<s.near||l>s.far)return;r.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}class da extends un{constructor(e,t,n=si,s,r,o,a=Qt,c=Qt,l,d=Ei,u=1){if(d!==Ei&&d!==bs)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:u};super(h,s,r,o,a,c,d,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new wd(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class DS extends da{constructor(e,t=si,n=vs,s,r,o=Qt,a=Qt,c,l=Ei){const d={width:e,height:e,depth:1},u=[d,d,d,d,d,d];super(e,e,t,n,s,r,o,a,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class km extends un{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Zd extends hn{constructor(e=[],t=[],n=1,s=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:s};const r=[],o=[];a(s),l(n),d(),this.setAttribute("position",new an(r,3)),this.setAttribute("normal",new an(r.slice(),3)),this.setAttribute("uv",new an(o,2)),s===0?this.computeVertexNormals():this.normalizeNormals();function a(T){const E=new U,y=new U,S=new U;for(let C=0;C<t.length;C+=3)f(t[C+0],E),f(t[C+1],y),f(t[C+2],S),c(E,y,S,T)}function c(T,E,y,S){const C=S+1,w=[];for(let k=0;k<=C;k++){w[k]=[];const _=T.clone().lerp(y,k/C),x=E.clone().lerp(y,k/C),R=C-k;for(let O=0;O<=R;O++)O===0&&k===C?w[k][O]=_:w[k][O]=_.clone().lerp(x,O/R)}for(let k=0;k<C;k++)for(let _=0;_<2*(C-k)-1;_++){const x=Math.floor(_/2);_%2===0?(h(w[k][x+1]),h(w[k+1][x]),h(w[k][x])):(h(w[k][x+1]),h(w[k+1][x+1]),h(w[k+1][x]))}}function l(T){const E=new U;for(let y=0;y<r.length;y+=3)E.x=r[y+0],E.y=r[y+1],E.z=r[y+2],E.normalize().multiplyScalar(T),r[y+0]=E.x,r[y+1]=E.y,r[y+2]=E.z}function d(){const T=new U;for(let E=0;E<r.length;E+=3){T.x=r[E+0],T.y=r[E+1],T.z=r[E+2];const y=m(T)/2/Math.PI+.5,S=p(T)/Math.PI+.5;o.push(y,1-S)}g(),u()}function u(){for(let T=0;T<o.length;T+=6){const E=o[T+0],y=o[T+2],S=o[T+4],C=Math.max(E,y,S),w=Math.min(E,y,S);C>.9&&w<.1&&(E<.2&&(o[T+0]+=1),y<.2&&(o[T+2]+=1),S<.2&&(o[T+4]+=1))}}function h(T){r.push(T.x,T.y,T.z)}function f(T,E){const y=T*3;E.x=e[y+0],E.y=e[y+1],E.z=e[y+2]}function g(){const T=new U,E=new U,y=new U,S=new U,C=new tt,w=new tt,k=new tt;for(let _=0,x=0;_<r.length;_+=9,x+=6){T.set(r[_+0],r[_+1],r[_+2]),E.set(r[_+3],r[_+4],r[_+5]),y.set(r[_+6],r[_+7],r[_+8]),C.set(o[x+0],o[x+1]),w.set(o[x+2],o[x+3]),k.set(o[x+4],o[x+5]),S.copy(T).add(E).add(y).divideScalar(3);const R=m(S);v(C,x+0,T,R),v(w,x+2,E,R),v(k,x+4,y,R)}}function v(T,E,y,S){S<0&&T.x===1&&(o[E]=T.x-1),y.x===0&&y.z===0&&(o[E]=S/2/Math.PI+.5)}function m(T){return Math.atan2(T.z,-T.x)}function p(T){return Math.atan2(-T.y,Math.sqrt(T.x*T.x+T.z*T.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Zd(e.vertices,e.indices,e.radius,e.detail)}}class Qd extends Zd{constructor(e=1,t=0){const n=(1+Math.sqrt(5))/2,s=[-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],r=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(s,r,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Qd(e.radius,e.detail)}}class Vo extends hn{constructor(e=1,t=1,n=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:s};const r=e/2,o=t/2,a=Math.floor(n),c=Math.floor(s),l=a+1,d=c+1,u=e/a,h=t/c,f=[],g=[],v=[],m=[];for(let p=0;p<d;p++){const T=p*h-o;for(let E=0;E<l;E++){const y=E*u-r;g.push(y,-T,0),v.push(0,0,1),m.push(E/a),m.push(1-p/c)}}for(let p=0;p<c;p++)for(let T=0;T<a;T++){const E=T+l*p,y=T+l*(p+1),S=T+1+l*(p+1),C=T+1+l*p;f.push(E,y,C),f.push(y,S,C)}this.setIndex(f),this.setAttribute("position",new an(g,3)),this.setAttribute("normal",new an(v,3)),this.setAttribute("uv",new an(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Vo(e.width,e.height,e.widthSegments,e.heightSegments)}}class yr extends hn{constructor(e=1,t=32,n=16,s=0,r=Math.PI*2,o=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:s,phiLength:r,thetaStart:o,thetaLength:a},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));const c=Math.min(o+a,Math.PI);let l=0;const d=[],u=new U,h=new U,f=[],g=[],v=[],m=[];for(let p=0;p<=n;p++){const T=[],E=p/n;let y=0;p===0&&o===0?y=.5/t:p===n&&c===Math.PI&&(y=-.5/t);for(let S=0;S<=t;S++){const C=S/t;u.x=-e*Math.cos(s+C*r)*Math.sin(o+E*a),u.y=e*Math.cos(o+E*a),u.z=e*Math.sin(s+C*r)*Math.sin(o+E*a),g.push(u.x,u.y,u.z),h.copy(u).normalize(),v.push(h.x,h.y,h.z),m.push(C+y,1-E),T.push(l++)}d.push(T)}for(let p=0;p<n;p++)for(let T=0;T<t;T++){const E=d[p][T+1],y=d[p][T],S=d[p+1][T],C=d[p+1][T+1];(p!==0||o>0)&&f.push(E,y,C),(p!==n-1||c<Math.PI)&&f.push(y,S,C)}this.setIndex(f),this.setAttribute("position",new an(g,3)),this.setAttribute("normal",new an(v,3)),this.setAttribute("uv",new an(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new yr(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class LS extends en{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class NS extends fr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=W_,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class OS extends fr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class eu extends Xt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Fe(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}const tu=new At,Im=new U,Dm=new U;class Lm{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new tt(512,512),this.mapType=Mn,this.map=null,this.mapPass=null,this.matrix=new At,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Kd,this._frameExtents=new tt(1,1),this._viewportCount=1,this._viewports=[new Dt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,n=this.matrix;Im.setFromMatrixPosition(e.matrixWorld),t.position.copy(Im),Dm.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Dm),t.updateMatrixWorld(),tu.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(tu,t.coordinateSystem,t.reversedDepth),t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(tu)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class US extends Lm{constructor(){super(new xn(90,1,.5,500)),this.isPointLightShadow=!0}}class FS extends eu{constructor(e,t,n=0,s=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=s,this.shadow=new US}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}}class nu extends Sm{constructor(e=-1,t=1,n=1,s=-1,r=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=s,this.near=r,this.far=o,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,s,r,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,s=(this.top+this.bottom)/2;let r=n-e,o=n+e,a=s+t,c=s-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,d=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=l*this.view.offsetX,o=r+l*this.view.width,a-=d*this.view.offsetY,c=a-d*this.view.height}this.projectionMatrix.makeOrthographic(r,o,a,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class BS extends Lm{constructor(){super(new nu(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class iu extends eu{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Xt.DEFAULT_UP),this.updateMatrix(),this.target=new Xt,this.shadow=new BS}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class zS extends eu{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class VS extends xn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Nm{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Om(i,e,t,n){const s=GS(n);switch(t){case qp:return i*e;case $p:return i*e/s.components*s.byteLength;case Bl:return i*e/s.components*s.byteLength;case Qs:return i*e*2/s.components*s.byteLength;case zl:return i*e*2/s.components*s.byteLength;case jp:return i*e*3/s.components*s.byteLength;case qn:return i*e*4/s.components*s.byteLength;case Vl:return i*e*4/s.components*s.byteLength;case lo:case uo:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case ho:case fo:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Hl:case ql:return Math.max(i,16)*Math.max(e,8)/4;case Gl:case Wl:return Math.max(i,8)*Math.max(e,8)/2;case jl:case $l:case Kl:case Yl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case Xl:case Jl:case Zl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Ql:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case ed:return Math.floor((i+4)/5)*Math.floor((e+3)/4)*16;case td:return Math.floor((i+4)/5)*Math.floor((e+4)/5)*16;case nd:return Math.floor((i+5)/6)*Math.floor((e+4)/5)*16;case id:return Math.floor((i+5)/6)*Math.floor((e+5)/6)*16;case sd:return Math.floor((i+7)/8)*Math.floor((e+4)/5)*16;case rd:return Math.floor((i+7)/8)*Math.floor((e+5)/6)*16;case ad:return Math.floor((i+7)/8)*Math.floor((e+7)/8)*16;case od:return Math.floor((i+9)/10)*Math.floor((e+4)/5)*16;case cd:return Math.floor((i+9)/10)*Math.floor((e+5)/6)*16;case ld:return Math.floor((i+9)/10)*Math.floor((e+7)/8)*16;case dd:return Math.floor((i+9)/10)*Math.floor((e+9)/10)*16;case ud:return Math.floor((i+11)/12)*Math.floor((e+9)/10)*16;case hd:return Math.floor((i+11)/12)*Math.floor((e+11)/12)*16;case fd:case pd:case md:return Math.ceil(i/4)*Math.ceil(e/4)*16;case gd:case vd:return Math.ceil(i/4)*Math.ceil(e/4)*8;case yd:case bd:return Math.ceil(i/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function GS(i){switch(i){case Mn:case Vp:return{byteLength:1,components:1};case Yr:case Gp:case Ci:return{byteLength:2,components:1};case Ul:case Fl:return{byteLength:2,components:4};case si:case Ol:case ri:return{byteLength:4,components:1};case Hp:case Wp:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${i}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Sl}})),typeof window<"u"&&(window.__THREE__?Be("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Sl);/**
127
+ `},s=new ca(5,5,5),r=new tn({name:"CubemapFromEquirect",uniforms:mr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:nn,blending:xi});r.uniforms.tEquirect.value=t;const o=new xn(s,r),a=t.minFilter;return t.minFilter===ys&&(t.minFilter=sn),new TS(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){const r=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,s);e.setRenderTarget(r)}}class Do extends Kt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const CS={type:"move"};class $d{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Do,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 Do,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new U,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new U),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Do,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new U,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new U),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let s=null,r=null,o=null;const a=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){o=!0;for(const v of e.hand.values()){const m=t.getJointPose(v,n),p=this._getHandJoint(l,v);m!==null&&(p.matrix.fromArray(m.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=m.radius),p.visible=m!==null}const d=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],h=d.position.distanceTo(u.position),f=.02,g=.005;l.inputState.pinching&&h>f+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&h<=f-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1));a!==null&&(s=t.getPose(e.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(CS)))}return a!==null&&(a.visible=s!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new Do;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class Mm extends Kt{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 Ri,this.environmentIntensity=1,this.environmentRotation=new Ri,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class ES extends hn{constructor(e=null,t=1,n=1,s,r,o,a,c,l=en,d=en,u,h){super(null,o,a,c,l,d,s,r,u,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const Xd=new U,MS=new U,wS=new We;class Ts{constructor(e=new U(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,s){return this.normal.set(e,t,n),this.constant=s,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const s=Xd.subVectors(n,t).cross(MS.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(s,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(Xd),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/s;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||wS.getNormalMatrix(e),s=this.coplanarPoint(Xd).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Cs=new ra,AS=new tt(.5,.5),Lo=new U;class Kd{constructor(e=new Ts,t=new Ts,n=new Ts,s=new Ts,r=new Ts,o=new Ts){this.planes=[e,t,n,s,r,o]}set(e,t,n,s,r,o){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(s),a[4].copy(r),a[5].copy(o),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=ai,n=!1){const s=this.planes,r=e.elements,o=r[0],a=r[1],c=r[2],l=r[3],d=r[4],u=r[5],h=r[6],f=r[7],g=r[8],v=r[9],m=r[10],p=r[11],T=r[12],E=r[13],y=r[14],S=r[15];if(s[0].setComponents(l-o,f-d,p-g,S-T).normalize(),s[1].setComponents(l+o,f+d,p+g,S+T).normalize(),s[2].setComponents(l+a,f+u,p+v,S+E).normalize(),s[3].setComponents(l-a,f-u,p-v,S-E).normalize(),n)s[4].setComponents(c,h,m,y).normalize(),s[5].setComponents(l-c,f-h,p-m,S-y).normalize();else if(s[4].setComponents(l-c,f-h,p-m,S-y).normalize(),t===ai)s[5].setComponents(l+c,f+h,p+m,S+y).normalize();else if(t===mo)s[5].setComponents(c,h,m,y).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Cs.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Cs.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Cs)}intersectsSprite(e){Cs.center.set(0,0,0);const t=AS.distanceTo(e.center);return Cs.radius=.7071067811865476+t,Cs.applyMatrix4(e.matrixWorld),this.intersectsSphere(Cs)}intersectsSphere(e){const t=this.planes,n=e.center,s=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<s)return!1;return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const s=t[n];if(Lo.x=s.normal.x>0?e.max.x:e.min.x,Lo.y=s.normal.y>0?e.max.y:e.min.y,Lo.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(Lo)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class RS extends fr{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Fe(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const No=new U,Oo=new U,wm=new At,la=new Nd,Uo=new ra,Yd=new U,Am=new U;class PS extends Kt{constructor(e=new fn,t=new RS){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,n=[0];for(let s=1,r=t.count;s<r;s++)No.fromBufferAttribute(t,s-1),Oo.fromBufferAttribute(t,s),n[s]=n[s-1],n[s]+=No.distanceTo(Oo);e.setAttribute("lineDistance",new on(n,1))}else Be("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const n=this.geometry,s=this.matrixWorld,r=e.params.Line.threshold,o=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Uo.copy(n.boundingSphere),Uo.applyMatrix4(s),Uo.radius+=r,e.ray.intersectsSphere(Uo)===!1)return;wm.copy(s).invert(),la.copy(e.ray).applyMatrix4(wm);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=this.isLineSegments?2:1,d=n.index,h=n.attributes.position;if(d!==null){const f=Math.max(0,o.start),g=Math.min(d.count,o.start+o.count);for(let v=f,m=g-1;v<m;v+=l){const p=d.getX(v),T=d.getX(v+1),E=Fo(this,e,la,c,p,T,v);E&&t.push(E)}if(this.isLineLoop){const v=d.getX(g-1),m=d.getX(f),p=Fo(this,e,la,c,v,m,g-1);p&&t.push(p)}}else{const f=Math.max(0,o.start),g=Math.min(h.count,o.start+o.count);for(let v=f,m=g-1;v<m;v+=l){const p=Fo(this,e,la,c,v,v+1,v);p&&t.push(p)}if(this.isLineLoop){const v=Fo(this,e,la,c,g-1,f,g-1);v&&t.push(v)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r<o;r++){const a=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}}function Fo(i,e,t,n,s,r,o){const a=i.geometry.attributes.position;if(No.fromBufferAttribute(a,s),Oo.fromBufferAttribute(a,r),t.distanceSqToSegment(No,Oo,Yd,Am)>n)return;Yd.applyMatrix4(i.matrixWorld);const l=e.ray.origin.distanceTo(Yd);if(!(l<e.near||l>e.far))return{distance:l,point:Am.clone().applyMatrix4(i.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:i}}class kS extends fr{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Fe(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const Rm=new At,Jd=new Nd,Bo=new ra,zo=new U;class IS extends Kt{constructor(e=new fn,t=new kS){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const n=this.geometry,s=this.matrixWorld,r=e.params.Points.threshold,o=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Bo.copy(n.boundingSphere),Bo.applyMatrix4(s),Bo.radius+=r,e.ray.intersectsSphere(Bo)===!1)return;Rm.copy(s).invert(),Jd.copy(e.ray).applyMatrix4(Rm);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=n.index,u=n.attributes.position;if(l!==null){const h=Math.max(0,o.start),f=Math.min(l.count,o.start+o.count);for(let g=h,v=f;g<v;g++){const m=l.getX(g);zo.fromBufferAttribute(u,m),Pm(zo,m,c,s,e,t,this)}}else{const h=Math.max(0,o.start),f=Math.min(u.count,o.start+o.count);for(let g=h,v=f;g<v;g++)zo.fromBufferAttribute(u,g),Pm(zo,g,c,s,e,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r<o;r++){const a=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}}function Pm(i,e,t,n,s,r,o){const a=Jd.distanceSqToPoint(i);if(a<t){const c=new U;Jd.closestPointToPoint(i,c),c.applyMatrix4(n);const l=s.ray.origin.distanceTo(c);if(l<s.near||l>s.far)return;r.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}class da extends hn{constructor(e,t,n=si,s,r,o,a=en,c=en,l,d=Ei,u=1){if(d!==Ei&&d!==bs)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:u};super(h,s,r,o,a,c,d,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new wd(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class DS extends da{constructor(e,t=si,n=vs,s,r,o=en,a=en,c,l=Ei){const d={width:e,height:e,depth:1},u=[d,d,d,d,d,d];super(e,e,t,n,s,r,o,a,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class km extends hn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Zd extends fn{constructor(e=[],t=[],n=1,s=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:s};const r=[],o=[];a(s),l(n),d(),this.setAttribute("position",new on(r,3)),this.setAttribute("normal",new on(r.slice(),3)),this.setAttribute("uv",new on(o,2)),s===0?this.computeVertexNormals():this.normalizeNormals();function a(T){const E=new U,y=new U,S=new U;for(let C=0;C<t.length;C+=3)f(t[C+0],E),f(t[C+1],y),f(t[C+2],S),c(E,y,S,T)}function c(T,E,y,S){const C=S+1,w=[];for(let k=0;k<=C;k++){w[k]=[];const _=T.clone().lerp(y,k/C),x=E.clone().lerp(y,k/C),R=C-k;for(let O=0;O<=R;O++)O===0&&k===C?w[k][O]=_:w[k][O]=_.clone().lerp(x,O/R)}for(let k=0;k<C;k++)for(let _=0;_<2*(C-k)-1;_++){const x=Math.floor(_/2);_%2===0?(h(w[k][x+1]),h(w[k+1][x]),h(w[k][x])):(h(w[k][x+1]),h(w[k+1][x+1]),h(w[k+1][x]))}}function l(T){const E=new U;for(let y=0;y<r.length;y+=3)E.x=r[y+0],E.y=r[y+1],E.z=r[y+2],E.normalize().multiplyScalar(T),r[y+0]=E.x,r[y+1]=E.y,r[y+2]=E.z}function d(){const T=new U;for(let E=0;E<r.length;E+=3){T.x=r[E+0],T.y=r[E+1],T.z=r[E+2];const y=m(T)/2/Math.PI+.5,S=p(T)/Math.PI+.5;o.push(y,1-S)}g(),u()}function u(){for(let T=0;T<o.length;T+=6){const E=o[T+0],y=o[T+2],S=o[T+4],C=Math.max(E,y,S),w=Math.min(E,y,S);C>.9&&w<.1&&(E<.2&&(o[T+0]+=1),y<.2&&(o[T+2]+=1),S<.2&&(o[T+4]+=1))}}function h(T){r.push(T.x,T.y,T.z)}function f(T,E){const y=T*3;E.x=e[y+0],E.y=e[y+1],E.z=e[y+2]}function g(){const T=new U,E=new U,y=new U,S=new U,C=new tt,w=new tt,k=new tt;for(let _=0,x=0;_<r.length;_+=9,x+=6){T.set(r[_+0],r[_+1],r[_+2]),E.set(r[_+3],r[_+4],r[_+5]),y.set(r[_+6],r[_+7],r[_+8]),C.set(o[x+0],o[x+1]),w.set(o[x+2],o[x+3]),k.set(o[x+4],o[x+5]),S.copy(T).add(E).add(y).divideScalar(3);const R=m(S);v(C,x+0,T,R),v(w,x+2,E,R),v(k,x+4,y,R)}}function v(T,E,y,S){S<0&&T.x===1&&(o[E]=T.x-1),y.x===0&&y.z===0&&(o[E]=S/2/Math.PI+.5)}function m(T){return Math.atan2(T.z,-T.x)}function p(T){return Math.atan2(-T.y,Math.sqrt(T.x*T.x+T.z*T.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Zd(e.vertices,e.indices,e.radius,e.detail)}}class Qd extends Zd{constructor(e=1,t=0){const n=(1+Math.sqrt(5))/2,s=[-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],r=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(s,r,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Qd(e.radius,e.detail)}}class Vo extends fn{constructor(e=1,t=1,n=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:s};const r=e/2,o=t/2,a=Math.floor(n),c=Math.floor(s),l=a+1,d=c+1,u=e/a,h=t/c,f=[],g=[],v=[],m=[];for(let p=0;p<d;p++){const T=p*h-o;for(let E=0;E<l;E++){const y=E*u-r;g.push(y,-T,0),v.push(0,0,1),m.push(E/a),m.push(1-p/c)}}for(let p=0;p<c;p++)for(let T=0;T<a;T++){const E=T+l*p,y=T+l*(p+1),S=T+1+l*(p+1),C=T+1+l*p;f.push(E,y,C),f.push(y,S,C)}this.setIndex(f),this.setAttribute("position",new on(g,3)),this.setAttribute("normal",new on(v,3)),this.setAttribute("uv",new on(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Vo(e.width,e.height,e.widthSegments,e.heightSegments)}}class yr extends fn{constructor(e=1,t=32,n=16,s=0,r=Math.PI*2,o=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:s,phiLength:r,thetaStart:o,thetaLength:a},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));const c=Math.min(o+a,Math.PI);let l=0;const d=[],u=new U,h=new U,f=[],g=[],v=[],m=[];for(let p=0;p<=n;p++){const T=[],E=p/n;let y=0;p===0&&o===0?y=.5/t:p===n&&c===Math.PI&&(y=-.5/t);for(let S=0;S<=t;S++){const C=S/t;u.x=-e*Math.cos(s+C*r)*Math.sin(o+E*a),u.y=e*Math.cos(o+E*a),u.z=e*Math.sin(s+C*r)*Math.sin(o+E*a),g.push(u.x,u.y,u.z),h.copy(u).normalize(),v.push(h.x,h.y,h.z),m.push(C+y,1-E),T.push(l++)}d.push(T)}for(let p=0;p<n;p++)for(let T=0;T<t;T++){const E=d[p][T+1],y=d[p][T],S=d[p+1][T],C=d[p+1][T+1];(p!==0||o>0)&&f.push(E,y,C),(p!==n-1||c<Math.PI)&&f.push(y,S,C)}this.setIndex(f),this.setAttribute("position",new on(g,3)),this.setAttribute("normal",new on(v,3)),this.setAttribute("uv",new on(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new yr(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class LS extends tn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class NS extends fr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=W_,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class OS extends fr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class eu extends Kt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Fe(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}const tu=new At,Im=new U,Dm=new U;class Lm{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new tt(512,512),this.mapType=wn,this.map=null,this.mapPass=null,this.matrix=new At,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Kd,this._frameExtents=new tt(1,1),this._viewportCount=1,this._viewports=[new Dt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,n=this.matrix;Im.setFromMatrixPosition(e.matrixWorld),t.position.copy(Im),Dm.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Dm),t.updateMatrixWorld(),tu.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(tu,t.coordinateSystem,t.reversedDepth),t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(tu)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class US extends Lm{constructor(){super(new Tn(90,1,.5,500)),this.isPointLightShadow=!0}}class FS extends eu{constructor(e,t,n=0,s=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=s,this.shadow=new US}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}}class nu extends Sm{constructor(e=-1,t=1,n=1,s=-1,r=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=s,this.near=r,this.far=o,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,s,r,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,s=(this.top+this.bottom)/2;let r=n-e,o=n+e,a=s+t,c=s-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,d=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=l*this.view.offsetX,o=r+l*this.view.width,a-=d*this.view.offsetY,c=a-d*this.view.height}this.projectionMatrix.makeOrthographic(r,o,a,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class BS extends Lm{constructor(){super(new nu(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class iu extends eu{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Kt.DEFAULT_UP),this.updateMatrix(),this.target=new Kt,this.shadow=new BS}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class zS extends eu{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class VS extends Tn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Nm{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Om(i,e,t,n){const s=GS(n);switch(t){case qp:return i*e;case $p:return i*e/s.components*s.byteLength;case Bl:return i*e/s.components*s.byteLength;case Qs:return i*e*2/s.components*s.byteLength;case zl:return i*e*2/s.components*s.byteLength;case jp:return i*e*3/s.components*s.byteLength;case qn:return i*e*4/s.components*s.byteLength;case Vl:return i*e*4/s.components*s.byteLength;case lo:case uo:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case ho:case fo:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Hl:case ql:return Math.max(i,16)*Math.max(e,8)/4;case Gl:case Wl:return Math.max(i,8)*Math.max(e,8)/2;case jl:case $l:case Kl:case Yl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case Xl:case Jl:case Zl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Ql:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case ed:return Math.floor((i+4)/5)*Math.floor((e+3)/4)*16;case td:return Math.floor((i+4)/5)*Math.floor((e+4)/5)*16;case nd:return Math.floor((i+5)/6)*Math.floor((e+4)/5)*16;case id:return Math.floor((i+5)/6)*Math.floor((e+5)/6)*16;case sd:return Math.floor((i+7)/8)*Math.floor((e+4)/5)*16;case rd:return Math.floor((i+7)/8)*Math.floor((e+5)/6)*16;case ad:return Math.floor((i+7)/8)*Math.floor((e+7)/8)*16;case od:return Math.floor((i+9)/10)*Math.floor((e+4)/5)*16;case cd:return Math.floor((i+9)/10)*Math.floor((e+5)/6)*16;case ld:return Math.floor((i+9)/10)*Math.floor((e+7)/8)*16;case dd:return Math.floor((i+9)/10)*Math.floor((e+9)/10)*16;case ud:return Math.floor((i+11)/12)*Math.floor((e+9)/10)*16;case hd:return Math.floor((i+11)/12)*Math.floor((e+11)/12)*16;case fd:case pd:case md:return Math.ceil(i/4)*Math.ceil(e/4)*16;case gd:case vd:return Math.ceil(i/4)*Math.ceil(e/4)*8;case yd:case bd:return Math.ceil(i/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function GS(i){switch(i){case wn:case Vp:return{byteLength:1,components:1};case Yr:case Gp:case Ci:return{byteLength:2,components:1};case Ul:case Fl:return{byteLength:2,components:4};case si:case Ol:case ri:return{byteLength:4,components:1};case Hp:case Wp:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${i}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Sl}})),typeof window<"u"&&(window.__THREE__?Be("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Sl);/**
128
128
  * @license
129
129
  * Copyright 2010-2025 Three.js Authors
130
130
  * SPDX-License-Identifier: MIT
@@ -3693,7 +3693,7 @@ void main() {
3693
3693
  #include <tonemapping_fragment>
3694
3694
  #include <colorspace_fragment>
3695
3695
  #include <fog_fragment>
3696
- }`},ve={common:{diffuse:{value:new Fe(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new We},alphaMap:{value:null},alphaMapTransform:{value:new We},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new We}},envmap:{envMap:{value:null},envMapRotation:{value:new We},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 We}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new We}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new We},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new We},normalScale:{value:new tt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new We},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new We}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new We}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new We}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Fe(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 Fe(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new We},alphaTest:{value:0},uvTransform:{value:new We}},sprite:{diffuse:{value:new Fe(16777215)},opacity:{value:1},center:{value:new tt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new We},alphaMap:{value:null},alphaMapTransform:{value:new We},alphaTest:{value:0}}},ci={basic:{uniforms:fn([ve.common,ve.specularmap,ve.envmap,ve.aomap,ve.lightmap,ve.fog]),vertexShader:je.meshbasic_vert,fragmentShader:je.meshbasic_frag},lambert:{uniforms:fn([ve.common,ve.specularmap,ve.envmap,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.fog,ve.lights,{emissive:{value:new Fe(0)}}]),vertexShader:je.meshlambert_vert,fragmentShader:je.meshlambert_frag},phong:{uniforms:fn([ve.common,ve.specularmap,ve.envmap,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.fog,ve.lights,{emissive:{value:new Fe(0)},specular:{value:new Fe(1118481)},shininess:{value:30}}]),vertexShader:je.meshphong_vert,fragmentShader:je.meshphong_frag},standard:{uniforms:fn([ve.common,ve.envmap,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.roughnessmap,ve.metalnessmap,ve.fog,ve.lights,{emissive:{value:new Fe(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:je.meshphysical_vert,fragmentShader:je.meshphysical_frag},toon:{uniforms:fn([ve.common,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.gradientmap,ve.fog,ve.lights,{emissive:{value:new Fe(0)}}]),vertexShader:je.meshtoon_vert,fragmentShader:je.meshtoon_frag},matcap:{uniforms:fn([ve.common,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.fog,{matcap:{value:null}}]),vertexShader:je.meshmatcap_vert,fragmentShader:je.meshmatcap_frag},points:{uniforms:fn([ve.points,ve.fog]),vertexShader:je.points_vert,fragmentShader:je.points_frag},dashed:{uniforms:fn([ve.common,ve.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:je.linedashed_vert,fragmentShader:je.linedashed_frag},depth:{uniforms:fn([ve.common,ve.displacementmap]),vertexShader:je.depth_vert,fragmentShader:je.depth_frag},normal:{uniforms:fn([ve.common,ve.bumpmap,ve.normalmap,ve.displacementmap,{opacity:{value:1}}]),vertexShader:je.meshnormal_vert,fragmentShader:je.meshnormal_frag},sprite:{uniforms:fn([ve.sprite,ve.fog]),vertexShader:je.sprite_vert,fragmentShader:je.sprite_frag},background:{uniforms:{uvTransform:{value:new We},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:je.background_vert,fragmentShader:je.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new We}},vertexShader:je.backgroundCube_vert,fragmentShader:je.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:je.cube_vert,fragmentShader:je.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:je.equirect_vert,fragmentShader:je.equirect_frag},distance:{uniforms:fn([ve.common,ve.displacementmap,{referencePosition:{value:new U},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:je.distance_vert,fragmentShader:je.distance_frag},shadow:{uniforms:fn([ve.lights,ve.fog,{color:{value:new Fe(0)},opacity:{value:1}}]),vertexShader:je.shadow_vert,fragmentShader:je.shadow_frag}};ci.physical={uniforms:fn([ci.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new We},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new We},clearcoatNormalScale:{value:new tt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new We},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new We},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new We},sheen:{value:0},sheenColor:{value:new Fe(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new We},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new We},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new We},transmissionSamplerSize:{value:new tt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new We},attenuationDistance:{value:0},attenuationColor:{value:new Fe(0)},specularColor:{value:new Fe(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new We},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new We},anisotropyVector:{value:new tt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new We}}]),vertexShader:je.meshphysical_vert,fragmentShader:je.meshphysical_frag};const Go={r:0,b:0,g:0},Es=new Ri,HT=new At;function WT(i,e,t,n,s,r,o){const a=new Fe(0);let c=r===!0?0:1,l,d,u=null,h=0,f=null;function g(E){let y=E.isScene===!0?E.background:null;return y&&y.isTexture&&(y=(E.backgroundBlurriness>0?t:e).get(y)),y}function v(E){let y=!1;const S=g(E);S===null?p(a,c):S&&S.isColor&&(p(S,1),y=!0);const C=i.xr.getEnvironmentBlendMode();C==="additive"?n.buffers.color.setClear(0,0,0,1,o):C==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,o),(i.autoClear||y)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function m(E,y){const S=g(y);S&&(S.isCubeTexture||S.mapping===oo)?(d===void 0&&(d=new Sn(new ca(1,1,1),new en({name:"BackgroundCubeMaterial",uniforms:mr(ci.backgroundCube.uniforms),vertexShader:ci.backgroundCube.vertexShader,fragmentShader:ci.backgroundCube.fragmentShader,side:tn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(C,w,k){this.matrixWorld.copyPosition(k.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(d)),Es.copy(y.backgroundRotation),Es.x*=-1,Es.y*=-1,Es.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(Es.y*=-1,Es.z*=-1),d.material.uniforms.envMap.value=S,d.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=y.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=y.backgroundIntensity,d.material.uniforms.backgroundRotation.value.setFromMatrix4(HT.makeRotationFromEuler(Es)),d.material.toneMapped=nt.getTransfer(S.colorSpace)!==lt,(u!==S||h!==S.version||f!==i.toneMapping)&&(d.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),d.layers.enableAll(),E.unshift(d,d.geometry,d.material,0,0,null)):S&&S.isTexture&&(l===void 0&&(l=new Sn(new Vo(2,2),new en({name:"BackgroundMaterial",uniforms:mr(ci.background.uniforms),vertexShader:ci.background.vertexShader,fragmentShader:ci.background.fragmentShader,side:_i,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(l)),l.material.uniforms.t2D.value=S,l.material.uniforms.backgroundIntensity.value=y.backgroundIntensity,l.material.toneMapped=nt.getTransfer(S.colorSpace)!==lt,S.matrixAutoUpdate===!0&&S.updateMatrix(),l.material.uniforms.uvTransform.value.copy(S.matrix),(u!==S||h!==S.version||f!==i.toneMapping)&&(l.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),l.layers.enableAll(),E.unshift(l,l.geometry,l.material,0,0,null))}function p(E,y){E.getRGB(Go,_m(i)),n.buffers.color.setClear(Go.r,Go.g,Go.b,y,o)}function T(){d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(E,y=1){a.set(E),c=y,p(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(E){c=E,p(a,c)},render:v,addToRenderList:m,dispose:T}}function qT(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=h(null);let r=s,o=!1;function a(x,R,O,F,q){let K=!1;const G=u(F,O,R);r!==G&&(r=G,l(r.object)),K=f(x,F,O,q),K&&g(x,F,O,q),q!==null&&e.update(q,i.ELEMENT_ARRAY_BUFFER),(K||o)&&(o=!1,y(x,R,O,F),q!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(q).buffer))}function c(){return i.createVertexArray()}function l(x){return i.bindVertexArray(x)}function d(x){return i.deleteVertexArray(x)}function u(x,R,O){const F=O.wireframe===!0;let q=n[x.id];q===void 0&&(q={},n[x.id]=q);let K=q[R.id];K===void 0&&(K={},q[R.id]=K);let G=K[F];return G===void 0&&(G=h(c()),K[F]=G),G}function h(x){const R=[],O=[],F=[];for(let q=0;q<t;q++)R[q]=0,O[q]=0,F[q]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:R,enabledAttributes:O,attributeDivisors:F,object:x,attributes:{},index:null}}function f(x,R,O,F){const q=r.attributes,K=R.attributes;let G=0;const W=O.getAttributes();for(const te in W)if(W[te].location>=0){const de=q[te];let _e=K[te];if(_e===void 0&&(te==="instanceMatrix"&&x.instanceMatrix&&(_e=x.instanceMatrix),te==="instanceColor"&&x.instanceColor&&(_e=x.instanceColor)),de===void 0||de.attribute!==_e||_e&&de.data!==_e.data)return!0;G++}return r.attributesNum!==G||r.index!==F}function g(x,R,O,F){const q={},K=R.attributes;let G=0;const W=O.getAttributes();for(const te in W)if(W[te].location>=0){let de=K[te];de===void 0&&(te==="instanceMatrix"&&x.instanceMatrix&&(de=x.instanceMatrix),te==="instanceColor"&&x.instanceColor&&(de=x.instanceColor));const _e={};_e.attribute=de,de&&de.data&&(_e.data=de.data),q[te]=_e,G++}r.attributes=q,r.attributesNum=G,r.index=F}function v(){const x=r.newAttributes;for(let R=0,O=x.length;R<O;R++)x[R]=0}function m(x){p(x,0)}function p(x,R){const O=r.newAttributes,F=r.enabledAttributes,q=r.attributeDivisors;O[x]=1,F[x]===0&&(i.enableVertexAttribArray(x),F[x]=1),q[x]!==R&&(i.vertexAttribDivisor(x,R),q[x]=R)}function T(){const x=r.newAttributes,R=r.enabledAttributes;for(let O=0,F=R.length;O<F;O++)R[O]!==x[O]&&(i.disableVertexAttribArray(O),R[O]=0)}function E(x,R,O,F,q,K,G){G===!0?i.vertexAttribIPointer(x,R,O,q,K):i.vertexAttribPointer(x,R,O,F,q,K)}function y(x,R,O,F){v();const q=F.attributes,K=O.getAttributes(),G=R.defaultAttributeValues;for(const W in K){const te=K[W];if(te.location>=0){let ye=q[W];if(ye===void 0&&(W==="instanceMatrix"&&x.instanceMatrix&&(ye=x.instanceMatrix),W==="instanceColor"&&x.instanceColor&&(ye=x.instanceColor)),ye!==void 0){const de=ye.normalized,_e=ye.itemSize,Ge=e.get(ye);if(Ge===void 0)continue;const Ve=Ge.buffer,Mt=Ge.type,pt=Ge.bytesPerElement,Y=Mt===i.INT||Mt===i.UNSIGNED_INT||ye.gpuType===Ol;if(ye.isInterleavedBufferAttribute){const ie=ye.data,Ce=ie.stride,qe=ye.offset;if(ie.isInstancedInterleavedBuffer){for(let we=0;we<te.locationSize;we++)p(te.location+we,ie.meshPerAttribute);x.isInstancedMesh!==!0&&F._maxInstanceCount===void 0&&(F._maxInstanceCount=ie.meshPerAttribute*ie.count)}else for(let we=0;we<te.locationSize;we++)m(te.location+we);i.bindBuffer(i.ARRAY_BUFFER,Ve);for(let we=0;we<te.locationSize;we++)E(te.location+we,_e/te.locationSize,Mt,de,Ce*pt,(qe+_e/te.locationSize*we)*pt,Y)}else{if(ye.isInstancedBufferAttribute){for(let ie=0;ie<te.locationSize;ie++)p(te.location+ie,ye.meshPerAttribute);x.isInstancedMesh!==!0&&F._maxInstanceCount===void 0&&(F._maxInstanceCount=ye.meshPerAttribute*ye.count)}else for(let ie=0;ie<te.locationSize;ie++)m(te.location+ie);i.bindBuffer(i.ARRAY_BUFFER,Ve);for(let ie=0;ie<te.locationSize;ie++)E(te.location+ie,_e/te.locationSize,Mt,de,_e*pt,_e/te.locationSize*ie*pt,Y)}}else if(G!==void 0){const de=G[W];if(de!==void 0)switch(de.length){case 2:i.vertexAttrib2fv(te.location,de);break;case 3:i.vertexAttrib3fv(te.location,de);break;case 4:i.vertexAttrib4fv(te.location,de);break;default:i.vertexAttrib1fv(te.location,de)}}}}T()}function S(){k();for(const x in n){const R=n[x];for(const O in R){const F=R[O];for(const q in F)d(F[q].object),delete F[q];delete R[O]}delete n[x]}}function C(x){if(n[x.id]===void 0)return;const R=n[x.id];for(const O in R){const F=R[O];for(const q in F)d(F[q].object),delete F[q];delete R[O]}delete n[x.id]}function w(x){for(const R in n){const O=n[R];if(O[x.id]===void 0)continue;const F=O[x.id];for(const q in F)d(F[q].object),delete F[q];delete O[x.id]}}function k(){_(),o=!0,r!==s&&(r=s,l(r.object))}function _(){s.geometry=null,s.program=null,s.wireframe=!1}return{setup:a,reset:k,resetDefaultState:_,dispose:S,releaseStatesOfGeometry:C,releaseStatesOfProgram:w,initAttributes:v,enableAttribute:m,disableUnusedAttributes:T}}function jT(i,e,t){let n;function s(l){n=l}function r(l,d){i.drawArrays(n,l,d),t.update(d,n,1)}function o(l,d,u){u!==0&&(i.drawArraysInstanced(n,l,d,u),t.update(d,n,u))}function a(l,d,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,d,0,u);let f=0;for(let g=0;g<u;g++)f+=d[g];t.update(f,n,1)}function c(l,d,u,h){if(u===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let g=0;g<l.length;g++)o(l[g],d[g],h[g]);else{f.multiDrawArraysInstancedWEBGL(n,l,0,d,0,h,0,u);let g=0;for(let v=0;v<u;v++)g+=d[v]*h[v];t.update(g,n,1)}}this.setMode=s,this.render=r,this.renderInstances=o,this.renderMultiDraw=a,this.renderMultiDrawInstances=c}function $T(i,e,t,n){let s;function r(){if(s!==void 0)return s;if(e.has("EXT_texture_filter_anisotropic")===!0){const w=e.get("EXT_texture_filter_anisotropic");s=i.getParameter(w.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s}function o(w){return!(w!==qn&&n.convert(w)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function a(w){const k=w===Ci&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(w!==Mn&&n.convert(w)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE)&&w!==ri&&!k)}function c(w){if(w==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";w="mediump"}return w==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const d=c(l);d!==l&&(Be("WebGLRenderer:",l,"not supported, using",d,"instead."),l=d);const u=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),g=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),p=i.getParameter(i.MAX_VERTEX_ATTRIBS),T=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),E=i.getParameter(i.MAX_VARYING_VECTORS),y=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),S=i.getParameter(i.MAX_SAMPLES),C=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:u,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:m,maxAttributes:p,maxVertexUniforms:T,maxVaryings:E,maxFragmentUniforms:y,maxSamples:S,samples:C}}function XT(i){const e=this;let t=null,n=0,s=!1,r=!1;const o=new Ts,a=new We,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,h){const f=u.length!==0||h||n!==0||s;return s=h,n=u.length,f},this.beginShadows=function(){r=!0,d(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,h){t=d(u,h,0)},this.setState=function(u,h,f){const g=u.clippingPlanes,v=u.clipIntersection,m=u.clipShadows,p=i.get(u);if(!s||g===null||g.length===0||r&&!m)r?d(null):l();else{const T=r?0:n,E=T*4;let y=p.clippingState||null;c.value=y,y=d(g,h,E,f);for(let S=0;S!==E;++S)y[S]=t[S];p.clippingState=y,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=T}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function d(u,h,f,g){const v=u!==null?u.length:0;let m=null;if(v!==0){if(m=c.value,g!==!0||m===null){const p=f+v*4,T=h.matrixWorldInverse;a.getNormalMatrix(T),(m===null||m.length<p)&&(m=new Float32Array(p));for(let E=0,y=f;E!==v;++E,y+=4)o.copy(u[E]).applyMatrix4(T,a),o.normal.toArray(m,y),m[y+3]=o.constant}c.value=m,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,m}}function KT(i){let e=new WeakMap;function t(o,a){return a===kl?o.mapping=vs:a===Il&&(o.mapping=Zs),o}function n(o){if(o&&o.isTexture){const a=o.mapping;if(a===kl||a===Il)if(e.has(o)){const c=e.get(o).texture;return t(c,o.mapping)}else{const c=o.image;if(c&&c.height>0){const l=new Em(c.height);return l.fromEquirectangularTexture(i,o),e.set(o,l),o.addEventListener("dispose",s),t(l.texture,o.mapping)}else return null}}return o}function s(o){const a=o.target;a.removeEventListener("dispose",s);const c=e.get(a);c!==void 0&&(e.delete(a),c.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}const rs=4,Fm=[.125,.215,.35,.446,.526,.582],Ms=20,YT=256,ua=new nu,Bm=new Fe;let su=null,ru=0,au=0,ou=!1;const JT=new U;class zm{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,s=100,r={}){const{size:o=256,position:a=JT}=r;su=this._renderer.getRenderTarget(),ru=this._renderer.getActiveCubeFace(),au=this._renderer.getActiveMipmapLevel(),ou=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,s,c,a),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Hm(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Gm(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(su,ru,au),this._renderer.xr.enabled=ou,e.scissorTest=!1,br(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===vs||e.mapping===Zs?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),su=this._renderer.getRenderTarget(),ru=this._renderer.getActiveCubeFace(),au=this._renderer.getActiveMipmapLevel(),ou=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:nn,minFilter:nn,generateMipmaps:!1,type:Ci,format:qn,colorSpace:er,depthBuffer:!1},s=Vm(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Vm(e,t,n);const{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=ZT(r)),this._blurMaterial=eC(r,e,t),this._ggxMaterial=QT(r,e,t)}return s}_compileMaterial(e){const t=new Sn(new hn,e);this._renderer.compile(t,ua)}_sceneToCubeUV(e,t,n,s,r){const c=new xn(90,1,t,n),l=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],u=this._renderer,h=u.autoClear,f=u.toneMapping;u.getClearColor(Bm),u.toneMapping=ii,u.autoClear=!1,u.state.buffers.depth.getReversed()&&(u.setRenderTarget(s),u.clearDepth(),u.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new Sn(new ca,new pm({name:"PMREM.Background",side:tn,depthWrite:!1,depthTest:!1})));const v=this._backgroundBox,m=v.material;let p=!1;const T=e.background;T?T.isColor&&(m.color.copy(T),e.background=null,p=!0):(m.color.copy(Bm),p=!0);for(let E=0;E<6;E++){const y=E%3;y===0?(c.up.set(0,l[E],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x+d[E],r.y,r.z)):y===1?(c.up.set(0,0,l[E]),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y+d[E],r.z)):(c.up.set(0,l[E],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y,r.z+d[E]));const S=this._cubeSize;br(s,y*S,E>2?S:0,S,S),u.setRenderTarget(s),p&&u.render(v,c),u.render(e,c)}u.toneMapping=f,u.autoClear=h,e.background=T}_textureToCubeUV(e,t){const n=this._renderer,s=e.mapping===vs||e.mapping===Zs;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=Hm()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Gm());const r=s?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=r;const a=r.uniforms;a.envMap.value=e;const c=this._cubeSize;br(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(o,ua)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let r=1;r<s;r++)this._applyGGXFilter(e,r-1,r);t.autoClear=n}_applyGGXFilter(e,t,n){const s=this._renderer,r=this._pingPongRenderTarget,o=this._ggxMaterial,a=this._lodMeshes[n];a.material=o;const c=o.uniforms,l=n/(this._lodMeshes.length-1),d=t/(this._lodMeshes.length-1),u=Math.sqrt(l*l-d*d),h=0+l*1.25,f=u*h,{_lodMax:g}=this,v=this._sizeLods[n],m=3*v*(n>g-rs?n-g+rs:0),p=4*(this._cubeSize-v);c.envMap.value=e.texture,c.roughness.value=f,c.mipInt.value=g-t,br(r,m,p,3*v,2*v),s.setRenderTarget(r),s.render(a,ua),c.envMap.value=r.texture,c.roughness.value=0,c.mipInt.value=g-n,br(e,m,p,3*v,2*v),s.setRenderTarget(e),s.render(a,ua)}_blur(e,t,n,s,r){const o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,s,"latitudinal",r),this._halfBlur(o,e,n,n,s,"longitudinal",r)}_halfBlur(e,t,n,s,r,o,a){const c=this._renderer,l=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&st("blur direction must be either latitudinal or longitudinal!");const d=3,u=this._lodMeshes[s];u.material=l;const h=l.uniforms,f=this._sizeLods[n]-1,g=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*Ms-1),v=r/g,m=isFinite(r)?1+Math.floor(d*v):Ms;m>Ms&&Be(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Ms}`);const p=[];let T=0;for(let w=0;w<Ms;++w){const k=w/v,_=Math.exp(-k*k/2);p.push(_),w===0?T+=_:w<m&&(T+=2*_)}for(let w=0;w<p.length;w++)p[w]=p[w]/T;h.envMap.value=e.texture,h.samples.value=m,h.weights.value=p,h.latitudinal.value=o==="latitudinal",a&&(h.poleAxis.value=a);const{_lodMax:E}=this;h.dTheta.value=g,h.mipInt.value=E-n;const y=this._sizeLods[s],S=3*y*(s>E-rs?s-E+rs:0),C=4*(this._cubeSize-y);br(t,S,C,3*y,2*y),c.setRenderTarget(t),c.render(u,ua)}}function ZT(i){const e=[],t=[],n=[];let s=i;const r=i-rs+1+Fm.length;for(let o=0;o<r;o++){const a=Math.pow(2,s);e.push(a);let c=1/a;o>i-rs?c=Fm[o-i+rs-1]:o===0&&(c=0),t.push(c);const l=1/(a-2),d=-l,u=1+l,h=[d,d,u,d,u,u,d,d,u,u,d,u],f=6,g=6,v=3,m=2,p=1,T=new Float32Array(v*g*f),E=new Float32Array(m*g*f),y=new Float32Array(p*g*f);for(let C=0;C<f;C++){const w=C%3*2/3-1,k=C>2?0:-1,_=[w,k,0,w+2/3,k,0,w+2/3,k+1,0,w,k,0,w+2/3,k+1,0,w,k+1,0];T.set(_,v*g*C),E.set(h,m*g*C);const x=[C,C,C,C,C,C];y.set(x,p*g*C)}const S=new hn;S.setAttribute("position",new _n(T,v)),S.setAttribute("uv",new _n(E,m)),S.setAttribute("faceIndex",new _n(y,p)),n.push(new Sn(S,null)),s>rs&&s--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function Vm(i,e,t){const n=new oi(i,e,t);return n.texture.mapping=oo,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function br(i,e,t,n,s){i.viewport.set(e,t,n,s),i.scissor.set(e,t,n,s)}function QT(i,e,t){return new en({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:YT,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Ho(),fragmentShader:`
3696
+ }`},ve={common:{diffuse:{value:new Fe(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new We},alphaMap:{value:null},alphaMapTransform:{value:new We},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new We}},envmap:{envMap:{value:null},envMapRotation:{value:new We},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 We}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new We}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new We},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new We},normalScale:{value:new tt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new We},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new We}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new We}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new We}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Fe(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 Fe(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new We},alphaTest:{value:0},uvTransform:{value:new We}},sprite:{diffuse:{value:new Fe(16777215)},opacity:{value:1},center:{value:new tt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new We},alphaMap:{value:null},alphaMapTransform:{value:new We},alphaTest:{value:0}}},ci={basic:{uniforms:pn([ve.common,ve.specularmap,ve.envmap,ve.aomap,ve.lightmap,ve.fog]),vertexShader:je.meshbasic_vert,fragmentShader:je.meshbasic_frag},lambert:{uniforms:pn([ve.common,ve.specularmap,ve.envmap,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.fog,ve.lights,{emissive:{value:new Fe(0)}}]),vertexShader:je.meshlambert_vert,fragmentShader:je.meshlambert_frag},phong:{uniforms:pn([ve.common,ve.specularmap,ve.envmap,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.fog,ve.lights,{emissive:{value:new Fe(0)},specular:{value:new Fe(1118481)},shininess:{value:30}}]),vertexShader:je.meshphong_vert,fragmentShader:je.meshphong_frag},standard:{uniforms:pn([ve.common,ve.envmap,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.roughnessmap,ve.metalnessmap,ve.fog,ve.lights,{emissive:{value:new Fe(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:je.meshphysical_vert,fragmentShader:je.meshphysical_frag},toon:{uniforms:pn([ve.common,ve.aomap,ve.lightmap,ve.emissivemap,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.gradientmap,ve.fog,ve.lights,{emissive:{value:new Fe(0)}}]),vertexShader:je.meshtoon_vert,fragmentShader:je.meshtoon_frag},matcap:{uniforms:pn([ve.common,ve.bumpmap,ve.normalmap,ve.displacementmap,ve.fog,{matcap:{value:null}}]),vertexShader:je.meshmatcap_vert,fragmentShader:je.meshmatcap_frag},points:{uniforms:pn([ve.points,ve.fog]),vertexShader:je.points_vert,fragmentShader:je.points_frag},dashed:{uniforms:pn([ve.common,ve.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:je.linedashed_vert,fragmentShader:je.linedashed_frag},depth:{uniforms:pn([ve.common,ve.displacementmap]),vertexShader:je.depth_vert,fragmentShader:je.depth_frag},normal:{uniforms:pn([ve.common,ve.bumpmap,ve.normalmap,ve.displacementmap,{opacity:{value:1}}]),vertexShader:je.meshnormal_vert,fragmentShader:je.meshnormal_frag},sprite:{uniforms:pn([ve.sprite,ve.fog]),vertexShader:je.sprite_vert,fragmentShader:je.sprite_frag},background:{uniforms:{uvTransform:{value:new We},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:je.background_vert,fragmentShader:je.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new We}},vertexShader:je.backgroundCube_vert,fragmentShader:je.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:je.cube_vert,fragmentShader:je.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:je.equirect_vert,fragmentShader:je.equirect_frag},distance:{uniforms:pn([ve.common,ve.displacementmap,{referencePosition:{value:new U},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:je.distance_vert,fragmentShader:je.distance_frag},shadow:{uniforms:pn([ve.lights,ve.fog,{color:{value:new Fe(0)},opacity:{value:1}}]),vertexShader:je.shadow_vert,fragmentShader:je.shadow_frag}};ci.physical={uniforms:pn([ci.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new We},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new We},clearcoatNormalScale:{value:new tt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new We},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new We},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new We},sheen:{value:0},sheenColor:{value:new Fe(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new We},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new We},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new We},transmissionSamplerSize:{value:new tt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new We},attenuationDistance:{value:0},attenuationColor:{value:new Fe(0)},specularColor:{value:new Fe(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new We},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new We},anisotropyVector:{value:new tt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new We}}]),vertexShader:je.meshphysical_vert,fragmentShader:je.meshphysical_frag};const Go={r:0,b:0,g:0},Es=new Ri,HT=new At;function WT(i,e,t,n,s,r,o){const a=new Fe(0);let c=r===!0?0:1,l,d,u=null,h=0,f=null;function g(E){let y=E.isScene===!0?E.background:null;return y&&y.isTexture&&(y=(E.backgroundBlurriness>0?t:e).get(y)),y}function v(E){let y=!1;const S=g(E);S===null?p(a,c):S&&S.isColor&&(p(S,1),y=!0);const C=i.xr.getEnvironmentBlendMode();C==="additive"?n.buffers.color.setClear(0,0,0,1,o):C==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,o),(i.autoClear||y)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function m(E,y){const S=g(y);S&&(S.isCubeTexture||S.mapping===oo)?(d===void 0&&(d=new xn(new ca(1,1,1),new tn({name:"BackgroundCubeMaterial",uniforms:mr(ci.backgroundCube.uniforms),vertexShader:ci.backgroundCube.vertexShader,fragmentShader:ci.backgroundCube.fragmentShader,side:nn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(C,w,k){this.matrixWorld.copyPosition(k.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(d)),Es.copy(y.backgroundRotation),Es.x*=-1,Es.y*=-1,Es.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(Es.y*=-1,Es.z*=-1),d.material.uniforms.envMap.value=S,d.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=y.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=y.backgroundIntensity,d.material.uniforms.backgroundRotation.value.setFromMatrix4(HT.makeRotationFromEuler(Es)),d.material.toneMapped=nt.getTransfer(S.colorSpace)!==lt,(u!==S||h!==S.version||f!==i.toneMapping)&&(d.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),d.layers.enableAll(),E.unshift(d,d.geometry,d.material,0,0,null)):S&&S.isTexture&&(l===void 0&&(l=new xn(new Vo(2,2),new tn({name:"BackgroundMaterial",uniforms:mr(ci.background.uniforms),vertexShader:ci.background.vertexShader,fragmentShader:ci.background.fragmentShader,side:_i,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(l)),l.material.uniforms.t2D.value=S,l.material.uniforms.backgroundIntensity.value=y.backgroundIntensity,l.material.toneMapped=nt.getTransfer(S.colorSpace)!==lt,S.matrixAutoUpdate===!0&&S.updateMatrix(),l.material.uniforms.uvTransform.value.copy(S.matrix),(u!==S||h!==S.version||f!==i.toneMapping)&&(l.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),l.layers.enableAll(),E.unshift(l,l.geometry,l.material,0,0,null))}function p(E,y){E.getRGB(Go,_m(i)),n.buffers.color.setClear(Go.r,Go.g,Go.b,y,o)}function T(){d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(E,y=1){a.set(E),c=y,p(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(E){c=E,p(a,c)},render:v,addToRenderList:m,dispose:T}}function qT(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=h(null);let r=s,o=!1;function a(x,R,O,F,q){let K=!1;const G=u(F,O,R);r!==G&&(r=G,l(r.object)),K=f(x,F,O,q),K&&g(x,F,O,q),q!==null&&e.update(q,i.ELEMENT_ARRAY_BUFFER),(K||o)&&(o=!1,y(x,R,O,F),q!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(q).buffer))}function c(){return i.createVertexArray()}function l(x){return i.bindVertexArray(x)}function d(x){return i.deleteVertexArray(x)}function u(x,R,O){const F=O.wireframe===!0;let q=n[x.id];q===void 0&&(q={},n[x.id]=q);let K=q[R.id];K===void 0&&(K={},q[R.id]=K);let G=K[F];return G===void 0&&(G=h(c()),K[F]=G),G}function h(x){const R=[],O=[],F=[];for(let q=0;q<t;q++)R[q]=0,O[q]=0,F[q]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:R,enabledAttributes:O,attributeDivisors:F,object:x,attributes:{},index:null}}function f(x,R,O,F){const q=r.attributes,K=R.attributes;let G=0;const W=O.getAttributes();for(const te in W)if(W[te].location>=0){const ue=q[te];let _e=K[te];if(_e===void 0&&(te==="instanceMatrix"&&x.instanceMatrix&&(_e=x.instanceMatrix),te==="instanceColor"&&x.instanceColor&&(_e=x.instanceColor)),ue===void 0||ue.attribute!==_e||_e&&ue.data!==_e.data)return!0;G++}return r.attributesNum!==G||r.index!==F}function g(x,R,O,F){const q={},K=R.attributes;let G=0;const W=O.getAttributes();for(const te in W)if(W[te].location>=0){let ue=K[te];ue===void 0&&(te==="instanceMatrix"&&x.instanceMatrix&&(ue=x.instanceMatrix),te==="instanceColor"&&x.instanceColor&&(ue=x.instanceColor));const _e={};_e.attribute=ue,ue&&ue.data&&(_e.data=ue.data),q[te]=_e,G++}r.attributes=q,r.attributesNum=G,r.index=F}function v(){const x=r.newAttributes;for(let R=0,O=x.length;R<O;R++)x[R]=0}function m(x){p(x,0)}function p(x,R){const O=r.newAttributes,F=r.enabledAttributes,q=r.attributeDivisors;O[x]=1,F[x]===0&&(i.enableVertexAttribArray(x),F[x]=1),q[x]!==R&&(i.vertexAttribDivisor(x,R),q[x]=R)}function T(){const x=r.newAttributes,R=r.enabledAttributes;for(let O=0,F=R.length;O<F;O++)R[O]!==x[O]&&(i.disableVertexAttribArray(O),R[O]=0)}function E(x,R,O,F,q,K,G){G===!0?i.vertexAttribIPointer(x,R,O,q,K):i.vertexAttribPointer(x,R,O,F,q,K)}function y(x,R,O,F){v();const q=F.attributes,K=O.getAttributes(),G=R.defaultAttributeValues;for(const W in K){const te=K[W];if(te.location>=0){let ye=q[W];if(ye===void 0&&(W==="instanceMatrix"&&x.instanceMatrix&&(ye=x.instanceMatrix),W==="instanceColor"&&x.instanceColor&&(ye=x.instanceColor)),ye!==void 0){const ue=ye.normalized,_e=ye.itemSize,Ge=e.get(ye);if(Ge===void 0)continue;const Ve=Ge.buffer,Mt=Ge.type,pt=Ge.bytesPerElement,Y=Mt===i.INT||Mt===i.UNSIGNED_INT||ye.gpuType===Ol;if(ye.isInterleavedBufferAttribute){const ie=ye.data,Ce=ie.stride,qe=ye.offset;if(ie.isInstancedInterleavedBuffer){for(let we=0;we<te.locationSize;we++)p(te.location+we,ie.meshPerAttribute);x.isInstancedMesh!==!0&&F._maxInstanceCount===void 0&&(F._maxInstanceCount=ie.meshPerAttribute*ie.count)}else for(let we=0;we<te.locationSize;we++)m(te.location+we);i.bindBuffer(i.ARRAY_BUFFER,Ve);for(let we=0;we<te.locationSize;we++)E(te.location+we,_e/te.locationSize,Mt,ue,Ce*pt,(qe+_e/te.locationSize*we)*pt,Y)}else{if(ye.isInstancedBufferAttribute){for(let ie=0;ie<te.locationSize;ie++)p(te.location+ie,ye.meshPerAttribute);x.isInstancedMesh!==!0&&F._maxInstanceCount===void 0&&(F._maxInstanceCount=ye.meshPerAttribute*ye.count)}else for(let ie=0;ie<te.locationSize;ie++)m(te.location+ie);i.bindBuffer(i.ARRAY_BUFFER,Ve);for(let ie=0;ie<te.locationSize;ie++)E(te.location+ie,_e/te.locationSize,Mt,ue,_e*pt,_e/te.locationSize*ie*pt,Y)}}else if(G!==void 0){const ue=G[W];if(ue!==void 0)switch(ue.length){case 2:i.vertexAttrib2fv(te.location,ue);break;case 3:i.vertexAttrib3fv(te.location,ue);break;case 4:i.vertexAttrib4fv(te.location,ue);break;default:i.vertexAttrib1fv(te.location,ue)}}}}T()}function S(){k();for(const x in n){const R=n[x];for(const O in R){const F=R[O];for(const q in F)d(F[q].object),delete F[q];delete R[O]}delete n[x]}}function C(x){if(n[x.id]===void 0)return;const R=n[x.id];for(const O in R){const F=R[O];for(const q in F)d(F[q].object),delete F[q];delete R[O]}delete n[x.id]}function w(x){for(const R in n){const O=n[R];if(O[x.id]===void 0)continue;const F=O[x.id];for(const q in F)d(F[q].object),delete F[q];delete O[x.id]}}function k(){_(),o=!0,r!==s&&(r=s,l(r.object))}function _(){s.geometry=null,s.program=null,s.wireframe=!1}return{setup:a,reset:k,resetDefaultState:_,dispose:S,releaseStatesOfGeometry:C,releaseStatesOfProgram:w,initAttributes:v,enableAttribute:m,disableUnusedAttributes:T}}function jT(i,e,t){let n;function s(l){n=l}function r(l,d){i.drawArrays(n,l,d),t.update(d,n,1)}function o(l,d,u){u!==0&&(i.drawArraysInstanced(n,l,d,u),t.update(d,n,u))}function a(l,d,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,d,0,u);let f=0;for(let g=0;g<u;g++)f+=d[g];t.update(f,n,1)}function c(l,d,u,h){if(u===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let g=0;g<l.length;g++)o(l[g],d[g],h[g]);else{f.multiDrawArraysInstancedWEBGL(n,l,0,d,0,h,0,u);let g=0;for(let v=0;v<u;v++)g+=d[v]*h[v];t.update(g,n,1)}}this.setMode=s,this.render=r,this.renderInstances=o,this.renderMultiDraw=a,this.renderMultiDrawInstances=c}function $T(i,e,t,n){let s;function r(){if(s!==void 0)return s;if(e.has("EXT_texture_filter_anisotropic")===!0){const w=e.get("EXT_texture_filter_anisotropic");s=i.getParameter(w.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s}function o(w){return!(w!==qn&&n.convert(w)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function a(w){const k=w===Ci&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(w!==wn&&n.convert(w)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE)&&w!==ri&&!k)}function c(w){if(w==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";w="mediump"}return w==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const d=c(l);d!==l&&(Be("WebGLRenderer:",l,"not supported, using",d,"instead."),l=d);const u=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),g=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),p=i.getParameter(i.MAX_VERTEX_ATTRIBS),T=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),E=i.getParameter(i.MAX_VARYING_VECTORS),y=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),S=i.getParameter(i.MAX_SAMPLES),C=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:u,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:m,maxAttributes:p,maxVertexUniforms:T,maxVaryings:E,maxFragmentUniforms:y,maxSamples:S,samples:C}}function XT(i){const e=this;let t=null,n=0,s=!1,r=!1;const o=new Ts,a=new We,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,h){const f=u.length!==0||h||n!==0||s;return s=h,n=u.length,f},this.beginShadows=function(){r=!0,d(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,h){t=d(u,h,0)},this.setState=function(u,h,f){const g=u.clippingPlanes,v=u.clipIntersection,m=u.clipShadows,p=i.get(u);if(!s||g===null||g.length===0||r&&!m)r?d(null):l();else{const T=r?0:n,E=T*4;let y=p.clippingState||null;c.value=y,y=d(g,h,E,f);for(let S=0;S!==E;++S)y[S]=t[S];p.clippingState=y,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=T}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function d(u,h,f,g){const v=u!==null?u.length:0;let m=null;if(v!==0){if(m=c.value,g!==!0||m===null){const p=f+v*4,T=h.matrixWorldInverse;a.getNormalMatrix(T),(m===null||m.length<p)&&(m=new Float32Array(p));for(let E=0,y=f;E!==v;++E,y+=4)o.copy(u[E]).applyMatrix4(T,a),o.normal.toArray(m,y),m[y+3]=o.constant}c.value=m,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,m}}function KT(i){let e=new WeakMap;function t(o,a){return a===kl?o.mapping=vs:a===Il&&(o.mapping=Zs),o}function n(o){if(o&&o.isTexture){const a=o.mapping;if(a===kl||a===Il)if(e.has(o)){const c=e.get(o).texture;return t(c,o.mapping)}else{const c=o.image;if(c&&c.height>0){const l=new Em(c.height);return l.fromEquirectangularTexture(i,o),e.set(o,l),o.addEventListener("dispose",s),t(l.texture,o.mapping)}else return null}}return o}function s(o){const a=o.target;a.removeEventListener("dispose",s);const c=e.get(a);c!==void 0&&(e.delete(a),c.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}const rs=4,Fm=[.125,.215,.35,.446,.526,.582],Ms=20,YT=256,ua=new nu,Bm=new Fe;let su=null,ru=0,au=0,ou=!1;const JT=new U;class zm{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,s=100,r={}){const{size:o=256,position:a=JT}=r;su=this._renderer.getRenderTarget(),ru=this._renderer.getActiveCubeFace(),au=this._renderer.getActiveMipmapLevel(),ou=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,s,c,a),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Hm(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Gm(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(su,ru,au),this._renderer.xr.enabled=ou,e.scissorTest=!1,br(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===vs||e.mapping===Zs?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),su=this._renderer.getRenderTarget(),ru=this._renderer.getActiveCubeFace(),au=this._renderer.getActiveMipmapLevel(),ou=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:sn,minFilter:sn,generateMipmaps:!1,type:Ci,format:qn,colorSpace:er,depthBuffer:!1},s=Vm(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Vm(e,t,n);const{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=ZT(r)),this._blurMaterial=eC(r,e,t),this._ggxMaterial=QT(r,e,t)}return s}_compileMaterial(e){const t=new xn(new fn,e);this._renderer.compile(t,ua)}_sceneToCubeUV(e,t,n,s,r){const c=new Tn(90,1,t,n),l=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],u=this._renderer,h=u.autoClear,f=u.toneMapping;u.getClearColor(Bm),u.toneMapping=ii,u.autoClear=!1,u.state.buffers.depth.getReversed()&&(u.setRenderTarget(s),u.clearDepth(),u.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new xn(new ca,new pm({name:"PMREM.Background",side:nn,depthWrite:!1,depthTest:!1})));const v=this._backgroundBox,m=v.material;let p=!1;const T=e.background;T?T.isColor&&(m.color.copy(T),e.background=null,p=!0):(m.color.copy(Bm),p=!0);for(let E=0;E<6;E++){const y=E%3;y===0?(c.up.set(0,l[E],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x+d[E],r.y,r.z)):y===1?(c.up.set(0,0,l[E]),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y+d[E],r.z)):(c.up.set(0,l[E],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y,r.z+d[E]));const S=this._cubeSize;br(s,y*S,E>2?S:0,S,S),u.setRenderTarget(s),p&&u.render(v,c),u.render(e,c)}u.toneMapping=f,u.autoClear=h,e.background=T}_textureToCubeUV(e,t){const n=this._renderer,s=e.mapping===vs||e.mapping===Zs;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=Hm()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Gm());const r=s?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=r;const a=r.uniforms;a.envMap.value=e;const c=this._cubeSize;br(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(o,ua)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let r=1;r<s;r++)this._applyGGXFilter(e,r-1,r);t.autoClear=n}_applyGGXFilter(e,t,n){const s=this._renderer,r=this._pingPongRenderTarget,o=this._ggxMaterial,a=this._lodMeshes[n];a.material=o;const c=o.uniforms,l=n/(this._lodMeshes.length-1),d=t/(this._lodMeshes.length-1),u=Math.sqrt(l*l-d*d),h=0+l*1.25,f=u*h,{_lodMax:g}=this,v=this._sizeLods[n],m=3*v*(n>g-rs?n-g+rs:0),p=4*(this._cubeSize-v);c.envMap.value=e.texture,c.roughness.value=f,c.mipInt.value=g-t,br(r,m,p,3*v,2*v),s.setRenderTarget(r),s.render(a,ua),c.envMap.value=r.texture,c.roughness.value=0,c.mipInt.value=g-n,br(e,m,p,3*v,2*v),s.setRenderTarget(e),s.render(a,ua)}_blur(e,t,n,s,r){const o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,s,"latitudinal",r),this._halfBlur(o,e,n,n,s,"longitudinal",r)}_halfBlur(e,t,n,s,r,o,a){const c=this._renderer,l=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&st("blur direction must be either latitudinal or longitudinal!");const d=3,u=this._lodMeshes[s];u.material=l;const h=l.uniforms,f=this._sizeLods[n]-1,g=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*Ms-1),v=r/g,m=isFinite(r)?1+Math.floor(d*v):Ms;m>Ms&&Be(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Ms}`);const p=[];let T=0;for(let w=0;w<Ms;++w){const k=w/v,_=Math.exp(-k*k/2);p.push(_),w===0?T+=_:w<m&&(T+=2*_)}for(let w=0;w<p.length;w++)p[w]=p[w]/T;h.envMap.value=e.texture,h.samples.value=m,h.weights.value=p,h.latitudinal.value=o==="latitudinal",a&&(h.poleAxis.value=a);const{_lodMax:E}=this;h.dTheta.value=g,h.mipInt.value=E-n;const y=this._sizeLods[s],S=3*y*(s>E-rs?s-E+rs:0),C=4*(this._cubeSize-y);br(t,S,C,3*y,2*y),c.setRenderTarget(t),c.render(u,ua)}}function ZT(i){const e=[],t=[],n=[];let s=i;const r=i-rs+1+Fm.length;for(let o=0;o<r;o++){const a=Math.pow(2,s);e.push(a);let c=1/a;o>i-rs?c=Fm[o-i+rs-1]:o===0&&(c=0),t.push(c);const l=1/(a-2),d=-l,u=1+l,h=[d,d,u,d,u,u,d,d,u,u,d,u],f=6,g=6,v=3,m=2,p=1,T=new Float32Array(v*g*f),E=new Float32Array(m*g*f),y=new Float32Array(p*g*f);for(let C=0;C<f;C++){const w=C%3*2/3-1,k=C>2?0:-1,_=[w,k,0,w+2/3,k,0,w+2/3,k+1,0,w,k,0,w+2/3,k+1,0,w,k+1,0];T.set(_,v*g*C),E.set(h,m*g*C);const x=[C,C,C,C,C,C];y.set(x,p*g*C)}const S=new fn;S.setAttribute("position",new Sn(T,v)),S.setAttribute("uv",new Sn(E,m)),S.setAttribute("faceIndex",new Sn(y,p)),n.push(new xn(S,null)),s>rs&&s--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function Vm(i,e,t){const n=new oi(i,e,t);return n.texture.mapping=oo,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function br(i,e,t,n,s){i.viewport.set(e,t,n,s),i.scissor.set(e,t,n,s)}function QT(i,e,t){return new tn({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:YT,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Ho(),fragmentShader:`
3697
3697
 
3698
3698
  precision highp float;
3699
3699
  precision highp int;
@@ -3801,7 +3801,7 @@ void main() {
3801
3801
 
3802
3802
  gl_FragColor = vec4(prefilteredColor, 1.0);
3803
3803
  }
3804
- `,blending:xi,depthTest:!1,depthWrite:!1})}function eC(i,e,t){const n=new Float32Array(Ms),s=new U(0,1,0);return new en({name:"SphericalGaussianBlur",defines:{n:Ms,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Ho(),fragmentShader:`
3804
+ `,blending:xi,depthTest:!1,depthWrite:!1})}function eC(i,e,t){const n=new Float32Array(Ms),s=new U(0,1,0);return new tn({name:"SphericalGaussianBlur",defines:{n:Ms,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Ho(),fragmentShader:`
3805
3805
 
3806
3806
  precision mediump float;
3807
3807
  precision mediump int;
@@ -3861,7 +3861,7 @@ void main() {
3861
3861
  }
3862
3862
 
3863
3863
  }
3864
- `,blending:xi,depthTest:!1,depthWrite:!1})}function Gm(){return new en({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Ho(),fragmentShader:`
3864
+ `,blending:xi,depthTest:!1,depthWrite:!1})}function Gm(){return new tn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Ho(),fragmentShader:`
3865
3865
 
3866
3866
  precision mediump float;
3867
3867
  precision mediump int;
@@ -3880,7 +3880,7 @@ void main() {
3880
3880
  gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
3881
3881
 
3882
3882
  }
3883
- `,blending:xi,depthTest:!1,depthWrite:!1})}function Hm(){return new en({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ho(),fragmentShader:`
3883
+ `,blending:xi,depthTest:!1,depthWrite:!1})}function Hm(){return new tn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ho(),fragmentShader:`
3884
3884
 
3885
3885
  precision mediump float;
3886
3886
  precision mediump int;
@@ -3951,7 +3951,7 @@ void main() {
3951
3951
  gl_Position = vec4( position, 1.0 );
3952
3952
 
3953
3953
  }
3954
- `}function tC(i){let e=new WeakMap,t=null;function n(a){if(a&&a.isTexture){const c=a.mapping,l=c===kl||c===Il,d=c===vs||c===Zs;if(l||d){let u=e.get(a);const h=u!==void 0?u.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==h)return t===null&&(t=new zm(i)),u=l?t.fromEquirectangular(a,u):t.fromCubemap(a,u),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),u.texture;if(u!==void 0)return u.texture;{const f=a.image;return l&&f&&f.height>0||d&&f&&s(f)?(t===null&&(t=new zm(i)),u=l?t.fromEquirectangular(a):t.fromCubemap(a),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),a.addEventListener("dispose",r),u.texture):null}}}return a}function s(a){let c=0;const l=6;for(let d=0;d<l;d++)a[d]!==void 0&&c++;return c===l}function r(a){const c=a.target;c.removeEventListener("dispose",r);const l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function o(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:o}}function nC(i){const e={};function t(n){if(e[n]!==void 0)return e[n];const s=i.getExtension(n);return e[n]=s,s}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){const s=t(n);return s===null&&Zr("WebGLRenderer: "+n+" extension not supported."),s}}}function iC(i,e,t,n){const s={},r=new WeakMap;function o(u){const h=u.target;h.index!==null&&e.remove(h.index);for(const g in h.attributes)e.remove(h.attributes[g]);h.removeEventListener("dispose",o),delete s[h.id];const f=r.get(h);f&&(e.remove(f),r.delete(h)),n.releaseStatesOfGeometry(h),h.isInstancedBufferGeometry===!0&&delete h._maxInstanceCount,t.memory.geometries--}function a(u,h){return s[h.id]===!0||(h.addEventListener("dispose",o),s[h.id]=!0,t.memory.geometries++),h}function c(u){const h=u.attributes;for(const f in h)e.update(h[f],i.ARRAY_BUFFER)}function l(u){const h=[],f=u.index,g=u.attributes.position;let v=0;if(f!==null){const T=f.array;v=f.version;for(let E=0,y=T.length;E<y;E+=3){const S=T[E+0],C=T[E+1],w=T[E+2];h.push(S,C,C,w,w,S)}}else if(g!==void 0){const T=g.array;v=g.version;for(let E=0,y=T.length/3-1;E<y;E+=3){const S=E+0,C=E+1,w=E+2;h.push(S,C,C,w,w,S)}}else return;const m=new(Jp(h)?gm:mm)(h,1);m.version=v;const p=r.get(u);p&&e.remove(p),r.set(u,m)}function d(u){const h=r.get(u);if(h){const f=u.index;f!==null&&h.version<f.version&&l(u)}else l(u);return r.get(u)}return{get:a,update:c,getWireframeAttribute:d}}function sC(i,e,t){let n;function s(h){n=h}let r,o;function a(h){r=h.type,o=h.bytesPerElement}function c(h,f){i.drawElements(n,f,r,h*o),t.update(f,n,1)}function l(h,f,g){g!==0&&(i.drawElementsInstanced(n,f,r,h*o,g),t.update(f,n,g))}function d(h,f,g){if(g===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,r,h,0,g);let m=0;for(let p=0;p<g;p++)m+=f[p];t.update(m,n,1)}function u(h,f,g,v){if(g===0)return;const m=e.get("WEBGL_multi_draw");if(m===null)for(let p=0;p<h.length;p++)l(h[p]/o,f[p],v[p]);else{m.multiDrawElementsInstancedWEBGL(n,f,0,r,h,0,v,0,g);let p=0;for(let T=0;T<g;T++)p+=f[T]*v[T];t.update(p,n,1)}}this.setMode=s,this.setIndex=a,this.render=c,this.renderInstances=l,this.renderMultiDraw=d,this.renderMultiDrawInstances=u}function rC(i){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,o,a){switch(t.calls++,o){case i.TRIANGLES:t.triangles+=a*(r/3);break;case i.LINES:t.lines+=a*(r/2);break;case i.LINE_STRIP:t.lines+=a*(r-1);break;case i.LINE_LOOP:t.lines+=a*r;break;case i.POINTS:t.points+=a*r;break;default:st("WebGLInfo: Unknown draw mode:",o);break}}function s(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:s,update:n}}function aC(i,e,t){const n=new WeakMap,s=new Dt;function r(o,a,c){const l=o.morphTargetInfluences,d=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,u=d!==void 0?d.length:0;let h=n.get(a);if(h===void 0||h.count!==u){let _=function(){w.dispose(),n.delete(a),a.removeEventListener("dispose",_)};h!==void 0&&h.texture.dispose();const f=a.morphAttributes.position!==void 0,g=a.morphAttributes.normal!==void 0,v=a.morphAttributes.color!==void 0,m=a.morphAttributes.position||[],p=a.morphAttributes.normal||[],T=a.morphAttributes.color||[];let E=0;f===!0&&(E=1),g===!0&&(E=2),v===!0&&(E=3);let y=a.attributes.position.count*E,S=1;y>e.maxTextureSize&&(S=Math.ceil(y/e.maxTextureSize),y=e.maxTextureSize);const C=new Float32Array(y*S*4*u),w=new im(C,y,S,u);w.type=ri,w.needsUpdate=!0;const k=E*4;for(let x=0;x<u;x++){const R=m[x],O=p[x],F=T[x],q=y*S*4*x;for(let K=0;K<R.count;K++){const G=K*k;f===!0&&(s.fromBufferAttribute(R,K),C[q+G+0]=s.x,C[q+G+1]=s.y,C[q+G+2]=s.z,C[q+G+3]=0),g===!0&&(s.fromBufferAttribute(O,K),C[q+G+4]=s.x,C[q+G+5]=s.y,C[q+G+6]=s.z,C[q+G+7]=0),v===!0&&(s.fromBufferAttribute(F,K),C[q+G+8]=s.x,C[q+G+9]=s.y,C[q+G+10]=s.z,C[q+G+11]=F.itemSize===4?s.w:1)}}h={count:u,texture:w,size:new tt(y,S)},n.set(a,h),a.addEventListener("dispose",_)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(i,"morphTexture",o.morphTexture,t);else{let f=0;for(let v=0;v<l.length;v++)f+=l[v];const g=a.morphTargetsRelative?1:1-f;c.getUniforms().setValue(i,"morphTargetBaseInfluence",g),c.getUniforms().setValue(i,"morphTargetInfluences",l)}c.getUniforms().setValue(i,"morphTargetsTexture",h.texture,t),c.getUniforms().setValue(i,"morphTargetsTextureSize",h.size)}return{update:r}}function oC(i,e,t,n){let s=new WeakMap;function r(c){const l=n.render.frame,d=c.geometry,u=e.get(c,d);if(s.get(u)!==l&&(e.update(u),s.set(u,l)),c.isInstancedMesh&&(c.hasEventListener("dispose",a)===!1&&c.addEventListener("dispose",a),s.get(c)!==l&&(t.update(c.instanceMatrix,i.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,i.ARRAY_BUFFER),s.set(c,l))),c.isSkinnedMesh){const h=c.skeleton;s.get(h)!==l&&(h.update(),s.set(h,l))}return u}function o(){s=new WeakMap}function a(c){const l=c.target;l.removeEventListener("dispose",a),t.remove(l.instanceMatrix),l.instanceColor!==null&&t.remove(l.instanceColor)}return{update:r,dispose:o}}const cC={[Dp]:"LINEAR_TONE_MAPPING",[Lp]:"REINHARD_TONE_MAPPING",[Np]:"CINEON_TONE_MAPPING",[Op]:"ACES_FILMIC_TONE_MAPPING",[Fp]:"AGX_TONE_MAPPING",[Bp]:"NEUTRAL_TONE_MAPPING",[Up]:"CUSTOM_TONE_MAPPING"};function lC(i,e,t,n,s){const r=new oi(e,t,{type:i,depthBuffer:n,stencilBuffer:s}),o=new oi(e,t,{type:Ci,depthBuffer:!1,stencilBuffer:!1}),a=new hn;a.setAttribute("position",new an([-1,3,0,-1,-1,0,3,-1,0],3)),a.setAttribute("uv",new an([0,2,0,0,2,0],2));const c=new LS({uniforms:{tDiffuse:{value:null}},vertexShader:`
3954
+ `}function tC(i){let e=new WeakMap,t=null;function n(a){if(a&&a.isTexture){const c=a.mapping,l=c===kl||c===Il,d=c===vs||c===Zs;if(l||d){let u=e.get(a);const h=u!==void 0?u.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==h)return t===null&&(t=new zm(i)),u=l?t.fromEquirectangular(a,u):t.fromCubemap(a,u),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),u.texture;if(u!==void 0)return u.texture;{const f=a.image;return l&&f&&f.height>0||d&&f&&s(f)?(t===null&&(t=new zm(i)),u=l?t.fromEquirectangular(a):t.fromCubemap(a),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),a.addEventListener("dispose",r),u.texture):null}}}return a}function s(a){let c=0;const l=6;for(let d=0;d<l;d++)a[d]!==void 0&&c++;return c===l}function r(a){const c=a.target;c.removeEventListener("dispose",r);const l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function o(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:o}}function nC(i){const e={};function t(n){if(e[n]!==void 0)return e[n];const s=i.getExtension(n);return e[n]=s,s}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){const s=t(n);return s===null&&Zr("WebGLRenderer: "+n+" extension not supported."),s}}}function iC(i,e,t,n){const s={},r=new WeakMap;function o(u){const h=u.target;h.index!==null&&e.remove(h.index);for(const g in h.attributes)e.remove(h.attributes[g]);h.removeEventListener("dispose",o),delete s[h.id];const f=r.get(h);f&&(e.remove(f),r.delete(h)),n.releaseStatesOfGeometry(h),h.isInstancedBufferGeometry===!0&&delete h._maxInstanceCount,t.memory.geometries--}function a(u,h){return s[h.id]===!0||(h.addEventListener("dispose",o),s[h.id]=!0,t.memory.geometries++),h}function c(u){const h=u.attributes;for(const f in h)e.update(h[f],i.ARRAY_BUFFER)}function l(u){const h=[],f=u.index,g=u.attributes.position;let v=0;if(f!==null){const T=f.array;v=f.version;for(let E=0,y=T.length;E<y;E+=3){const S=T[E+0],C=T[E+1],w=T[E+2];h.push(S,C,C,w,w,S)}}else if(g!==void 0){const T=g.array;v=g.version;for(let E=0,y=T.length/3-1;E<y;E+=3){const S=E+0,C=E+1,w=E+2;h.push(S,C,C,w,w,S)}}else return;const m=new(Jp(h)?gm:mm)(h,1);m.version=v;const p=r.get(u);p&&e.remove(p),r.set(u,m)}function d(u){const h=r.get(u);if(h){const f=u.index;f!==null&&h.version<f.version&&l(u)}else l(u);return r.get(u)}return{get:a,update:c,getWireframeAttribute:d}}function sC(i,e,t){let n;function s(h){n=h}let r,o;function a(h){r=h.type,o=h.bytesPerElement}function c(h,f){i.drawElements(n,f,r,h*o),t.update(f,n,1)}function l(h,f,g){g!==0&&(i.drawElementsInstanced(n,f,r,h*o,g),t.update(f,n,g))}function d(h,f,g){if(g===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,r,h,0,g);let m=0;for(let p=0;p<g;p++)m+=f[p];t.update(m,n,1)}function u(h,f,g,v){if(g===0)return;const m=e.get("WEBGL_multi_draw");if(m===null)for(let p=0;p<h.length;p++)l(h[p]/o,f[p],v[p]);else{m.multiDrawElementsInstancedWEBGL(n,f,0,r,h,0,v,0,g);let p=0;for(let T=0;T<g;T++)p+=f[T]*v[T];t.update(p,n,1)}}this.setMode=s,this.setIndex=a,this.render=c,this.renderInstances=l,this.renderMultiDraw=d,this.renderMultiDrawInstances=u}function rC(i){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,o,a){switch(t.calls++,o){case i.TRIANGLES:t.triangles+=a*(r/3);break;case i.LINES:t.lines+=a*(r/2);break;case i.LINE_STRIP:t.lines+=a*(r-1);break;case i.LINE_LOOP:t.lines+=a*r;break;case i.POINTS:t.points+=a*r;break;default:st("WebGLInfo: Unknown draw mode:",o);break}}function s(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:s,update:n}}function aC(i,e,t){const n=new WeakMap,s=new Dt;function r(o,a,c){const l=o.morphTargetInfluences,d=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,u=d!==void 0?d.length:0;let h=n.get(a);if(h===void 0||h.count!==u){let _=function(){w.dispose(),n.delete(a),a.removeEventListener("dispose",_)};h!==void 0&&h.texture.dispose();const f=a.morphAttributes.position!==void 0,g=a.morphAttributes.normal!==void 0,v=a.morphAttributes.color!==void 0,m=a.morphAttributes.position||[],p=a.morphAttributes.normal||[],T=a.morphAttributes.color||[];let E=0;f===!0&&(E=1),g===!0&&(E=2),v===!0&&(E=3);let y=a.attributes.position.count*E,S=1;y>e.maxTextureSize&&(S=Math.ceil(y/e.maxTextureSize),y=e.maxTextureSize);const C=new Float32Array(y*S*4*u),w=new im(C,y,S,u);w.type=ri,w.needsUpdate=!0;const k=E*4;for(let x=0;x<u;x++){const R=m[x],O=p[x],F=T[x],q=y*S*4*x;for(let K=0;K<R.count;K++){const G=K*k;f===!0&&(s.fromBufferAttribute(R,K),C[q+G+0]=s.x,C[q+G+1]=s.y,C[q+G+2]=s.z,C[q+G+3]=0),g===!0&&(s.fromBufferAttribute(O,K),C[q+G+4]=s.x,C[q+G+5]=s.y,C[q+G+6]=s.z,C[q+G+7]=0),v===!0&&(s.fromBufferAttribute(F,K),C[q+G+8]=s.x,C[q+G+9]=s.y,C[q+G+10]=s.z,C[q+G+11]=F.itemSize===4?s.w:1)}}h={count:u,texture:w,size:new tt(y,S)},n.set(a,h),a.addEventListener("dispose",_)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(i,"morphTexture",o.morphTexture,t);else{let f=0;for(let v=0;v<l.length;v++)f+=l[v];const g=a.morphTargetsRelative?1:1-f;c.getUniforms().setValue(i,"morphTargetBaseInfluence",g),c.getUniforms().setValue(i,"morphTargetInfluences",l)}c.getUniforms().setValue(i,"morphTargetsTexture",h.texture,t),c.getUniforms().setValue(i,"morphTargetsTextureSize",h.size)}return{update:r}}function oC(i,e,t,n){let s=new WeakMap;function r(c){const l=n.render.frame,d=c.geometry,u=e.get(c,d);if(s.get(u)!==l&&(e.update(u),s.set(u,l)),c.isInstancedMesh&&(c.hasEventListener("dispose",a)===!1&&c.addEventListener("dispose",a),s.get(c)!==l&&(t.update(c.instanceMatrix,i.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,i.ARRAY_BUFFER),s.set(c,l))),c.isSkinnedMesh){const h=c.skeleton;s.get(h)!==l&&(h.update(),s.set(h,l))}return u}function o(){s=new WeakMap}function a(c){const l=c.target;l.removeEventListener("dispose",a),t.remove(l.instanceMatrix),l.instanceColor!==null&&t.remove(l.instanceColor)}return{update:r,dispose:o}}const cC={[Dp]:"LINEAR_TONE_MAPPING",[Lp]:"REINHARD_TONE_MAPPING",[Np]:"CINEON_TONE_MAPPING",[Op]:"ACES_FILMIC_TONE_MAPPING",[Fp]:"AGX_TONE_MAPPING",[Bp]:"NEUTRAL_TONE_MAPPING",[Up]:"CUSTOM_TONE_MAPPING"};function lC(i,e,t,n,s){const r=new oi(e,t,{type:i,depthBuffer:n,stencilBuffer:s}),o=new oi(e,t,{type:Ci,depthBuffer:!1,stencilBuffer:!1}),a=new fn;a.setAttribute("position",new on([-1,3,0,-1,-1,0,3,-1,0],3)),a.setAttribute("uv",new on([0,2,0,0,2,0],2));const c=new LS({uniforms:{tDiffuse:{value:null}},vertexShader:`
3955
3955
  precision highp float;
3956
3956
 
3957
3957
  uniform mat4 modelViewMatrix;
@@ -3997,7 +3997,7 @@ void main() {
3997
3997
  #ifdef SRGB_TRANSFER
3998
3998
  gl_FragColor = sRGBTransferOETF( gl_FragColor );
3999
3999
  #endif
4000
- }`,depthTest:!1,depthWrite:!1}),l=new Sn(a,c),d=new nu(-1,1,1,-1,0,1);let u=null,h=null,f=!1,g,v=null,m=[],p=!1;this.setSize=function(T,E){r.setSize(T,E),o.setSize(T,E);for(let y=0;y<m.length;y++){const S=m[y];S.setSize&&S.setSize(T,E)}},this.setEffects=function(T){m=T,p=m.length>0&&m[0].isRenderPass===!0;const E=r.width,y=r.height;for(let S=0;S<m.length;S++){const C=m[S];C.setSize&&C.setSize(E,y)}},this.begin=function(T,E){if(f||T.toneMapping===ii&&m.length===0)return!1;if(v=E,E!==null){const y=E.width,S=E.height;(r.width!==y||r.height!==S)&&this.setSize(y,S)}return p===!1&&T.setRenderTarget(r),g=T.toneMapping,T.toneMapping=ii,!0},this.hasRenderPass=function(){return p},this.end=function(T,E){T.toneMapping=g,f=!0;let y=r,S=o;for(let C=0;C<m.length;C++){const w=m[C];if(w.enabled!==!1&&(w.render(T,S,y,E),w.needsSwap!==!1)){const k=y;y=S,S=k}}if(u!==T.outputColorSpace||h!==T.toneMapping){u=T.outputColorSpace,h=T.toneMapping,c.defines={},nt.getTransfer(u)===lt&&(c.defines.SRGB_TRANSFER="");const C=cC[h];C&&(c.defines[C]=""),c.needsUpdate=!0}c.uniforms.tDiffuse.value=y.texture,T.setRenderTarget(v),T.render(l,d),v=null,f=!1},this.isCompositing=function(){return f},this.dispose=function(){r.dispose(),o.dispose(),a.dispose(),c.dispose()}}const Wm=new un,cu=new da(1,1),qm=new im,jm=new oS,$m=new Cm,Xm=[],Km=[],Ym=new Float32Array(16),Jm=new Float32Array(9),Zm=new Float32Array(4);function _r(i,e,t){const n=i[0];if(n<=0||n>0)return i;const s=e*t;let r=Xm[s];if(r===void 0&&(r=new Float32Array(s),Xm[s]=r),e!==0){n.toArray(r,0);for(let o=1,a=0;o!==e;++o)a+=t,i[o].toArray(r,a)}return r}function Wt(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function qt(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function Wo(i,e){let t=Km[e];t===void 0&&(t=new Int32Array(e),Km[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function dC(i,e){const t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function uC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Wt(t,e))return;i.uniform2fv(this.addr,e),qt(t,e)}}function hC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(Wt(t,e))return;i.uniform3fv(this.addr,e),qt(t,e)}}function fC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Wt(t,e))return;i.uniform4fv(this.addr,e),qt(t,e)}}function pC(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Wt(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),qt(t,e)}else{if(Wt(t,n))return;Zm.set(n),i.uniformMatrix2fv(this.addr,!1,Zm),qt(t,n)}}function mC(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Wt(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),qt(t,e)}else{if(Wt(t,n))return;Jm.set(n),i.uniformMatrix3fv(this.addr,!1,Jm),qt(t,n)}}function gC(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Wt(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),qt(t,e)}else{if(Wt(t,n))return;Ym.set(n),i.uniformMatrix4fv(this.addr,!1,Ym),qt(t,n)}}function vC(i,e){const t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function yC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Wt(t,e))return;i.uniform2iv(this.addr,e),qt(t,e)}}function bC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Wt(t,e))return;i.uniform3iv(this.addr,e),qt(t,e)}}function _C(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Wt(t,e))return;i.uniform4iv(this.addr,e),qt(t,e)}}function SC(i,e){const t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function xC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Wt(t,e))return;i.uniform2uiv(this.addr,e),qt(t,e)}}function TC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Wt(t,e))return;i.uniform3uiv(this.addr,e),qt(t,e)}}function CC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Wt(t,e))return;i.uniform4uiv(this.addr,e),qt(t,e)}}function EC(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s);let r;this.type===i.SAMPLER_2D_SHADOW?(cu.compareFunction=t.isReversedDepthBuffer()?Sd:_d,r=cu):r=Wm,t.setTexture2D(e||r,s)}function MC(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture3D(e||jm,s)}function wC(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTextureCube(e||$m,s)}function AC(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture2DArray(e||qm,s)}function RC(i){switch(i){case 5126:return dC;case 35664:return uC;case 35665:return hC;case 35666:return fC;case 35674:return pC;case 35675:return mC;case 35676:return gC;case 5124:case 35670:return vC;case 35667:case 35671:return yC;case 35668:case 35672:return bC;case 35669:case 35673:return _C;case 5125:return SC;case 36294:return xC;case 36295:return TC;case 36296:return CC;case 35678:case 36198:case 36298:case 36306:case 35682:return EC;case 35679:case 36299:case 36307:return MC;case 35680:case 36300:case 36308:case 36293:return wC;case 36289:case 36303:case 36311:case 36292:return AC}}function PC(i,e){i.uniform1fv(this.addr,e)}function kC(i,e){const t=_r(e,this.size,2);i.uniform2fv(this.addr,t)}function IC(i,e){const t=_r(e,this.size,3);i.uniform3fv(this.addr,t)}function DC(i,e){const t=_r(e,this.size,4);i.uniform4fv(this.addr,t)}function LC(i,e){const t=_r(e,this.size,4);i.uniformMatrix2fv(this.addr,!1,t)}function NC(i,e){const t=_r(e,this.size,9);i.uniformMatrix3fv(this.addr,!1,t)}function OC(i,e){const t=_r(e,this.size,16);i.uniformMatrix4fv(this.addr,!1,t)}function UC(i,e){i.uniform1iv(this.addr,e)}function FC(i,e){i.uniform2iv(this.addr,e)}function BC(i,e){i.uniform3iv(this.addr,e)}function zC(i,e){i.uniform4iv(this.addr,e)}function VC(i,e){i.uniform1uiv(this.addr,e)}function GC(i,e){i.uniform2uiv(this.addr,e)}function HC(i,e){i.uniform3uiv(this.addr,e)}function WC(i,e){i.uniform4uiv(this.addr,e)}function qC(i,e,t){const n=this.cache,s=e.length,r=Wo(t,s);Wt(n,r)||(i.uniform1iv(this.addr,r),qt(n,r));let o;this.type===i.SAMPLER_2D_SHADOW?o=cu:o=Wm;for(let a=0;a!==s;++a)t.setTexture2D(e[a]||o,r[a])}function jC(i,e,t){const n=this.cache,s=e.length,r=Wo(t,s);Wt(n,r)||(i.uniform1iv(this.addr,r),qt(n,r));for(let o=0;o!==s;++o)t.setTexture3D(e[o]||jm,r[o])}function $C(i,e,t){const n=this.cache,s=e.length,r=Wo(t,s);Wt(n,r)||(i.uniform1iv(this.addr,r),qt(n,r));for(let o=0;o!==s;++o)t.setTextureCube(e[o]||$m,r[o])}function XC(i,e,t){const n=this.cache,s=e.length,r=Wo(t,s);Wt(n,r)||(i.uniform1iv(this.addr,r),qt(n,r));for(let o=0;o!==s;++o)t.setTexture2DArray(e[o]||qm,r[o])}function KC(i){switch(i){case 5126:return PC;case 35664:return kC;case 35665:return IC;case 35666:return DC;case 35674:return LC;case 35675:return NC;case 35676:return OC;case 5124:case 35670:return UC;case 35667:case 35671:return FC;case 35668:case 35672:return BC;case 35669:case 35673:return zC;case 5125:return VC;case 36294:return GC;case 36295:return HC;case 36296:return WC;case 35678:case 36198:case 36298:case 36306:case 35682:return qC;case 35679:case 36299:case 36307:return jC;case 35680:case 36300:case 36308:case 36293:return $C;case 36289:case 36303:case 36311:case 36292:return XC}}class YC{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=RC(t.type)}}class JC{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=KC(t.type)}}class ZC{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const s=this.seq;for(let r=0,o=s.length;r!==o;++r){const a=s[r];a.setValue(e,t[a.id],n)}}}const lu=/(\w+)(\])?(\[|\.)?/g;function Qm(i,e){i.seq.push(e),i.map[e.id]=e}function QC(i,e,t){const n=i.name,s=n.length;for(lu.lastIndex=0;;){const r=lu.exec(n),o=lu.lastIndex;let a=r[1];const c=r[2]==="]",l=r[3];if(c&&(a=a|0),l===void 0||l==="["&&o+2===s){Qm(t,l===void 0?new YC(a,i,e):new JC(a,i,e));break}else{let u=t.map[a];u===void 0&&(u=new ZC(a),Qm(t,u)),t=u}}}class qo{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let o=0;o<n;++o){const a=e.getActiveUniform(t,o),c=e.getUniformLocation(t,a.name);QC(a,c,this)}const s=[],r=[];for(const o of this.seq)o.type===e.SAMPLER_2D_SHADOW||o.type===e.SAMPLER_CUBE_SHADOW||o.type===e.SAMPLER_2D_ARRAY_SHADOW?s.push(o):r.push(o);s.length>0&&(this.seq=s.concat(r))}setValue(e,t,n,s){const r=this.map[t];r!==void 0&&r.setValue(e,n,s)}setOptional(e,t,n){const s=t[n];s!==void 0&&this.setValue(e,n,s)}static upload(e,t,n,s){for(let r=0,o=t.length;r!==o;++r){const a=t[r],c=n[a.id];c.needsUpdate!==!1&&a.setValue(e,c.value,s)}}static seqWithValue(e,t){const n=[];for(let s=0,r=e.length;s!==r;++s){const o=e[s];o.id in t&&n.push(o)}return n}}function eg(i,e,t){const n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}const eE=37297;let tE=0;function nE(i,e){const t=i.split(`
4000
+ }`,depthTest:!1,depthWrite:!1}),l=new xn(a,c),d=new nu(-1,1,1,-1,0,1);let u=null,h=null,f=!1,g,v=null,m=[],p=!1;this.setSize=function(T,E){r.setSize(T,E),o.setSize(T,E);for(let y=0;y<m.length;y++){const S=m[y];S.setSize&&S.setSize(T,E)}},this.setEffects=function(T){m=T,p=m.length>0&&m[0].isRenderPass===!0;const E=r.width,y=r.height;for(let S=0;S<m.length;S++){const C=m[S];C.setSize&&C.setSize(E,y)}},this.begin=function(T,E){if(f||T.toneMapping===ii&&m.length===0)return!1;if(v=E,E!==null){const y=E.width,S=E.height;(r.width!==y||r.height!==S)&&this.setSize(y,S)}return p===!1&&T.setRenderTarget(r),g=T.toneMapping,T.toneMapping=ii,!0},this.hasRenderPass=function(){return p},this.end=function(T,E){T.toneMapping=g,f=!0;let y=r,S=o;for(let C=0;C<m.length;C++){const w=m[C];if(w.enabled!==!1&&(w.render(T,S,y,E),w.needsSwap!==!1)){const k=y;y=S,S=k}}if(u!==T.outputColorSpace||h!==T.toneMapping){u=T.outputColorSpace,h=T.toneMapping,c.defines={},nt.getTransfer(u)===lt&&(c.defines.SRGB_TRANSFER="");const C=cC[h];C&&(c.defines[C]=""),c.needsUpdate=!0}c.uniforms.tDiffuse.value=y.texture,T.setRenderTarget(v),T.render(l,d),v=null,f=!1},this.isCompositing=function(){return f},this.dispose=function(){r.dispose(),o.dispose(),a.dispose(),c.dispose()}}const Wm=new hn,cu=new da(1,1),qm=new im,jm=new oS,$m=new Cm,Xm=[],Km=[],Ym=new Float32Array(16),Jm=new Float32Array(9),Zm=new Float32Array(4);function _r(i,e,t){const n=i[0];if(n<=0||n>0)return i;const s=e*t;let r=Xm[s];if(r===void 0&&(r=new Float32Array(s),Xm[s]=r),e!==0){n.toArray(r,0);for(let o=1,a=0;o!==e;++o)a+=t,i[o].toArray(r,a)}return r}function Wt(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function qt(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function Wo(i,e){let t=Km[e];t===void 0&&(t=new Int32Array(e),Km[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function dC(i,e){const t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function uC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Wt(t,e))return;i.uniform2fv(this.addr,e),qt(t,e)}}function hC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(Wt(t,e))return;i.uniform3fv(this.addr,e),qt(t,e)}}function fC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Wt(t,e))return;i.uniform4fv(this.addr,e),qt(t,e)}}function pC(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Wt(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),qt(t,e)}else{if(Wt(t,n))return;Zm.set(n),i.uniformMatrix2fv(this.addr,!1,Zm),qt(t,n)}}function mC(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Wt(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),qt(t,e)}else{if(Wt(t,n))return;Jm.set(n),i.uniformMatrix3fv(this.addr,!1,Jm),qt(t,n)}}function gC(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Wt(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),qt(t,e)}else{if(Wt(t,n))return;Ym.set(n),i.uniformMatrix4fv(this.addr,!1,Ym),qt(t,n)}}function vC(i,e){const t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function yC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Wt(t,e))return;i.uniform2iv(this.addr,e),qt(t,e)}}function bC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Wt(t,e))return;i.uniform3iv(this.addr,e),qt(t,e)}}function _C(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Wt(t,e))return;i.uniform4iv(this.addr,e),qt(t,e)}}function SC(i,e){const t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function xC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Wt(t,e))return;i.uniform2uiv(this.addr,e),qt(t,e)}}function TC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Wt(t,e))return;i.uniform3uiv(this.addr,e),qt(t,e)}}function CC(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Wt(t,e))return;i.uniform4uiv(this.addr,e),qt(t,e)}}function EC(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s);let r;this.type===i.SAMPLER_2D_SHADOW?(cu.compareFunction=t.isReversedDepthBuffer()?Sd:_d,r=cu):r=Wm,t.setTexture2D(e||r,s)}function MC(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture3D(e||jm,s)}function wC(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTextureCube(e||$m,s)}function AC(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture2DArray(e||qm,s)}function RC(i){switch(i){case 5126:return dC;case 35664:return uC;case 35665:return hC;case 35666:return fC;case 35674:return pC;case 35675:return mC;case 35676:return gC;case 5124:case 35670:return vC;case 35667:case 35671:return yC;case 35668:case 35672:return bC;case 35669:case 35673:return _C;case 5125:return SC;case 36294:return xC;case 36295:return TC;case 36296:return CC;case 35678:case 36198:case 36298:case 36306:case 35682:return EC;case 35679:case 36299:case 36307:return MC;case 35680:case 36300:case 36308:case 36293:return wC;case 36289:case 36303:case 36311:case 36292:return AC}}function PC(i,e){i.uniform1fv(this.addr,e)}function kC(i,e){const t=_r(e,this.size,2);i.uniform2fv(this.addr,t)}function IC(i,e){const t=_r(e,this.size,3);i.uniform3fv(this.addr,t)}function DC(i,e){const t=_r(e,this.size,4);i.uniform4fv(this.addr,t)}function LC(i,e){const t=_r(e,this.size,4);i.uniformMatrix2fv(this.addr,!1,t)}function NC(i,e){const t=_r(e,this.size,9);i.uniformMatrix3fv(this.addr,!1,t)}function OC(i,e){const t=_r(e,this.size,16);i.uniformMatrix4fv(this.addr,!1,t)}function UC(i,e){i.uniform1iv(this.addr,e)}function FC(i,e){i.uniform2iv(this.addr,e)}function BC(i,e){i.uniform3iv(this.addr,e)}function zC(i,e){i.uniform4iv(this.addr,e)}function VC(i,e){i.uniform1uiv(this.addr,e)}function GC(i,e){i.uniform2uiv(this.addr,e)}function HC(i,e){i.uniform3uiv(this.addr,e)}function WC(i,e){i.uniform4uiv(this.addr,e)}function qC(i,e,t){const n=this.cache,s=e.length,r=Wo(t,s);Wt(n,r)||(i.uniform1iv(this.addr,r),qt(n,r));let o;this.type===i.SAMPLER_2D_SHADOW?o=cu:o=Wm;for(let a=0;a!==s;++a)t.setTexture2D(e[a]||o,r[a])}function jC(i,e,t){const n=this.cache,s=e.length,r=Wo(t,s);Wt(n,r)||(i.uniform1iv(this.addr,r),qt(n,r));for(let o=0;o!==s;++o)t.setTexture3D(e[o]||jm,r[o])}function $C(i,e,t){const n=this.cache,s=e.length,r=Wo(t,s);Wt(n,r)||(i.uniform1iv(this.addr,r),qt(n,r));for(let o=0;o!==s;++o)t.setTextureCube(e[o]||$m,r[o])}function XC(i,e,t){const n=this.cache,s=e.length,r=Wo(t,s);Wt(n,r)||(i.uniform1iv(this.addr,r),qt(n,r));for(let o=0;o!==s;++o)t.setTexture2DArray(e[o]||qm,r[o])}function KC(i){switch(i){case 5126:return PC;case 35664:return kC;case 35665:return IC;case 35666:return DC;case 35674:return LC;case 35675:return NC;case 35676:return OC;case 5124:case 35670:return UC;case 35667:case 35671:return FC;case 35668:case 35672:return BC;case 35669:case 35673:return zC;case 5125:return VC;case 36294:return GC;case 36295:return HC;case 36296:return WC;case 35678:case 36198:case 36298:case 36306:case 35682:return qC;case 35679:case 36299:case 36307:return jC;case 35680:case 36300:case 36308:case 36293:return $C;case 36289:case 36303:case 36311:case 36292:return XC}}class YC{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=RC(t.type)}}class JC{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=KC(t.type)}}class ZC{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const s=this.seq;for(let r=0,o=s.length;r!==o;++r){const a=s[r];a.setValue(e,t[a.id],n)}}}const lu=/(\w+)(\])?(\[|\.)?/g;function Qm(i,e){i.seq.push(e),i.map[e.id]=e}function QC(i,e,t){const n=i.name,s=n.length;for(lu.lastIndex=0;;){const r=lu.exec(n),o=lu.lastIndex;let a=r[1];const c=r[2]==="]",l=r[3];if(c&&(a=a|0),l===void 0||l==="["&&o+2===s){Qm(t,l===void 0?new YC(a,i,e):new JC(a,i,e));break}else{let u=t.map[a];u===void 0&&(u=new ZC(a),Qm(t,u)),t=u}}}class qo{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let o=0;o<n;++o){const a=e.getActiveUniform(t,o),c=e.getUniformLocation(t,a.name);QC(a,c,this)}const s=[],r=[];for(const o of this.seq)o.type===e.SAMPLER_2D_SHADOW||o.type===e.SAMPLER_CUBE_SHADOW||o.type===e.SAMPLER_2D_ARRAY_SHADOW?s.push(o):r.push(o);s.length>0&&(this.seq=s.concat(r))}setValue(e,t,n,s){const r=this.map[t];r!==void 0&&r.setValue(e,n,s)}setOptional(e,t,n){const s=t[n];s!==void 0&&this.setValue(e,n,s)}static upload(e,t,n,s){for(let r=0,o=t.length;r!==o;++r){const a=t[r],c=n[a.id];c.needsUpdate!==!1&&a.setValue(e,c.value,s)}}static seqWithValue(e,t){const n=[];for(let s=0,r=e.length;s!==r;++s){const o=e[s];o.id in t&&n.push(o)}return n}}function eg(i,e,t){const n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}const eE=37297;let tE=0;function nE(i,e){const t=i.split(`
4001
4001
  `),n=[],s=Math.max(e-6,0),r=Math.min(e+6,t.length);for(let o=s;o<r;o++){const a=o+1;n.push(`${a===e?">":" "} ${a}: ${t[o]}`)}return n.join(`
4002
4002
  `)}const tg=new We;function iE(i){nt._getMatrix(tg,nt.workingColorSpace,i);const e=`mat3( ${tg.elements.map(t=>t.toFixed(4))} )`;switch(nt.getTransfer(i)){case po:return[e,"LinearTransferOETF"];case lt:return[e,"sRGBTransferOETF"];default:return Be("WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function ng(i,e,t){const n=i.getShaderParameter(e,i.COMPILE_STATUS),r=(i.getShaderInfoLog(e)||"").trim();if(n&&r==="")return"";const o=/ERROR: 0:(\d+)/.exec(r);if(o){const a=parseInt(o[1]);return t.toUpperCase()+`
4003
4003
 
@@ -4041,14 +4041,14 @@ void main() {
4041
4041
  `)+`
4042
4042
  `+m,p=["#define varying in",t.glslVersion===Yp?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Yp?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
4043
4043
  `)+`
4044
- `+p);const E=T+m+o,y=T+p+a,S=eg(s,s.VERTEX_SHADER,E),C=eg(s,s.FRAGMENT_SHADER,y);s.attachShader(v,S),s.attachShader(v,C),t.index0AttributeName!==void 0?s.bindAttribLocation(v,0,t.index0AttributeName):t.morphTargets===!0&&s.bindAttribLocation(v,0,"position"),s.linkProgram(v);function w(R){if(i.debug.checkShaderErrors){const O=s.getProgramInfoLog(v)||"",F=s.getShaderInfoLog(S)||"",q=s.getShaderInfoLog(C)||"",K=O.trim(),G=F.trim(),W=q.trim();let te=!0,ye=!0;if(s.getProgramParameter(v,s.LINK_STATUS)===!1)if(te=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(s,v,S,C);else{const de=ng(s,S,"vertex"),_e=ng(s,C,"fragment");st("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(v,s.VALIDATE_STATUS)+`
4044
+ `+p);const E=T+m+o,y=T+p+a,S=eg(s,s.VERTEX_SHADER,E),C=eg(s,s.FRAGMENT_SHADER,y);s.attachShader(v,S),s.attachShader(v,C),t.index0AttributeName!==void 0?s.bindAttribLocation(v,0,t.index0AttributeName):t.morphTargets===!0&&s.bindAttribLocation(v,0,"position"),s.linkProgram(v);function w(R){if(i.debug.checkShaderErrors){const O=s.getProgramInfoLog(v)||"",F=s.getShaderInfoLog(S)||"",q=s.getShaderInfoLog(C)||"",K=O.trim(),G=F.trim(),W=q.trim();let te=!0,ye=!0;if(s.getProgramParameter(v,s.LINK_STATUS)===!1)if(te=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(s,v,S,C);else{const ue=ng(s,S,"vertex"),_e=ng(s,C,"fragment");st("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(v,s.VALIDATE_STATUS)+`
4045
4045
 
4046
4046
  Material Name: `+R.name+`
4047
4047
  Material Type: `+R.type+`
4048
4048
 
4049
4049
  Program Info Log: `+K+`
4050
- `+de+`
4051
- `+_e)}else K!==""?Be("WebGLProgram: Program Info Log:",K):(G===""||W==="")&&(ye=!1);ye&&(R.diagnostics={runnable:te,programLog:K,vertexShader:{log:G,prefix:m},fragmentShader:{log:W,prefix:p}})}s.deleteShader(S),s.deleteShader(C),k=new qo(s,v),_=dE(s,v)}let k;this.getUniforms=function(){return k===void 0&&w(this),k};let _;this.getAttributes=function(){return _===void 0&&w(this),_};let x=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return x===!1&&(x=s.getProgramParameter(v,eE)),x},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=tE++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=S,this.fragmentShader=C,this}let ME=0;class wE{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,s=this._getShaderStage(t),r=this._getShaderStage(n),o=this._getShaderCacheForMaterial(e);return o.has(s)===!1&&(o.add(s),s.usedTimes++),o.has(r)===!1&&(o.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new AE(e),t.set(e,n)),n}}class AE{constructor(e){this.id=ME++,this.code=e,this.usedTimes=0}}function RE(i,e,t,n,s,r,o){const a=new am,c=new wE,l=new Set,d=[],u=new Map,h=s.logarithmicDepthBuffer;let f=s.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(_){return l.add(_),_===0?"uv":`uv${_}`}function m(_,x,R,O,F){const q=O.fog,K=F.geometry,G=_.isMeshStandardMaterial?O.environment:null,W=(_.isMeshStandardMaterial?t:e).get(_.envMap||G),te=W&&W.mapping===oo?W.image.height:null,ye=g[_.type];_.precision!==null&&(f=s.getMaxPrecision(_.precision),f!==_.precision&&Be("WebGLProgram.getParameters:",_.precision,"not supported, using",f,"instead."));const de=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,_e=de!==void 0?de.length:0;let Ge=0;K.morphAttributes.position!==void 0&&(Ge=1),K.morphAttributes.normal!==void 0&&(Ge=2),K.morphAttributes.color!==void 0&&(Ge=3);let Ve,Mt,pt,Y;if(ye){const ut=ci[ye];Ve=ut.vertexShader,Mt=ut.fragmentShader}else Ve=_.vertexShader,Mt=_.fragmentShader,c.update(_),pt=c.getVertexShaderID(_),Y=c.getFragmentShaderID(_);const ie=i.getRenderTarget(),Ce=i.state.buffers.depth.getReversed(),qe=F.isInstancedMesh===!0,we=F.isBatchedMesh===!0,rt=!!_.map,Yt=!!_.matcap,it=!!W,dt=!!_.aoMap,yt=!!_.lightMap,$e=!!_.bumpMap,Vt=!!_.normalMap,I=!!_.displacementMap,Gt=!!_.emissiveMap,ct=!!_.metalnessMap,_t=!!_.roughnessMap,Re=_.anisotropy>0,A=_.clearcoat>0,b=_.dispersion>0,L=_.iridescence>0,X=_.sheen>0,ee=_.transmission>0,j=Re&&!!_.anisotropyMap,ke=A&&!!_.clearcoatMap,he=A&&!!_.clearcoatNormalMap,Ae=A&&!!_.clearcoatRoughnessMap,Ue=L&&!!_.iridescenceMap,re=L&&!!_.iridescenceThicknessMap,me=X&&!!_.sheenColorMap,Me=X&&!!_.sheenRoughnessMap,Pe=!!_.specularMap,fe=!!_.specularColorMap,Xe=!!_.specularIntensityMap,D=ee&&!!_.transmissionMap,Se=ee&&!!_.thicknessMap,oe=!!_.gradientMap,xe=!!_.alphaMap,se=_.alphaTest>0,Q=!!_.alphaHash,ue=!!_.extensions;let ze=ii;_.toneMapped&&(ie===null||ie.isXRRenderTarget===!0)&&(ze=i.toneMapping);const St={shaderID:ye,shaderType:_.type,shaderName:_.name,vertexShader:Ve,fragmentShader:Mt,defines:_.defines,customVertexShaderID:pt,customFragmentShaderID:Y,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:f,batching:we,batchingColor:we&&F._colorsTexture!==null,instancing:qe,instancingColor:qe&&F.instanceColor!==null,instancingMorph:qe&&F.morphTexture!==null,outputColorSpace:ie===null?i.outputColorSpace:ie.isXRRenderTarget===!0?ie.texture.colorSpace:er,alphaToCoverage:!!_.alphaToCoverage,map:rt,matcap:Yt,envMap:it,envMapMode:it&&W.mapping,envMapCubeUVHeight:te,aoMap:dt,lightMap:yt,bumpMap:$e,normalMap:Vt,displacementMap:I,emissiveMap:Gt,normalMapObjectSpace:Vt&&_.normalMapType===j_,normalMapTangentSpace:Vt&&_.normalMapType===q_,metalnessMap:ct,roughnessMap:_t,anisotropy:Re,anisotropyMap:j,clearcoat:A,clearcoatMap:ke,clearcoatNormalMap:he,clearcoatRoughnessMap:Ae,dispersion:b,iridescence:L,iridescenceMap:Ue,iridescenceThicknessMap:re,sheen:X,sheenColorMap:me,sheenRoughnessMap:Me,specularMap:Pe,specularColorMap:fe,specularIntensityMap:Xe,transmission:ee,transmissionMap:D,thicknessMap:Se,gradientMap:oe,opaque:_.transparent===!1&&_.blending===Ys&&_.alphaToCoverage===!1,alphaMap:xe,alphaTest:se,alphaHash:Q,combine:_.combine,mapUv:rt&&v(_.map.channel),aoMapUv:dt&&v(_.aoMap.channel),lightMapUv:yt&&v(_.lightMap.channel),bumpMapUv:$e&&v(_.bumpMap.channel),normalMapUv:Vt&&v(_.normalMap.channel),displacementMapUv:I&&v(_.displacementMap.channel),emissiveMapUv:Gt&&v(_.emissiveMap.channel),metalnessMapUv:ct&&v(_.metalnessMap.channel),roughnessMapUv:_t&&v(_.roughnessMap.channel),anisotropyMapUv:j&&v(_.anisotropyMap.channel),clearcoatMapUv:ke&&v(_.clearcoatMap.channel),clearcoatNormalMapUv:he&&v(_.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ae&&v(_.clearcoatRoughnessMap.channel),iridescenceMapUv:Ue&&v(_.iridescenceMap.channel),iridescenceThicknessMapUv:re&&v(_.iridescenceThicknessMap.channel),sheenColorMapUv:me&&v(_.sheenColorMap.channel),sheenRoughnessMapUv:Me&&v(_.sheenRoughnessMap.channel),specularMapUv:Pe&&v(_.specularMap.channel),specularColorMapUv:fe&&v(_.specularColorMap.channel),specularIntensityMapUv:Xe&&v(_.specularIntensityMap.channel),transmissionMapUv:D&&v(_.transmissionMap.channel),thicknessMapUv:Se&&v(_.thicknessMap.channel),alphaMapUv:xe&&v(_.alphaMap.channel),vertexTangents:!!K.attributes.tangent&&(Vt||Re),vertexColors:_.vertexColors,vertexAlphas:_.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,pointsUvs:F.isPoints===!0&&!!K.attributes.uv&&(rt||xe),fog:!!q,useFog:_.fog===!0,fogExp2:!!q&&q.isFogExp2,flatShading:_.flatShading===!0&&_.wireframe===!1,sizeAttenuation:_.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:Ce,skinning:F.isSkinnedMesh===!0,morphTargets:K.morphAttributes.position!==void 0,morphNormals:K.morphAttributes.normal!==void 0,morphColors:K.morphAttributes.color!==void 0,morphTargetsCount:_e,morphTextureStride:Ge,numDirLights:x.directional.length,numPointLights:x.point.length,numSpotLights:x.spot.length,numSpotLightMaps:x.spotLightMap.length,numRectAreaLights:x.rectArea.length,numHemiLights:x.hemi.length,numDirLightShadows:x.directionalShadowMap.length,numPointLightShadows:x.pointShadowMap.length,numSpotLightShadows:x.spotShadowMap.length,numSpotLightShadowsWithMaps:x.numSpotLightShadowsWithMaps,numLightProbes:x.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:_.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:ze,decodeVideoTexture:rt&&_.map.isVideoTexture===!0&&nt.getTransfer(_.map.colorSpace)===lt,decodeVideoTextureEmissive:Gt&&_.emissiveMap.isVideoTexture===!0&&nt.getTransfer(_.emissiveMap.colorSpace)===lt,premultipliedAlpha:_.premultipliedAlpha,doubleSided:_.side===Si,flipSided:_.side===tn,useDepthPacking:_.depthPacking>=0,depthPacking:_.depthPacking||0,index0AttributeName:_.index0AttributeName,extensionClipCullDistance:ue&&_.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ue&&_.extensions.multiDraw===!0||we)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:_.customProgramCacheKey()};return St.vertexUv1s=l.has(1),St.vertexUv2s=l.has(2),St.vertexUv3s=l.has(3),l.clear(),St}function p(_){const x=[];if(_.shaderID?x.push(_.shaderID):(x.push(_.customVertexShaderID),x.push(_.customFragmentShaderID)),_.defines!==void 0)for(const R in _.defines)x.push(R),x.push(_.defines[R]);return _.isRawShaderMaterial===!1&&(T(x,_),E(x,_),x.push(i.outputColorSpace)),x.push(_.customProgramCacheKey),x.join()}function T(_,x){_.push(x.precision),_.push(x.outputColorSpace),_.push(x.envMapMode),_.push(x.envMapCubeUVHeight),_.push(x.mapUv),_.push(x.alphaMapUv),_.push(x.lightMapUv),_.push(x.aoMapUv),_.push(x.bumpMapUv),_.push(x.normalMapUv),_.push(x.displacementMapUv),_.push(x.emissiveMapUv),_.push(x.metalnessMapUv),_.push(x.roughnessMapUv),_.push(x.anisotropyMapUv),_.push(x.clearcoatMapUv),_.push(x.clearcoatNormalMapUv),_.push(x.clearcoatRoughnessMapUv),_.push(x.iridescenceMapUv),_.push(x.iridescenceThicknessMapUv),_.push(x.sheenColorMapUv),_.push(x.sheenRoughnessMapUv),_.push(x.specularMapUv),_.push(x.specularColorMapUv),_.push(x.specularIntensityMapUv),_.push(x.transmissionMapUv),_.push(x.thicknessMapUv),_.push(x.combine),_.push(x.fogExp2),_.push(x.sizeAttenuation),_.push(x.morphTargetsCount),_.push(x.morphAttributeCount),_.push(x.numDirLights),_.push(x.numPointLights),_.push(x.numSpotLights),_.push(x.numSpotLightMaps),_.push(x.numHemiLights),_.push(x.numRectAreaLights),_.push(x.numDirLightShadows),_.push(x.numPointLightShadows),_.push(x.numSpotLightShadows),_.push(x.numSpotLightShadowsWithMaps),_.push(x.numLightProbes),_.push(x.shadowMapType),_.push(x.toneMapping),_.push(x.numClippingPlanes),_.push(x.numClipIntersection),_.push(x.depthPacking)}function E(_,x){a.disableAll(),x.instancing&&a.enable(0),x.instancingColor&&a.enable(1),x.instancingMorph&&a.enable(2),x.matcap&&a.enable(3),x.envMap&&a.enable(4),x.normalMapObjectSpace&&a.enable(5),x.normalMapTangentSpace&&a.enable(6),x.clearcoat&&a.enable(7),x.iridescence&&a.enable(8),x.alphaTest&&a.enable(9),x.vertexColors&&a.enable(10),x.vertexAlphas&&a.enable(11),x.vertexUv1s&&a.enable(12),x.vertexUv2s&&a.enable(13),x.vertexUv3s&&a.enable(14),x.vertexTangents&&a.enable(15),x.anisotropy&&a.enable(16),x.alphaHash&&a.enable(17),x.batching&&a.enable(18),x.dispersion&&a.enable(19),x.batchingColor&&a.enable(20),x.gradientMap&&a.enable(21),_.push(a.mask),a.disableAll(),x.fog&&a.enable(0),x.useFog&&a.enable(1),x.flatShading&&a.enable(2),x.logarithmicDepthBuffer&&a.enable(3),x.reversedDepthBuffer&&a.enable(4),x.skinning&&a.enable(5),x.morphTargets&&a.enable(6),x.morphNormals&&a.enable(7),x.morphColors&&a.enable(8),x.premultipliedAlpha&&a.enable(9),x.shadowMapEnabled&&a.enable(10),x.doubleSided&&a.enable(11),x.flipSided&&a.enable(12),x.useDepthPacking&&a.enable(13),x.dithering&&a.enable(14),x.transmission&&a.enable(15),x.sheen&&a.enable(16),x.opaque&&a.enable(17),x.pointsUvs&&a.enable(18),x.decodeVideoTexture&&a.enable(19),x.decodeVideoTextureEmissive&&a.enable(20),x.alphaToCoverage&&a.enable(21),_.push(a.mask)}function y(_){const x=g[_.type];let R;if(x){const O=ci[x];R=_S.clone(O.uniforms)}else R=_.uniforms;return R}function S(_,x){let R=u.get(x);return R!==void 0?++R.usedTimes:(R=new EE(i,x,_,r),d.push(R),u.set(x,R)),R}function C(_){if(--_.usedTimes===0){const x=d.indexOf(_);d[x]=d[d.length-1],d.pop(),u.delete(_.cacheKey),_.destroy()}}function w(_){c.remove(_)}function k(){c.dispose()}return{getParameters:m,getProgramCacheKey:p,getUniforms:y,acquireProgram:S,releaseProgram:C,releaseShaderCache:w,programs:d,dispose:k}}function PE(){let i=new WeakMap;function e(o){return i.has(o)}function t(o){let a=i.get(o);return a===void 0&&(a={},i.set(o,a)),a}function n(o){i.delete(o)}function s(o,a,c){i.get(o)[a]=c}function r(){i=new WeakMap}return{has:e,get:t,remove:n,update:s,dispose:r}}function kE(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.z!==e.z?i.z-e.z:i.id-e.id}function og(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function cg(){const i=[];let e=0;const t=[],n=[],s=[];function r(){e=0,t.length=0,n.length=0,s.length=0}function o(u,h,f,g,v,m){let p=i[e];return p===void 0?(p={id:u.id,object:u,geometry:h,material:f,groupOrder:g,renderOrder:u.renderOrder,z:v,group:m},i[e]=p):(p.id=u.id,p.object=u,p.geometry=h,p.material=f,p.groupOrder=g,p.renderOrder=u.renderOrder,p.z=v,p.group=m),e++,p}function a(u,h,f,g,v,m){const p=o(u,h,f,g,v,m);f.transmission>0?n.push(p):f.transparent===!0?s.push(p):t.push(p)}function c(u,h,f,g,v,m){const p=o(u,h,f,g,v,m);f.transmission>0?n.unshift(p):f.transparent===!0?s.unshift(p):t.unshift(p)}function l(u,h){t.length>1&&t.sort(u||kE),n.length>1&&n.sort(h||og),s.length>1&&s.sort(h||og)}function d(){for(let u=e,h=i.length;u<h;u++){const f=i[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:n,transparent:s,init:r,push:a,unshift:c,finish:d,sort:l}}function IE(){let i=new WeakMap;function e(n,s){const r=i.get(n);let o;return r===void 0?(o=new cg,i.set(n,[o])):s>=r.length?(o=new cg,r.push(o)):o=r[s],o}function t(){i=new WeakMap}return{get:e,dispose:t}}function DE(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new U,color:new Fe};break;case"SpotLight":t={position:new U,direction:new U,color:new Fe,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new U,color:new Fe,distance:0,decay:0};break;case"HemisphereLight":t={direction:new U,skyColor:new Fe,groundColor:new Fe};break;case"RectAreaLight":t={color:new Fe,position:new U,halfWidth:new U,halfHeight:new U};break}return i[e.id]=t,t}}}function LE(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new tt};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new tt};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new tt,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let NE=0;function OE(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function UE(i){const e=new DE,t=LE(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new U);const s=new U,r=new At,o=new At;function a(l){let d=0,u=0,h=0;for(let _=0;_<9;_++)n.probe[_].set(0,0,0);let f=0,g=0,v=0,m=0,p=0,T=0,E=0,y=0,S=0,C=0,w=0;l.sort(OE);for(let _=0,x=l.length;_<x;_++){const R=l[_],O=R.color,F=R.intensity,q=R.distance;let K=null;if(R.shadow&&R.shadow.map&&(R.shadow.map.texture.format===Qs?K=R.shadow.map.texture:K=R.shadow.map.depthTexture||R.shadow.map.texture),R.isAmbientLight)d+=O.r*F,u+=O.g*F,h+=O.b*F;else if(R.isLightProbe){for(let G=0;G<9;G++)n.probe[G].addScaledVector(R.sh.coefficients[G],F);w++}else if(R.isDirectionalLight){const G=e.get(R);if(G.color.copy(R.color).multiplyScalar(R.intensity),R.castShadow){const W=R.shadow,te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,n.directionalShadow[f]=te,n.directionalShadowMap[f]=K,n.directionalShadowMatrix[f]=R.shadow.matrix,T++}n.directional[f]=G,f++}else if(R.isSpotLight){const G=e.get(R);G.position.setFromMatrixPosition(R.matrixWorld),G.color.copy(O).multiplyScalar(F),G.distance=q,G.coneCos=Math.cos(R.angle),G.penumbraCos=Math.cos(R.angle*(1-R.penumbra)),G.decay=R.decay,n.spot[v]=G;const W=R.shadow;if(R.map&&(n.spotLightMap[S]=R.map,S++,W.updateMatrices(R),R.castShadow&&C++),n.spotLightMatrix[v]=W.matrix,R.castShadow){const te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,n.spotShadow[v]=te,n.spotShadowMap[v]=K,y++}v++}else if(R.isRectAreaLight){const G=e.get(R);G.color.copy(O).multiplyScalar(F),G.halfWidth.set(R.width*.5,0,0),G.halfHeight.set(0,R.height*.5,0),n.rectArea[m]=G,m++}else if(R.isPointLight){const G=e.get(R);if(G.color.copy(R.color).multiplyScalar(R.intensity),G.distance=R.distance,G.decay=R.decay,R.castShadow){const W=R.shadow,te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,te.shadowCameraNear=W.camera.near,te.shadowCameraFar=W.camera.far,n.pointShadow[g]=te,n.pointShadowMap[g]=K,n.pointShadowMatrix[g]=R.shadow.matrix,E++}n.point[g]=G,g++}else if(R.isHemisphereLight){const G=e.get(R);G.skyColor.copy(R.color).multiplyScalar(F),G.groundColor.copy(R.groundColor).multiplyScalar(F),n.hemi[p]=G,p++}}m>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ve.LTC_FLOAT_1,n.rectAreaLTC2=ve.LTC_FLOAT_2):(n.rectAreaLTC1=ve.LTC_HALF_1,n.rectAreaLTC2=ve.LTC_HALF_2)),n.ambient[0]=d,n.ambient[1]=u,n.ambient[2]=h;const k=n.hash;(k.directionalLength!==f||k.pointLength!==g||k.spotLength!==v||k.rectAreaLength!==m||k.hemiLength!==p||k.numDirectionalShadows!==T||k.numPointShadows!==E||k.numSpotShadows!==y||k.numSpotMaps!==S||k.numLightProbes!==w)&&(n.directional.length=f,n.spot.length=v,n.rectArea.length=m,n.point.length=g,n.hemi.length=p,n.directionalShadow.length=T,n.directionalShadowMap.length=T,n.pointShadow.length=E,n.pointShadowMap.length=E,n.spotShadow.length=y,n.spotShadowMap.length=y,n.directionalShadowMatrix.length=T,n.pointShadowMatrix.length=E,n.spotLightMatrix.length=y+S-C,n.spotLightMap.length=S,n.numSpotLightShadowsWithMaps=C,n.numLightProbes=w,k.directionalLength=f,k.pointLength=g,k.spotLength=v,k.rectAreaLength=m,k.hemiLength=p,k.numDirectionalShadows=T,k.numPointShadows=E,k.numSpotShadows=y,k.numSpotMaps=S,k.numLightProbes=w,n.version=NE++)}function c(l,d){let u=0,h=0,f=0,g=0,v=0;const m=d.matrixWorldInverse;for(let p=0,T=l.length;p<T;p++){const E=l[p];if(E.isDirectionalLight){const y=n.directional[u];y.direction.setFromMatrixPosition(E.matrixWorld),s.setFromMatrixPosition(E.target.matrixWorld),y.direction.sub(s),y.direction.transformDirection(m),u++}else if(E.isSpotLight){const y=n.spot[f];y.position.setFromMatrixPosition(E.matrixWorld),y.position.applyMatrix4(m),y.direction.setFromMatrixPosition(E.matrixWorld),s.setFromMatrixPosition(E.target.matrixWorld),y.direction.sub(s),y.direction.transformDirection(m),f++}else if(E.isRectAreaLight){const y=n.rectArea[g];y.position.setFromMatrixPosition(E.matrixWorld),y.position.applyMatrix4(m),o.identity(),r.copy(E.matrixWorld),r.premultiply(m),o.extractRotation(r),y.halfWidth.set(E.width*.5,0,0),y.halfHeight.set(0,E.height*.5,0),y.halfWidth.applyMatrix4(o),y.halfHeight.applyMatrix4(o),g++}else if(E.isPointLight){const y=n.point[h];y.position.setFromMatrixPosition(E.matrixWorld),y.position.applyMatrix4(m),h++}else if(E.isHemisphereLight){const y=n.hemi[v];y.direction.setFromMatrixPosition(E.matrixWorld),y.direction.transformDirection(m),v++}}}return{setup:a,setupView:c,state:n}}function lg(i){const e=new UE(i),t=[],n=[];function s(d){l.camera=d,t.length=0,n.length=0}function r(d){t.push(d)}function o(d){n.push(d)}function a(){e.setup(t)}function c(d){e.setupView(t,d)}const l={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:s,state:l,setupLights:a,setupLightsView:c,pushLight:r,pushShadow:o}}function FE(i){let e=new WeakMap;function t(s,r=0){const o=e.get(s);let a;return o===void 0?(a=new lg(i),e.set(s,[a])):r>=o.length?(a=new lg(i),o.push(a)):a=o[r],a}function n(){e=new WeakMap}return{get:t,dispose:n}}const BE=`void main() {
4050
+ `+ue+`
4051
+ `+_e)}else K!==""?Be("WebGLProgram: Program Info Log:",K):(G===""||W==="")&&(ye=!1);ye&&(R.diagnostics={runnable:te,programLog:K,vertexShader:{log:G,prefix:m},fragmentShader:{log:W,prefix:p}})}s.deleteShader(S),s.deleteShader(C),k=new qo(s,v),_=dE(s,v)}let k;this.getUniforms=function(){return k===void 0&&w(this),k};let _;this.getAttributes=function(){return _===void 0&&w(this),_};let x=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return x===!1&&(x=s.getProgramParameter(v,eE)),x},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=tE++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=S,this.fragmentShader=C,this}let ME=0;class wE{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,s=this._getShaderStage(t),r=this._getShaderStage(n),o=this._getShaderCacheForMaterial(e);return o.has(s)===!1&&(o.add(s),s.usedTimes++),o.has(r)===!1&&(o.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new AE(e),t.set(e,n)),n}}class AE{constructor(e){this.id=ME++,this.code=e,this.usedTimes=0}}function RE(i,e,t,n,s,r,o){const a=new am,c=new wE,l=new Set,d=[],u=new Map,h=s.logarithmicDepthBuffer;let f=s.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(_){return l.add(_),_===0?"uv":`uv${_}`}function m(_,x,R,O,F){const q=O.fog,K=F.geometry,G=_.isMeshStandardMaterial?O.environment:null,W=(_.isMeshStandardMaterial?t:e).get(_.envMap||G),te=W&&W.mapping===oo?W.image.height:null,ye=g[_.type];_.precision!==null&&(f=s.getMaxPrecision(_.precision),f!==_.precision&&Be("WebGLProgram.getParameters:",_.precision,"not supported, using",f,"instead."));const ue=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,_e=ue!==void 0?ue.length:0;let Ge=0;K.morphAttributes.position!==void 0&&(Ge=1),K.morphAttributes.normal!==void 0&&(Ge=2),K.morphAttributes.color!==void 0&&(Ge=3);let Ve,Mt,pt,Y;if(ye){const ut=ci[ye];Ve=ut.vertexShader,Mt=ut.fragmentShader}else Ve=_.vertexShader,Mt=_.fragmentShader,c.update(_),pt=c.getVertexShaderID(_),Y=c.getFragmentShaderID(_);const ie=i.getRenderTarget(),Ce=i.state.buffers.depth.getReversed(),qe=F.isInstancedMesh===!0,we=F.isBatchedMesh===!0,rt=!!_.map,Jt=!!_.matcap,it=!!W,dt=!!_.aoMap,yt=!!_.lightMap,$e=!!_.bumpMap,Vt=!!_.normalMap,I=!!_.displacementMap,Gt=!!_.emissiveMap,ct=!!_.metalnessMap,_t=!!_.roughnessMap,Re=_.anisotropy>0,A=_.clearcoat>0,b=_.dispersion>0,L=_.iridescence>0,X=_.sheen>0,ee=_.transmission>0,j=Re&&!!_.anisotropyMap,ke=A&&!!_.clearcoatMap,fe=A&&!!_.clearcoatNormalMap,Ae=A&&!!_.clearcoatRoughnessMap,Ue=L&&!!_.iridescenceMap,re=L&&!!_.iridescenceThicknessMap,me=X&&!!_.sheenColorMap,Me=X&&!!_.sheenRoughnessMap,Pe=!!_.specularMap,pe=!!_.specularColorMap,Xe=!!_.specularIntensityMap,D=ee&&!!_.transmissionMap,Se=ee&&!!_.thicknessMap,oe=!!_.gradientMap,xe=!!_.alphaMap,se=_.alphaTest>0,Q=!!_.alphaHash,he=!!_.extensions;let ze=ii;_.toneMapped&&(ie===null||ie.isXRRenderTarget===!0)&&(ze=i.toneMapping);const St={shaderID:ye,shaderType:_.type,shaderName:_.name,vertexShader:Ve,fragmentShader:Mt,defines:_.defines,customVertexShaderID:pt,customFragmentShaderID:Y,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:f,batching:we,batchingColor:we&&F._colorsTexture!==null,instancing:qe,instancingColor:qe&&F.instanceColor!==null,instancingMorph:qe&&F.morphTexture!==null,outputColorSpace:ie===null?i.outputColorSpace:ie.isXRRenderTarget===!0?ie.texture.colorSpace:er,alphaToCoverage:!!_.alphaToCoverage,map:rt,matcap:Jt,envMap:it,envMapMode:it&&W.mapping,envMapCubeUVHeight:te,aoMap:dt,lightMap:yt,bumpMap:$e,normalMap:Vt,displacementMap:I,emissiveMap:Gt,normalMapObjectSpace:Vt&&_.normalMapType===j_,normalMapTangentSpace:Vt&&_.normalMapType===q_,metalnessMap:ct,roughnessMap:_t,anisotropy:Re,anisotropyMap:j,clearcoat:A,clearcoatMap:ke,clearcoatNormalMap:fe,clearcoatRoughnessMap:Ae,dispersion:b,iridescence:L,iridescenceMap:Ue,iridescenceThicknessMap:re,sheen:X,sheenColorMap:me,sheenRoughnessMap:Me,specularMap:Pe,specularColorMap:pe,specularIntensityMap:Xe,transmission:ee,transmissionMap:D,thicknessMap:Se,gradientMap:oe,opaque:_.transparent===!1&&_.blending===Ys&&_.alphaToCoverage===!1,alphaMap:xe,alphaTest:se,alphaHash:Q,combine:_.combine,mapUv:rt&&v(_.map.channel),aoMapUv:dt&&v(_.aoMap.channel),lightMapUv:yt&&v(_.lightMap.channel),bumpMapUv:$e&&v(_.bumpMap.channel),normalMapUv:Vt&&v(_.normalMap.channel),displacementMapUv:I&&v(_.displacementMap.channel),emissiveMapUv:Gt&&v(_.emissiveMap.channel),metalnessMapUv:ct&&v(_.metalnessMap.channel),roughnessMapUv:_t&&v(_.roughnessMap.channel),anisotropyMapUv:j&&v(_.anisotropyMap.channel),clearcoatMapUv:ke&&v(_.clearcoatMap.channel),clearcoatNormalMapUv:fe&&v(_.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ae&&v(_.clearcoatRoughnessMap.channel),iridescenceMapUv:Ue&&v(_.iridescenceMap.channel),iridescenceThicknessMapUv:re&&v(_.iridescenceThicknessMap.channel),sheenColorMapUv:me&&v(_.sheenColorMap.channel),sheenRoughnessMapUv:Me&&v(_.sheenRoughnessMap.channel),specularMapUv:Pe&&v(_.specularMap.channel),specularColorMapUv:pe&&v(_.specularColorMap.channel),specularIntensityMapUv:Xe&&v(_.specularIntensityMap.channel),transmissionMapUv:D&&v(_.transmissionMap.channel),thicknessMapUv:Se&&v(_.thicknessMap.channel),alphaMapUv:xe&&v(_.alphaMap.channel),vertexTangents:!!K.attributes.tangent&&(Vt||Re),vertexColors:_.vertexColors,vertexAlphas:_.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,pointsUvs:F.isPoints===!0&&!!K.attributes.uv&&(rt||xe),fog:!!q,useFog:_.fog===!0,fogExp2:!!q&&q.isFogExp2,flatShading:_.flatShading===!0&&_.wireframe===!1,sizeAttenuation:_.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:Ce,skinning:F.isSkinnedMesh===!0,morphTargets:K.morphAttributes.position!==void 0,morphNormals:K.morphAttributes.normal!==void 0,morphColors:K.morphAttributes.color!==void 0,morphTargetsCount:_e,morphTextureStride:Ge,numDirLights:x.directional.length,numPointLights:x.point.length,numSpotLights:x.spot.length,numSpotLightMaps:x.spotLightMap.length,numRectAreaLights:x.rectArea.length,numHemiLights:x.hemi.length,numDirLightShadows:x.directionalShadowMap.length,numPointLightShadows:x.pointShadowMap.length,numSpotLightShadows:x.spotShadowMap.length,numSpotLightShadowsWithMaps:x.numSpotLightShadowsWithMaps,numLightProbes:x.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:_.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:ze,decodeVideoTexture:rt&&_.map.isVideoTexture===!0&&nt.getTransfer(_.map.colorSpace)===lt,decodeVideoTextureEmissive:Gt&&_.emissiveMap.isVideoTexture===!0&&nt.getTransfer(_.emissiveMap.colorSpace)===lt,premultipliedAlpha:_.premultipliedAlpha,doubleSided:_.side===Si,flipSided:_.side===nn,useDepthPacking:_.depthPacking>=0,depthPacking:_.depthPacking||0,index0AttributeName:_.index0AttributeName,extensionClipCullDistance:he&&_.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(he&&_.extensions.multiDraw===!0||we)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:_.customProgramCacheKey()};return St.vertexUv1s=l.has(1),St.vertexUv2s=l.has(2),St.vertexUv3s=l.has(3),l.clear(),St}function p(_){const x=[];if(_.shaderID?x.push(_.shaderID):(x.push(_.customVertexShaderID),x.push(_.customFragmentShaderID)),_.defines!==void 0)for(const R in _.defines)x.push(R),x.push(_.defines[R]);return _.isRawShaderMaterial===!1&&(T(x,_),E(x,_),x.push(i.outputColorSpace)),x.push(_.customProgramCacheKey),x.join()}function T(_,x){_.push(x.precision),_.push(x.outputColorSpace),_.push(x.envMapMode),_.push(x.envMapCubeUVHeight),_.push(x.mapUv),_.push(x.alphaMapUv),_.push(x.lightMapUv),_.push(x.aoMapUv),_.push(x.bumpMapUv),_.push(x.normalMapUv),_.push(x.displacementMapUv),_.push(x.emissiveMapUv),_.push(x.metalnessMapUv),_.push(x.roughnessMapUv),_.push(x.anisotropyMapUv),_.push(x.clearcoatMapUv),_.push(x.clearcoatNormalMapUv),_.push(x.clearcoatRoughnessMapUv),_.push(x.iridescenceMapUv),_.push(x.iridescenceThicknessMapUv),_.push(x.sheenColorMapUv),_.push(x.sheenRoughnessMapUv),_.push(x.specularMapUv),_.push(x.specularColorMapUv),_.push(x.specularIntensityMapUv),_.push(x.transmissionMapUv),_.push(x.thicknessMapUv),_.push(x.combine),_.push(x.fogExp2),_.push(x.sizeAttenuation),_.push(x.morphTargetsCount),_.push(x.morphAttributeCount),_.push(x.numDirLights),_.push(x.numPointLights),_.push(x.numSpotLights),_.push(x.numSpotLightMaps),_.push(x.numHemiLights),_.push(x.numRectAreaLights),_.push(x.numDirLightShadows),_.push(x.numPointLightShadows),_.push(x.numSpotLightShadows),_.push(x.numSpotLightShadowsWithMaps),_.push(x.numLightProbes),_.push(x.shadowMapType),_.push(x.toneMapping),_.push(x.numClippingPlanes),_.push(x.numClipIntersection),_.push(x.depthPacking)}function E(_,x){a.disableAll(),x.instancing&&a.enable(0),x.instancingColor&&a.enable(1),x.instancingMorph&&a.enable(2),x.matcap&&a.enable(3),x.envMap&&a.enable(4),x.normalMapObjectSpace&&a.enable(5),x.normalMapTangentSpace&&a.enable(6),x.clearcoat&&a.enable(7),x.iridescence&&a.enable(8),x.alphaTest&&a.enable(9),x.vertexColors&&a.enable(10),x.vertexAlphas&&a.enable(11),x.vertexUv1s&&a.enable(12),x.vertexUv2s&&a.enable(13),x.vertexUv3s&&a.enable(14),x.vertexTangents&&a.enable(15),x.anisotropy&&a.enable(16),x.alphaHash&&a.enable(17),x.batching&&a.enable(18),x.dispersion&&a.enable(19),x.batchingColor&&a.enable(20),x.gradientMap&&a.enable(21),_.push(a.mask),a.disableAll(),x.fog&&a.enable(0),x.useFog&&a.enable(1),x.flatShading&&a.enable(2),x.logarithmicDepthBuffer&&a.enable(3),x.reversedDepthBuffer&&a.enable(4),x.skinning&&a.enable(5),x.morphTargets&&a.enable(6),x.morphNormals&&a.enable(7),x.morphColors&&a.enable(8),x.premultipliedAlpha&&a.enable(9),x.shadowMapEnabled&&a.enable(10),x.doubleSided&&a.enable(11),x.flipSided&&a.enable(12),x.useDepthPacking&&a.enable(13),x.dithering&&a.enable(14),x.transmission&&a.enable(15),x.sheen&&a.enable(16),x.opaque&&a.enable(17),x.pointsUvs&&a.enable(18),x.decodeVideoTexture&&a.enable(19),x.decodeVideoTextureEmissive&&a.enable(20),x.alphaToCoverage&&a.enable(21),_.push(a.mask)}function y(_){const x=g[_.type];let R;if(x){const O=ci[x];R=_S.clone(O.uniforms)}else R=_.uniforms;return R}function S(_,x){let R=u.get(x);return R!==void 0?++R.usedTimes:(R=new EE(i,x,_,r),d.push(R),u.set(x,R)),R}function C(_){if(--_.usedTimes===0){const x=d.indexOf(_);d[x]=d[d.length-1],d.pop(),u.delete(_.cacheKey),_.destroy()}}function w(_){c.remove(_)}function k(){c.dispose()}return{getParameters:m,getProgramCacheKey:p,getUniforms:y,acquireProgram:S,releaseProgram:C,releaseShaderCache:w,programs:d,dispose:k}}function PE(){let i=new WeakMap;function e(o){return i.has(o)}function t(o){let a=i.get(o);return a===void 0&&(a={},i.set(o,a)),a}function n(o){i.delete(o)}function s(o,a,c){i.get(o)[a]=c}function r(){i=new WeakMap}return{has:e,get:t,remove:n,update:s,dispose:r}}function kE(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.z!==e.z?i.z-e.z:i.id-e.id}function og(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function cg(){const i=[];let e=0;const t=[],n=[],s=[];function r(){e=0,t.length=0,n.length=0,s.length=0}function o(u,h,f,g,v,m){let p=i[e];return p===void 0?(p={id:u.id,object:u,geometry:h,material:f,groupOrder:g,renderOrder:u.renderOrder,z:v,group:m},i[e]=p):(p.id=u.id,p.object=u,p.geometry=h,p.material=f,p.groupOrder=g,p.renderOrder=u.renderOrder,p.z=v,p.group=m),e++,p}function a(u,h,f,g,v,m){const p=o(u,h,f,g,v,m);f.transmission>0?n.push(p):f.transparent===!0?s.push(p):t.push(p)}function c(u,h,f,g,v,m){const p=o(u,h,f,g,v,m);f.transmission>0?n.unshift(p):f.transparent===!0?s.unshift(p):t.unshift(p)}function l(u,h){t.length>1&&t.sort(u||kE),n.length>1&&n.sort(h||og),s.length>1&&s.sort(h||og)}function d(){for(let u=e,h=i.length;u<h;u++){const f=i[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:n,transparent:s,init:r,push:a,unshift:c,finish:d,sort:l}}function IE(){let i=new WeakMap;function e(n,s){const r=i.get(n);let o;return r===void 0?(o=new cg,i.set(n,[o])):s>=r.length?(o=new cg,r.push(o)):o=r[s],o}function t(){i=new WeakMap}return{get:e,dispose:t}}function DE(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new U,color:new Fe};break;case"SpotLight":t={position:new U,direction:new U,color:new Fe,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new U,color:new Fe,distance:0,decay:0};break;case"HemisphereLight":t={direction:new U,skyColor:new Fe,groundColor:new Fe};break;case"RectAreaLight":t={color:new Fe,position:new U,halfWidth:new U,halfHeight:new U};break}return i[e.id]=t,t}}}function LE(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new tt};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new tt};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new tt,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let NE=0;function OE(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function UE(i){const e=new DE,t=LE(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new U);const s=new U,r=new At,o=new At;function a(l){let d=0,u=0,h=0;for(let _=0;_<9;_++)n.probe[_].set(0,0,0);let f=0,g=0,v=0,m=0,p=0,T=0,E=0,y=0,S=0,C=0,w=0;l.sort(OE);for(let _=0,x=l.length;_<x;_++){const R=l[_],O=R.color,F=R.intensity,q=R.distance;let K=null;if(R.shadow&&R.shadow.map&&(R.shadow.map.texture.format===Qs?K=R.shadow.map.texture:K=R.shadow.map.depthTexture||R.shadow.map.texture),R.isAmbientLight)d+=O.r*F,u+=O.g*F,h+=O.b*F;else if(R.isLightProbe){for(let G=0;G<9;G++)n.probe[G].addScaledVector(R.sh.coefficients[G],F);w++}else if(R.isDirectionalLight){const G=e.get(R);if(G.color.copy(R.color).multiplyScalar(R.intensity),R.castShadow){const W=R.shadow,te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,n.directionalShadow[f]=te,n.directionalShadowMap[f]=K,n.directionalShadowMatrix[f]=R.shadow.matrix,T++}n.directional[f]=G,f++}else if(R.isSpotLight){const G=e.get(R);G.position.setFromMatrixPosition(R.matrixWorld),G.color.copy(O).multiplyScalar(F),G.distance=q,G.coneCos=Math.cos(R.angle),G.penumbraCos=Math.cos(R.angle*(1-R.penumbra)),G.decay=R.decay,n.spot[v]=G;const W=R.shadow;if(R.map&&(n.spotLightMap[S]=R.map,S++,W.updateMatrices(R),R.castShadow&&C++),n.spotLightMatrix[v]=W.matrix,R.castShadow){const te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,n.spotShadow[v]=te,n.spotShadowMap[v]=K,y++}v++}else if(R.isRectAreaLight){const G=e.get(R);G.color.copy(O).multiplyScalar(F),G.halfWidth.set(R.width*.5,0,0),G.halfHeight.set(0,R.height*.5,0),n.rectArea[m]=G,m++}else if(R.isPointLight){const G=e.get(R);if(G.color.copy(R.color).multiplyScalar(R.intensity),G.distance=R.distance,G.decay=R.decay,R.castShadow){const W=R.shadow,te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,te.shadowCameraNear=W.camera.near,te.shadowCameraFar=W.camera.far,n.pointShadow[g]=te,n.pointShadowMap[g]=K,n.pointShadowMatrix[g]=R.shadow.matrix,E++}n.point[g]=G,g++}else if(R.isHemisphereLight){const G=e.get(R);G.skyColor.copy(R.color).multiplyScalar(F),G.groundColor.copy(R.groundColor).multiplyScalar(F),n.hemi[p]=G,p++}}m>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ve.LTC_FLOAT_1,n.rectAreaLTC2=ve.LTC_FLOAT_2):(n.rectAreaLTC1=ve.LTC_HALF_1,n.rectAreaLTC2=ve.LTC_HALF_2)),n.ambient[0]=d,n.ambient[1]=u,n.ambient[2]=h;const k=n.hash;(k.directionalLength!==f||k.pointLength!==g||k.spotLength!==v||k.rectAreaLength!==m||k.hemiLength!==p||k.numDirectionalShadows!==T||k.numPointShadows!==E||k.numSpotShadows!==y||k.numSpotMaps!==S||k.numLightProbes!==w)&&(n.directional.length=f,n.spot.length=v,n.rectArea.length=m,n.point.length=g,n.hemi.length=p,n.directionalShadow.length=T,n.directionalShadowMap.length=T,n.pointShadow.length=E,n.pointShadowMap.length=E,n.spotShadow.length=y,n.spotShadowMap.length=y,n.directionalShadowMatrix.length=T,n.pointShadowMatrix.length=E,n.spotLightMatrix.length=y+S-C,n.spotLightMap.length=S,n.numSpotLightShadowsWithMaps=C,n.numLightProbes=w,k.directionalLength=f,k.pointLength=g,k.spotLength=v,k.rectAreaLength=m,k.hemiLength=p,k.numDirectionalShadows=T,k.numPointShadows=E,k.numSpotShadows=y,k.numSpotMaps=S,k.numLightProbes=w,n.version=NE++)}function c(l,d){let u=0,h=0,f=0,g=0,v=0;const m=d.matrixWorldInverse;for(let p=0,T=l.length;p<T;p++){const E=l[p];if(E.isDirectionalLight){const y=n.directional[u];y.direction.setFromMatrixPosition(E.matrixWorld),s.setFromMatrixPosition(E.target.matrixWorld),y.direction.sub(s),y.direction.transformDirection(m),u++}else if(E.isSpotLight){const y=n.spot[f];y.position.setFromMatrixPosition(E.matrixWorld),y.position.applyMatrix4(m),y.direction.setFromMatrixPosition(E.matrixWorld),s.setFromMatrixPosition(E.target.matrixWorld),y.direction.sub(s),y.direction.transformDirection(m),f++}else if(E.isRectAreaLight){const y=n.rectArea[g];y.position.setFromMatrixPosition(E.matrixWorld),y.position.applyMatrix4(m),o.identity(),r.copy(E.matrixWorld),r.premultiply(m),o.extractRotation(r),y.halfWidth.set(E.width*.5,0,0),y.halfHeight.set(0,E.height*.5,0),y.halfWidth.applyMatrix4(o),y.halfHeight.applyMatrix4(o),g++}else if(E.isPointLight){const y=n.point[h];y.position.setFromMatrixPosition(E.matrixWorld),y.position.applyMatrix4(m),h++}else if(E.isHemisphereLight){const y=n.hemi[v];y.direction.setFromMatrixPosition(E.matrixWorld),y.direction.transformDirection(m),v++}}}return{setup:a,setupView:c,state:n}}function lg(i){const e=new UE(i),t=[],n=[];function s(d){l.camera=d,t.length=0,n.length=0}function r(d){t.push(d)}function o(d){n.push(d)}function a(){e.setup(t)}function c(d){e.setupView(t,d)}const l={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:s,state:l,setupLights:a,setupLightsView:c,pushLight:r,pushShadow:o}}function FE(i){let e=new WeakMap;function t(s,r=0){const o=e.get(s);let a;return o===void 0?(a=new lg(i),e.set(s,[a])):r>=o.length?(a=new lg(i),o.push(a)):a=o[r],a}function n(){e=new WeakMap}return{get:t,dispose:n}}const BE=`void main() {
4052
4052
  gl_Position = vec4( position, 1.0 );
4053
4053
  }`,zE=`uniform sampler2D shadow_pass;
4054
4054
  uniform vec2 resolution;
@@ -4075,7 +4075,7 @@ void main() {
4075
4075
  squared_mean = squared_mean / samples;
4076
4076
  float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
4077
4077
  gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
4078
- }`,VE=[new U(1,0,0),new U(-1,0,0),new U(0,1,0),new U(0,-1,0),new U(0,0,1),new U(0,0,-1)],GE=[new U(0,-1,0),new U(0,-1,0),new U(0,0,1),new U(0,0,-1),new U(0,-1,0),new U(0,-1,0)],dg=new At,fa=new U,uu=new U;function HE(i,e,t){let n=new Kd;const s=new tt,r=new tt,o=new Dt,a=new NS,c=new OS,l={},d=t.maxTextureSize,u={[_i]:tn,[tn]:_i,[Si]:Si},h=new en({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new tt},radius:{value:4}},vertexShader:BE,fragmentShader:zE}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const g=new hn;g.setAttribute("position",new _n(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Sn(g,h),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=ao;let p=this.type;this.render=function(C,w,k){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||C.length===0)return;C.type===x_&&(Be("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),C.type=ao);const _=i.getRenderTarget(),x=i.getActiveCubeFace(),R=i.getActiveMipmapLevel(),O=i.state;O.setBlending(xi),O.buffers.depth.getReversed()===!0?O.buffers.color.setClear(0,0,0,0):O.buffers.color.setClear(1,1,1,1),O.buffers.depth.setTest(!0),O.setScissorTest(!1);const F=p!==this.type;F&&w.traverse(function(q){q.material&&(Array.isArray(q.material)?q.material.forEach(K=>K.needsUpdate=!0):q.material.needsUpdate=!0)});for(let q=0,K=C.length;q<K;q++){const G=C[q],W=G.shadow;if(W===void 0){Be("WebGLShadowMap:",G,"has no shadow.");continue}if(W.autoUpdate===!1&&W.needsUpdate===!1)continue;s.copy(W.mapSize);const te=W.getFrameExtents();if(s.multiply(te),r.copy(W.mapSize),(s.x>d||s.y>d)&&(s.x>d&&(r.x=Math.floor(d/te.x),s.x=r.x*te.x,W.mapSize.x=r.x),s.y>d&&(r.y=Math.floor(d/te.y),s.y=r.y*te.y,W.mapSize.y=r.y)),W.map===null||F===!0){if(W.map!==null&&(W.map.depthTexture!==null&&(W.map.depthTexture.dispose(),W.map.depthTexture=null),W.map.dispose()),this.type===Kr){if(G.isPointLight){Be("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}W.map=new oi(s.x,s.y,{format:Qs,type:Ci,minFilter:nn,magFilter:nn,generateMipmaps:!1}),W.map.texture.name=G.name+".shadowMap",W.map.depthTexture=new da(s.x,s.y,ri),W.map.depthTexture.name=G.name+".shadowMapDepth",W.map.depthTexture.format=Ei,W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Qt,W.map.depthTexture.magFilter=Qt}else{G.isPointLight?(W.map=new Em(s.x),W.map.depthTexture=new DS(s.x,si)):(W.map=new oi(s.x,s.y),W.map.depthTexture=new da(s.x,s.y,si)),W.map.depthTexture.name=G.name+".shadowMap",W.map.depthTexture.format=Ei;const de=i.state.buffers.depth.getReversed();this.type===ao?(W.map.depthTexture.compareFunction=de?Sd:_d,W.map.depthTexture.minFilter=nn,W.map.depthTexture.magFilter=nn):(W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Qt,W.map.depthTexture.magFilter=Qt)}W.camera.updateProjectionMatrix()}const ye=W.map.isWebGLCubeRenderTarget?6:1;for(let de=0;de<ye;de++){if(W.map.isWebGLCubeRenderTarget)i.setRenderTarget(W.map,de),i.clear();else{de===0&&(i.setRenderTarget(W.map),i.clear());const _e=W.getViewport(de);o.set(r.x*_e.x,r.y*_e.y,r.x*_e.z,r.y*_e.w),O.viewport(o)}if(G.isPointLight){const _e=W.camera,Ge=W.matrix,Ve=G.distance||_e.far;Ve!==_e.far&&(_e.far=Ve,_e.updateProjectionMatrix()),fa.setFromMatrixPosition(G.matrixWorld),_e.position.copy(fa),uu.copy(_e.position),uu.add(VE[de]),_e.up.copy(GE[de]),_e.lookAt(uu),_e.updateMatrixWorld(),Ge.makeTranslation(-fa.x,-fa.y,-fa.z),dg.multiplyMatrices(_e.projectionMatrix,_e.matrixWorldInverse),W._frustum.setFromProjectionMatrix(dg,_e.coordinateSystem,_e.reversedDepth)}else W.updateMatrices(G);n=W.getFrustum(),y(w,k,W.camera,G,this.type)}W.isPointLightShadow!==!0&&this.type===Kr&&T(W,k),W.needsUpdate=!1}p=this.type,m.needsUpdate=!1,i.setRenderTarget(_,x,R)};function T(C,w){const k=e.update(v);h.defines.VSM_SAMPLES!==C.blurSamples&&(h.defines.VSM_SAMPLES=C.blurSamples,f.defines.VSM_SAMPLES=C.blurSamples,h.needsUpdate=!0,f.needsUpdate=!0),C.mapPass===null&&(C.mapPass=new oi(s.x,s.y,{format:Qs,type:Ci})),h.uniforms.shadow_pass.value=C.map.depthTexture,h.uniforms.resolution.value=C.mapSize,h.uniforms.radius.value=C.radius,i.setRenderTarget(C.mapPass),i.clear(),i.renderBufferDirect(w,null,k,h,v,null),f.uniforms.shadow_pass.value=C.mapPass.texture,f.uniforms.resolution.value=C.mapSize,f.uniforms.radius.value=C.radius,i.setRenderTarget(C.map),i.clear(),i.renderBufferDirect(w,null,k,f,v,null)}function E(C,w,k,_){let x=null;const R=k.isPointLight===!0?C.customDistanceMaterial:C.customDepthMaterial;if(R!==void 0)x=R;else if(x=k.isPointLight===!0?c:a,i.localClippingEnabled&&w.clipShadows===!0&&Array.isArray(w.clippingPlanes)&&w.clippingPlanes.length!==0||w.displacementMap&&w.displacementScale!==0||w.alphaMap&&w.alphaTest>0||w.map&&w.alphaTest>0||w.alphaToCoverage===!0){const O=x.uuid,F=w.uuid;let q=l[O];q===void 0&&(q={},l[O]=q);let K=q[F];K===void 0&&(K=x.clone(),q[F]=K,w.addEventListener("dispose",S)),x=K}if(x.visible=w.visible,x.wireframe=w.wireframe,_===Kr?x.side=w.shadowSide!==null?w.shadowSide:w.side:x.side=w.shadowSide!==null?w.shadowSide:u[w.side],x.alphaMap=w.alphaMap,x.alphaTest=w.alphaToCoverage===!0?.5:w.alphaTest,x.map=w.map,x.clipShadows=w.clipShadows,x.clippingPlanes=w.clippingPlanes,x.clipIntersection=w.clipIntersection,x.displacementMap=w.displacementMap,x.displacementScale=w.displacementScale,x.displacementBias=w.displacementBias,x.wireframeLinewidth=w.wireframeLinewidth,x.linewidth=w.linewidth,k.isPointLight===!0&&x.isMeshDistanceMaterial===!0){const O=i.properties.get(x);O.light=k}return x}function y(C,w,k,_,x){if(C.visible===!1)return;if(C.layers.test(w.layers)&&(C.isMesh||C.isLine||C.isPoints)&&(C.castShadow||C.receiveShadow&&x===Kr)&&(!C.frustumCulled||n.intersectsObject(C))){C.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse,C.matrixWorld);const F=e.update(C),q=C.material;if(Array.isArray(q)){const K=F.groups;for(let G=0,W=K.length;G<W;G++){const te=K[G],ye=q[te.materialIndex];if(ye&&ye.visible){const de=E(C,ye,_,x);C.onBeforeShadow(i,C,w,k,F,de,te),i.renderBufferDirect(k,null,F,de,C,te),C.onAfterShadow(i,C,w,k,F,de,te)}}}else if(q.visible){const K=E(C,q,_,x);C.onBeforeShadow(i,C,w,k,F,K,null),i.renderBufferDirect(k,null,F,K,C,null),C.onAfterShadow(i,C,w,k,F,K,null)}}const O=C.children;for(let F=0,q=O.length;F<q;F++)y(O[F],w,k,_,x)}function S(C){C.target.removeEventListener("dispose",S);for(const k in l){const _=l[k],x=C.target.uuid;x in _&&(_[x].dispose(),delete _[x])}}}const WE={[Cl]:El,[Ml]:Rl,[wl]:Pl,[Js]:Al,[El]:Cl,[Rl]:Ml,[Pl]:wl,[Al]:Js};function qE(i,e){function t(){let D=!1;const Se=new Dt;let oe=null;const xe=new Dt(0,0,0,0);return{setMask:function(se){oe!==se&&!D&&(i.colorMask(se,se,se,se),oe=se)},setLocked:function(se){D=se},setClear:function(se,Q,ue,ze,St){St===!0&&(se*=ze,Q*=ze,ue*=ze),Se.set(se,Q,ue,ze),xe.equals(Se)===!1&&(i.clearColor(se,Q,ue,ze),xe.copy(Se))},reset:function(){D=!1,oe=null,xe.set(-1,0,0,0)}}}function n(){let D=!1,Se=!1,oe=null,xe=null,se=null;return{setReversed:function(Q){if(Se!==Q){const ue=e.get("EXT_clip_control");Q?ue.clipControlEXT(ue.LOWER_LEFT_EXT,ue.ZERO_TO_ONE_EXT):ue.clipControlEXT(ue.LOWER_LEFT_EXT,ue.NEGATIVE_ONE_TO_ONE_EXT),Se=Q;const ze=se;se=null,this.setClear(ze)}},getReversed:function(){return Se},setTest:function(Q){Q?ie(i.DEPTH_TEST):Ce(i.DEPTH_TEST)},setMask:function(Q){oe!==Q&&!D&&(i.depthMask(Q),oe=Q)},setFunc:function(Q){if(Se&&(Q=WE[Q]),xe!==Q){switch(Q){case Cl:i.depthFunc(i.NEVER);break;case El:i.depthFunc(i.ALWAYS);break;case Ml:i.depthFunc(i.LESS);break;case Js:i.depthFunc(i.LEQUAL);break;case wl:i.depthFunc(i.EQUAL);break;case Al:i.depthFunc(i.GEQUAL);break;case Rl:i.depthFunc(i.GREATER);break;case Pl:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}xe=Q}},setLocked:function(Q){D=Q},setClear:function(Q){se!==Q&&(Se&&(Q=1-Q),i.clearDepth(Q),se=Q)},reset:function(){D=!1,oe=null,xe=null,se=null,Se=!1}}}function s(){let D=!1,Se=null,oe=null,xe=null,se=null,Q=null,ue=null,ze=null,St=null;return{setTest:function(ut){D||(ut?ie(i.STENCIL_TEST):Ce(i.STENCIL_TEST))},setMask:function(ut){Se!==ut&&!D&&(i.stencilMask(ut),Se=ut)},setFunc:function(ut,hi,Di){(oe!==ut||xe!==hi||se!==Di)&&(i.stencilFunc(ut,hi,Di),oe=ut,xe=hi,se=Di)},setOp:function(ut,hi,Di){(Q!==ut||ue!==hi||ze!==Di)&&(i.stencilOp(ut,hi,Di),Q=ut,ue=hi,ze=Di)},setLocked:function(ut){D=ut},setClear:function(ut){St!==ut&&(i.clearStencil(ut),St=ut)},reset:function(){D=!1,Se=null,oe=null,xe=null,se=null,Q=null,ue=null,ze=null,St=null}}}const r=new t,o=new n,a=new s,c=new WeakMap,l=new WeakMap;let d={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,T=null,E=null,y=null,S=null,C=null,w=new Fe(0,0,0),k=0,_=!1,x=null,R=null,O=null,F=null,q=null;const K=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let G=!1,W=0;const te=i.getParameter(i.VERSION);te.indexOf("WebGL")!==-1?(W=parseFloat(/^WebGL (\d)/.exec(te)[1]),G=W>=1):te.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(te)[1]),G=W>=2);let ye=null,de={};const _e=i.getParameter(i.SCISSOR_BOX),Ge=i.getParameter(i.VIEWPORT),Ve=new Dt().fromArray(_e),Mt=new Dt().fromArray(Ge);function pt(D,Se,oe,xe){const se=new Uint8Array(4),Q=i.createTexture();i.bindTexture(D,Q),i.texParameteri(D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(D,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let ue=0;ue<oe;ue++)D===i.TEXTURE_3D||D===i.TEXTURE_2D_ARRAY?i.texImage3D(Se,0,i.RGBA,1,1,xe,0,i.RGBA,i.UNSIGNED_BYTE,se):i.texImage2D(Se+ue,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,se);return Q}const Y={};Y[i.TEXTURE_2D]=pt(i.TEXTURE_2D,i.TEXTURE_2D,1),Y[i.TEXTURE_CUBE_MAP]=pt(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),Y[i.TEXTURE_2D_ARRAY]=pt(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),Y[i.TEXTURE_3D]=pt(i.TEXTURE_3D,i.TEXTURE_3D,1,1),r.setClear(0,0,0,1),o.setClear(1),a.setClear(0),ie(i.DEPTH_TEST),o.setFunc(Js),$e(!1),Vt(Rp),ie(i.CULL_FACE),dt(xi);function ie(D){d[D]!==!0&&(i.enable(D),d[D]=!0)}function Ce(D){d[D]!==!1&&(i.disable(D),d[D]=!1)}function qe(D,Se){return u[D]!==Se?(i.bindFramebuffer(D,Se),u[D]=Se,D===i.DRAW_FRAMEBUFFER&&(u[i.FRAMEBUFFER]=Se),D===i.FRAMEBUFFER&&(u[i.DRAW_FRAMEBUFFER]=Se),!0):!1}function we(D,Se){let oe=f,xe=!1;if(D){oe=h.get(Se),oe===void 0&&(oe=[],h.set(Se,oe));const se=D.textures;if(oe.length!==se.length||oe[0]!==i.COLOR_ATTACHMENT0){for(let Q=0,ue=se.length;Q<ue;Q++)oe[Q]=i.COLOR_ATTACHMENT0+Q;oe.length=se.length,xe=!0}}else oe[0]!==i.BACK&&(oe[0]=i.BACK,xe=!0);xe&&i.drawBuffers(oe)}function rt(D){return g!==D?(i.useProgram(D),g=D,!0):!1}const Yt={[gs]:i.FUNC_ADD,[C_]:i.FUNC_SUBTRACT,[E_]:i.FUNC_REVERSE_SUBTRACT};Yt[M_]=i.MIN,Yt[w_]=i.MAX;const it={[A_]:i.ZERO,[R_]:i.ONE,[P_]:i.SRC_COLOR,[xl]:i.SRC_ALPHA,[O_]:i.SRC_ALPHA_SATURATE,[L_]:i.DST_COLOR,[I_]:i.DST_ALPHA,[k_]:i.ONE_MINUS_SRC_COLOR,[Tl]:i.ONE_MINUS_SRC_ALPHA,[N_]:i.ONE_MINUS_DST_COLOR,[D_]:i.ONE_MINUS_DST_ALPHA,[U_]:i.CONSTANT_COLOR,[F_]:i.ONE_MINUS_CONSTANT_COLOR,[B_]:i.CONSTANT_ALPHA,[z_]:i.ONE_MINUS_CONSTANT_ALPHA};function dt(D,Se,oe,xe,se,Q,ue,ze,St,ut){if(D===xi){v===!0&&(Ce(i.BLEND),v=!1);return}if(v===!1&&(ie(i.BLEND),v=!0),D!==T_){if(D!==m||ut!==_){if((p!==gs||y!==gs)&&(i.blendEquation(i.FUNC_ADD),p=gs,y=gs),ut)switch(D){case Ys:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Ji:i.blendFunc(i.ONE,i.ONE);break;case Pp:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case kp:i.blendFuncSeparate(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE);break;default:st("WebGLState: Invalid blending: ",D);break}else switch(D){case Ys:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Ji:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE,i.ONE,i.ONE);break;case Pp:st("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case kp:st("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:st("WebGLState: Invalid blending: ",D);break}T=null,E=null,S=null,C=null,w.set(0,0,0),k=0,m=D,_=ut}return}se=se||Se,Q=Q||oe,ue=ue||xe,(Se!==p||se!==y)&&(i.blendEquationSeparate(Yt[Se],Yt[se]),p=Se,y=se),(oe!==T||xe!==E||Q!==S||ue!==C)&&(i.blendFuncSeparate(it[oe],it[xe],it[Q],it[ue]),T=oe,E=xe,S=Q,C=ue),(ze.equals(w)===!1||St!==k)&&(i.blendColor(ze.r,ze.g,ze.b,St),w.copy(ze),k=St),m=D,_=!1}function yt(D,Se){D.side===Si?Ce(i.CULL_FACE):ie(i.CULL_FACE);let oe=D.side===tn;Se&&(oe=!oe),$e(oe),D.blending===Ys&&D.transparent===!1?dt(xi):dt(D.blending,D.blendEquation,D.blendSrc,D.blendDst,D.blendEquationAlpha,D.blendSrcAlpha,D.blendDstAlpha,D.blendColor,D.blendAlpha,D.premultipliedAlpha),o.setFunc(D.depthFunc),o.setTest(D.depthTest),o.setMask(D.depthWrite),r.setMask(D.colorWrite);const xe=D.stencilWrite;a.setTest(xe),xe&&(a.setMask(D.stencilWriteMask),a.setFunc(D.stencilFunc,D.stencilRef,D.stencilFuncMask),a.setOp(D.stencilFail,D.stencilZFail,D.stencilZPass)),Gt(D.polygonOffset,D.polygonOffsetFactor,D.polygonOffsetUnits),D.alphaToCoverage===!0?ie(i.SAMPLE_ALPHA_TO_COVERAGE):Ce(i.SAMPLE_ALPHA_TO_COVERAGE)}function $e(D){x!==D&&(D?i.frontFace(i.CW):i.frontFace(i.CCW),x=D)}function Vt(D){D!==__?(ie(i.CULL_FACE),D!==R&&(D===Rp?i.cullFace(i.BACK):D===S_?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):Ce(i.CULL_FACE),R=D}function I(D){D!==O&&(G&&i.lineWidth(D),O=D)}function Gt(D,Se,oe){D?(ie(i.POLYGON_OFFSET_FILL),(F!==Se||q!==oe)&&(i.polygonOffset(Se,oe),F=Se,q=oe)):Ce(i.POLYGON_OFFSET_FILL)}function ct(D){D?ie(i.SCISSOR_TEST):Ce(i.SCISSOR_TEST)}function _t(D){D===void 0&&(D=i.TEXTURE0+K-1),ye!==D&&(i.activeTexture(D),ye=D)}function Re(D,Se,oe){oe===void 0&&(ye===null?oe=i.TEXTURE0+K-1:oe=ye);let xe=de[oe];xe===void 0&&(xe={type:void 0,texture:void 0},de[oe]=xe),(xe.type!==D||xe.texture!==Se)&&(ye!==oe&&(i.activeTexture(oe),ye=oe),i.bindTexture(D,Se||Y[D]),xe.type=D,xe.texture=Se)}function A(){const D=de[ye];D!==void 0&&D.type!==void 0&&(i.bindTexture(D.type,null),D.type=void 0,D.texture=void 0)}function b(){try{i.compressedTexImage2D(...arguments)}catch(D){st("WebGLState:",D)}}function L(){try{i.compressedTexImage3D(...arguments)}catch(D){st("WebGLState:",D)}}function X(){try{i.texSubImage2D(...arguments)}catch(D){st("WebGLState:",D)}}function ee(){try{i.texSubImage3D(...arguments)}catch(D){st("WebGLState:",D)}}function j(){try{i.compressedTexSubImage2D(...arguments)}catch(D){st("WebGLState:",D)}}function ke(){try{i.compressedTexSubImage3D(...arguments)}catch(D){st("WebGLState:",D)}}function he(){try{i.texStorage2D(...arguments)}catch(D){st("WebGLState:",D)}}function Ae(){try{i.texStorage3D(...arguments)}catch(D){st("WebGLState:",D)}}function Ue(){try{i.texImage2D(...arguments)}catch(D){st("WebGLState:",D)}}function re(){try{i.texImage3D(...arguments)}catch(D){st("WebGLState:",D)}}function me(D){Ve.equals(D)===!1&&(i.scissor(D.x,D.y,D.z,D.w),Ve.copy(D))}function Me(D){Mt.equals(D)===!1&&(i.viewport(D.x,D.y,D.z,D.w),Mt.copy(D))}function Pe(D,Se){let oe=l.get(Se);oe===void 0&&(oe=new WeakMap,l.set(Se,oe));let xe=oe.get(D);xe===void 0&&(xe=i.getUniformBlockIndex(Se,D.name),oe.set(D,xe))}function fe(D,Se){const xe=l.get(Se).get(D);c.get(Se)!==xe&&(i.uniformBlockBinding(Se,xe,D.__bindingPointIndex),c.set(Se,xe))}function Xe(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.blendColor(0,0,0,0),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),o.setReversed(!1),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),d={},ye=null,de={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,T=null,E=null,y=null,S=null,C=null,w=new Fe(0,0,0),k=0,_=!1,x=null,R=null,O=null,F=null,q=null,Ve.set(0,0,i.canvas.width,i.canvas.height),Mt.set(0,0,i.canvas.width,i.canvas.height),r.reset(),o.reset(),a.reset()}return{buffers:{color:r,depth:o,stencil:a},enable:ie,disable:Ce,bindFramebuffer:qe,drawBuffers:we,useProgram:rt,setBlending:dt,setMaterial:yt,setFlipSided:$e,setCullFace:Vt,setLineWidth:I,setPolygonOffset:Gt,setScissorTest:ct,activeTexture:_t,bindTexture:Re,unbindTexture:A,compressedTexImage2D:b,compressedTexImage3D:L,texImage2D:Ue,texImage3D:re,updateUBOMapping:Pe,uniformBlockBinding:fe,texStorage2D:he,texStorage3D:Ae,texSubImage2D:X,texSubImage3D:ee,compressedTexSubImage2D:j,compressedTexSubImage3D:ke,scissor:me,viewport:Me,reset:Xe}}function jE(i,e,t,n,s,r,o){const a=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new tt,d=new WeakMap;let u;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(A,b){return f?new OffscreenCanvas(A,b):go("canvas")}function v(A,b,L){let X=1;const ee=Re(A);if((ee.width>L||ee.height>L)&&(X=L/Math.max(ee.width,ee.height)),X<1)if(typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&A instanceof ImageBitmap||typeof VideoFrame<"u"&&A instanceof VideoFrame){const j=Math.floor(X*ee.width),ke=Math.floor(X*ee.height);u===void 0&&(u=g(j,ke));const he=b?g(j,ke):u;return he.width=j,he.height=ke,he.getContext("2d").drawImage(A,0,0,j,ke),Be("WebGLRenderer: Texture has been resized from ("+ee.width+"x"+ee.height+") to ("+j+"x"+ke+")."),he}else return"data"in A&&Be("WebGLRenderer: Image in DataTexture is too big ("+ee.width+"x"+ee.height+")."),A;return A}function m(A){return A.generateMipmaps}function p(A){i.generateMipmap(A)}function T(A){return A.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:A.isWebGL3DRenderTarget?i.TEXTURE_3D:A.isWebGLArrayRenderTarget||A.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function E(A,b,L,X,ee=!1){if(A!==null){if(i[A]!==void 0)return i[A];Be("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+A+"'")}let j=b;if(b===i.RED&&(L===i.FLOAT&&(j=i.R32F),L===i.HALF_FLOAT&&(j=i.R16F),L===i.UNSIGNED_BYTE&&(j=i.R8)),b===i.RED_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.R8UI),L===i.UNSIGNED_SHORT&&(j=i.R16UI),L===i.UNSIGNED_INT&&(j=i.R32UI),L===i.BYTE&&(j=i.R8I),L===i.SHORT&&(j=i.R16I),L===i.INT&&(j=i.R32I)),b===i.RG&&(L===i.FLOAT&&(j=i.RG32F),L===i.HALF_FLOAT&&(j=i.RG16F),L===i.UNSIGNED_BYTE&&(j=i.RG8)),b===i.RG_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RG8UI),L===i.UNSIGNED_SHORT&&(j=i.RG16UI),L===i.UNSIGNED_INT&&(j=i.RG32UI),L===i.BYTE&&(j=i.RG8I),L===i.SHORT&&(j=i.RG16I),L===i.INT&&(j=i.RG32I)),b===i.RGB_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGB8UI),L===i.UNSIGNED_SHORT&&(j=i.RGB16UI),L===i.UNSIGNED_INT&&(j=i.RGB32UI),L===i.BYTE&&(j=i.RGB8I),L===i.SHORT&&(j=i.RGB16I),L===i.INT&&(j=i.RGB32I)),b===i.RGBA_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGBA8UI),L===i.UNSIGNED_SHORT&&(j=i.RGBA16UI),L===i.UNSIGNED_INT&&(j=i.RGBA32UI),L===i.BYTE&&(j=i.RGBA8I),L===i.SHORT&&(j=i.RGBA16I),L===i.INT&&(j=i.RGBA32I)),b===i.RGB&&(L===i.UNSIGNED_INT_5_9_9_9_REV&&(j=i.RGB9_E5),L===i.UNSIGNED_INT_10F_11F_11F_REV&&(j=i.R11F_G11F_B10F)),b===i.RGBA){const ke=ee?po:nt.getTransfer(X);L===i.FLOAT&&(j=i.RGBA32F),L===i.HALF_FLOAT&&(j=i.RGBA16F),L===i.UNSIGNED_BYTE&&(j=ke===lt?i.SRGB8_ALPHA8:i.RGBA8),L===i.UNSIGNED_SHORT_4_4_4_4&&(j=i.RGBA4),L===i.UNSIGNED_SHORT_5_5_5_1&&(j=i.RGB5_A1)}return(j===i.R16F||j===i.R32F||j===i.RG16F||j===i.RG32F||j===i.RGBA16F||j===i.RGBA32F)&&e.get("EXT_color_buffer_float"),j}function y(A,b){let L;return A?b===null||b===si||b===Jr?L=i.DEPTH24_STENCIL8:b===ri?L=i.DEPTH32F_STENCIL8:b===Yr&&(L=i.DEPTH24_STENCIL8,Be("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):b===null||b===si||b===Jr?L=i.DEPTH_COMPONENT24:b===ri?L=i.DEPTH_COMPONENT32F:b===Yr&&(L=i.DEPTH_COMPONENT16),L}function S(A,b){return m(A)===!0||A.isFramebufferTexture&&A.minFilter!==Qt&&A.minFilter!==nn?Math.log2(Math.max(b.width,b.height))+1:A.mipmaps!==void 0&&A.mipmaps.length>0?A.mipmaps.length:A.isCompressedTexture&&Array.isArray(A.image)?b.mipmaps.length:1}function C(A){const b=A.target;b.removeEventListener("dispose",C),k(b),b.isVideoTexture&&d.delete(b)}function w(A){const b=A.target;b.removeEventListener("dispose",w),x(b)}function k(A){const b=n.get(A);if(b.__webglInit===void 0)return;const L=A.source,X=h.get(L);if(X){const ee=X[b.__cacheKey];ee.usedTimes--,ee.usedTimes===0&&_(A),Object.keys(X).length===0&&h.delete(L)}n.remove(A)}function _(A){const b=n.get(A);i.deleteTexture(b.__webglTexture);const L=A.source,X=h.get(L);delete X[b.__cacheKey],o.memory.textures--}function x(A){const b=n.get(A);if(A.depthTexture&&(A.depthTexture.dispose(),n.remove(A.depthTexture)),A.isWebGLCubeRenderTarget)for(let X=0;X<6;X++){if(Array.isArray(b.__webglFramebuffer[X]))for(let ee=0;ee<b.__webglFramebuffer[X].length;ee++)i.deleteFramebuffer(b.__webglFramebuffer[X][ee]);else i.deleteFramebuffer(b.__webglFramebuffer[X]);b.__webglDepthbuffer&&i.deleteRenderbuffer(b.__webglDepthbuffer[X])}else{if(Array.isArray(b.__webglFramebuffer))for(let X=0;X<b.__webglFramebuffer.length;X++)i.deleteFramebuffer(b.__webglFramebuffer[X]);else i.deleteFramebuffer(b.__webglFramebuffer);if(b.__webglDepthbuffer&&i.deleteRenderbuffer(b.__webglDepthbuffer),b.__webglMultisampledFramebuffer&&i.deleteFramebuffer(b.__webglMultisampledFramebuffer),b.__webglColorRenderbuffer)for(let X=0;X<b.__webglColorRenderbuffer.length;X++)b.__webglColorRenderbuffer[X]&&i.deleteRenderbuffer(b.__webglColorRenderbuffer[X]);b.__webglDepthRenderbuffer&&i.deleteRenderbuffer(b.__webglDepthRenderbuffer)}const L=A.textures;for(let X=0,ee=L.length;X<ee;X++){const j=n.get(L[X]);j.__webglTexture&&(i.deleteTexture(j.__webglTexture),o.memory.textures--),n.remove(L[X])}n.remove(A)}let R=0;function O(){R=0}function F(){const A=R;return A>=s.maxTextures&&Be("WebGLTextures: Trying to use "+A+" texture units while this GPU supports only "+s.maxTextures),R+=1,A}function q(A){const b=[];return b.push(A.wrapS),b.push(A.wrapT),b.push(A.wrapR||0),b.push(A.magFilter),b.push(A.minFilter),b.push(A.anisotropy),b.push(A.internalFormat),b.push(A.format),b.push(A.type),b.push(A.generateMipmaps),b.push(A.premultiplyAlpha),b.push(A.flipY),b.push(A.unpackAlignment),b.push(A.colorSpace),b.join()}function K(A,b){const L=n.get(A);if(A.isVideoTexture&&ct(A),A.isRenderTargetTexture===!1&&A.isExternalTexture!==!0&&A.version>0&&L.__version!==A.version){const X=A.image;if(X===null)Be("WebGLRenderer: Texture marked for update but no image data found.");else if(X.complete===!1)Be("WebGLRenderer: Texture marked for update but image is incomplete");else{Y(L,A,b);return}}else A.isExternalTexture&&(L.__webglTexture=A.sourceTexture?A.sourceTexture:null);t.bindTexture(i.TEXTURE_2D,L.__webglTexture,i.TEXTURE0+b)}function G(A,b){const L=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&L.__version!==A.version){Y(L,A,b);return}else A.isExternalTexture&&(L.__webglTexture=A.sourceTexture?A.sourceTexture:null);t.bindTexture(i.TEXTURE_2D_ARRAY,L.__webglTexture,i.TEXTURE0+b)}function W(A,b){const L=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&L.__version!==A.version){Y(L,A,b);return}t.bindTexture(i.TEXTURE_3D,L.__webglTexture,i.TEXTURE0+b)}function te(A,b){const L=n.get(A);if(A.isCubeDepthTexture!==!0&&A.version>0&&L.__version!==A.version){ie(L,A,b);return}t.bindTexture(i.TEXTURE_CUBE_MAP,L.__webglTexture,i.TEXTURE0+b)}const ye={[Dl]:i.REPEAT,[Ti]:i.CLAMP_TO_EDGE,[Ll]:i.MIRRORED_REPEAT},de={[Qt]:i.NEAREST,[H_]:i.NEAREST_MIPMAP_NEAREST,[co]:i.NEAREST_MIPMAP_LINEAR,[nn]:i.LINEAR,[Nl]:i.LINEAR_MIPMAP_NEAREST,[ys]:i.LINEAR_MIPMAP_LINEAR},_e={[$_]:i.NEVER,[Z_]:i.ALWAYS,[X_]:i.LESS,[_d]:i.LEQUAL,[K_]:i.EQUAL,[Sd]:i.GEQUAL,[Y_]:i.GREATER,[J_]:i.NOTEQUAL};function Ge(A,b){if(b.type===ri&&e.has("OES_texture_float_linear")===!1&&(b.magFilter===nn||b.magFilter===Nl||b.magFilter===co||b.magFilter===ys||b.minFilter===nn||b.minFilter===Nl||b.minFilter===co||b.minFilter===ys)&&Be("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(A,i.TEXTURE_WRAP_S,ye[b.wrapS]),i.texParameteri(A,i.TEXTURE_WRAP_T,ye[b.wrapT]),(A===i.TEXTURE_3D||A===i.TEXTURE_2D_ARRAY)&&i.texParameteri(A,i.TEXTURE_WRAP_R,ye[b.wrapR]),i.texParameteri(A,i.TEXTURE_MAG_FILTER,de[b.magFilter]),i.texParameteri(A,i.TEXTURE_MIN_FILTER,de[b.minFilter]),b.compareFunction&&(i.texParameteri(A,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(A,i.TEXTURE_COMPARE_FUNC,_e[b.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(b.magFilter===Qt||b.minFilter!==co&&b.minFilter!==ys||b.type===ri&&e.has("OES_texture_float_linear")===!1)return;if(b.anisotropy>1||n.get(b).__currentAnisotropy){const L=e.get("EXT_texture_filter_anisotropic");i.texParameterf(A,L.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(b.anisotropy,s.getMaxAnisotropy())),n.get(b).__currentAnisotropy=b.anisotropy}}}function Ve(A,b){let L=!1;A.__webglInit===void 0&&(A.__webglInit=!0,b.addEventListener("dispose",C));const X=b.source;let ee=h.get(X);ee===void 0&&(ee={},h.set(X,ee));const j=q(b);if(j!==A.__cacheKey){ee[j]===void 0&&(ee[j]={texture:i.createTexture(),usedTimes:0},o.memory.textures++,L=!0),ee[j].usedTimes++;const ke=ee[A.__cacheKey];ke!==void 0&&(ee[A.__cacheKey].usedTimes--,ke.usedTimes===0&&_(b)),A.__cacheKey=j,A.__webglTexture=ee[j].texture}return L}function Mt(A,b,L){return Math.floor(Math.floor(A/L)/b)}function pt(A,b,L,X){const j=A.updateRanges;if(j.length===0)t.texSubImage2D(i.TEXTURE_2D,0,0,0,b.width,b.height,L,X,b.data);else{j.sort((re,me)=>re.start-me.start);let ke=0;for(let re=1;re<j.length;re++){const me=j[ke],Me=j[re],Pe=me.start+me.count,fe=Mt(Me.start,b.width,4),Xe=Mt(me.start,b.width,4);Me.start<=Pe+1&&fe===Xe&&Mt(Me.start+Me.count-1,b.width,4)===fe?me.count=Math.max(me.count,Me.start+Me.count-me.start):(++ke,j[ke]=Me)}j.length=ke+1;const he=i.getParameter(i.UNPACK_ROW_LENGTH),Ae=i.getParameter(i.UNPACK_SKIP_PIXELS),Ue=i.getParameter(i.UNPACK_SKIP_ROWS);i.pixelStorei(i.UNPACK_ROW_LENGTH,b.width);for(let re=0,me=j.length;re<me;re++){const Me=j[re],Pe=Math.floor(Me.start/4),fe=Math.ceil(Me.count/4),Xe=Pe%b.width,D=Math.floor(Pe/b.width),Se=fe,oe=1;i.pixelStorei(i.UNPACK_SKIP_PIXELS,Xe),i.pixelStorei(i.UNPACK_SKIP_ROWS,D),t.texSubImage2D(i.TEXTURE_2D,0,Xe,D,Se,oe,L,X,b.data)}A.clearUpdateRanges(),i.pixelStorei(i.UNPACK_ROW_LENGTH,he),i.pixelStorei(i.UNPACK_SKIP_PIXELS,Ae),i.pixelStorei(i.UNPACK_SKIP_ROWS,Ue)}}function Y(A,b,L){let X=i.TEXTURE_2D;(b.isDataArrayTexture||b.isCompressedArrayTexture)&&(X=i.TEXTURE_2D_ARRAY),b.isData3DTexture&&(X=i.TEXTURE_3D);const ee=Ve(A,b),j=b.source;t.bindTexture(X,A.__webglTexture,i.TEXTURE0+L);const ke=n.get(j);if(j.version!==ke.__version||ee===!0){t.activeTexture(i.TEXTURE0+L);const he=nt.getPrimaries(nt.workingColorSpace),Ae=b.colorSpace===Zi?null:nt.getPrimaries(b.colorSpace),Ue=b.colorSpace===Zi||he===Ae?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,b.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,b.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ue);let re=v(b.image,!1,s.maxTextureSize);re=_t(b,re);const me=r.convert(b.format,b.colorSpace),Me=r.convert(b.type);let Pe=E(b.internalFormat,me,Me,b.colorSpace,b.isVideoTexture);Ge(X,b);let fe;const Xe=b.mipmaps,D=b.isVideoTexture!==!0,Se=ke.__version===void 0||ee===!0,oe=j.dataReady,xe=S(b,re);if(b.isDepthTexture)Pe=y(b.format===bs,b.type),Se&&(D?t.texStorage2D(i.TEXTURE_2D,1,Pe,re.width,re.height):t.texImage2D(i.TEXTURE_2D,0,Pe,re.width,re.height,0,me,Me,null));else if(b.isDataTexture)if(Xe.length>0){D&&Se&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,Xe[0].width,Xe[0].height);for(let se=0,Q=Xe.length;se<Q;se++)fe=Xe[se],D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,fe.width,fe.height,me,Me,fe.data):t.texImage2D(i.TEXTURE_2D,se,Pe,fe.width,fe.height,0,me,Me,fe.data);b.generateMipmaps=!1}else D?(Se&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,re.width,re.height),oe&&pt(b,re,me,Me)):t.texImage2D(i.TEXTURE_2D,0,Pe,re.width,re.height,0,me,Me,re.data);else if(b.isCompressedTexture)if(b.isCompressedArrayTexture){D&&Se&&t.texStorage3D(i.TEXTURE_2D_ARRAY,xe,Pe,Xe[0].width,Xe[0].height,re.depth);for(let se=0,Q=Xe.length;se<Q;se++)if(fe=Xe[se],b.format!==qn)if(me!==null)if(D){if(oe)if(b.layerUpdates.size>0){const ue=Om(fe.width,fe.height,b.format,b.type);for(const ze of b.layerUpdates){const St=fe.data.subarray(ze*ue/fe.data.BYTES_PER_ELEMENT,(ze+1)*ue/fe.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,ze,fe.width,fe.height,1,me,St)}b.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,0,fe.width,fe.height,re.depth,me,fe.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,se,Pe,fe.width,fe.height,re.depth,0,fe.data,0,0);else Be("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else D?oe&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,0,fe.width,fe.height,re.depth,me,Me,fe.data):t.texImage3D(i.TEXTURE_2D_ARRAY,se,Pe,fe.width,fe.height,re.depth,0,me,Me,fe.data)}else{D&&Se&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,Xe[0].width,Xe[0].height);for(let se=0,Q=Xe.length;se<Q;se++)fe=Xe[se],b.format!==qn?me!==null?D?oe&&t.compressedTexSubImage2D(i.TEXTURE_2D,se,0,0,fe.width,fe.height,me,fe.data):t.compressedTexImage2D(i.TEXTURE_2D,se,Pe,fe.width,fe.height,0,fe.data):Be("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,fe.width,fe.height,me,Me,fe.data):t.texImage2D(i.TEXTURE_2D,se,Pe,fe.width,fe.height,0,me,Me,fe.data)}else if(b.isDataArrayTexture)if(D){if(Se&&t.texStorage3D(i.TEXTURE_2D_ARRAY,xe,Pe,re.width,re.height,re.depth),oe)if(b.layerUpdates.size>0){const se=Om(re.width,re.height,b.format,b.type);for(const Q of b.layerUpdates){const ue=re.data.subarray(Q*se/re.data.BYTES_PER_ELEMENT,(Q+1)*se/re.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,Q,re.width,re.height,1,me,Me,ue)}b.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,re.width,re.height,re.depth,me,Me,re.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,Pe,re.width,re.height,re.depth,0,me,Me,re.data);else if(b.isData3DTexture)D?(Se&&t.texStorage3D(i.TEXTURE_3D,xe,Pe,re.width,re.height,re.depth),oe&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,re.width,re.height,re.depth,me,Me,re.data)):t.texImage3D(i.TEXTURE_3D,0,Pe,re.width,re.height,re.depth,0,me,Me,re.data);else if(b.isFramebufferTexture){if(Se)if(D)t.texStorage2D(i.TEXTURE_2D,xe,Pe,re.width,re.height);else{let se=re.width,Q=re.height;for(let ue=0;ue<xe;ue++)t.texImage2D(i.TEXTURE_2D,ue,Pe,se,Q,0,me,Me,null),se>>=1,Q>>=1}}else if(Xe.length>0){if(D&&Se){const se=Re(Xe[0]);t.texStorage2D(i.TEXTURE_2D,xe,Pe,se.width,se.height)}for(let se=0,Q=Xe.length;se<Q;se++)fe=Xe[se],D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,me,Me,fe):t.texImage2D(i.TEXTURE_2D,se,Pe,me,Me,fe);b.generateMipmaps=!1}else if(D){if(Se){const se=Re(re);t.texStorage2D(i.TEXTURE_2D,xe,Pe,se.width,se.height)}oe&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,me,Me,re)}else t.texImage2D(i.TEXTURE_2D,0,Pe,me,Me,re);m(b)&&p(X),ke.__version=j.version,b.onUpdate&&b.onUpdate(b)}A.__version=b.version}function ie(A,b,L){if(b.image.length!==6)return;const X=Ve(A,b),ee=b.source;t.bindTexture(i.TEXTURE_CUBE_MAP,A.__webglTexture,i.TEXTURE0+L);const j=n.get(ee);if(ee.version!==j.__version||X===!0){t.activeTexture(i.TEXTURE0+L);const ke=nt.getPrimaries(nt.workingColorSpace),he=b.colorSpace===Zi?null:nt.getPrimaries(b.colorSpace),Ae=b.colorSpace===Zi||ke===he?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,b.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,b.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ae);const Ue=b.isCompressedTexture||b.image[0].isCompressedTexture,re=b.image[0]&&b.image[0].isDataTexture,me=[];for(let Q=0;Q<6;Q++)!Ue&&!re?me[Q]=v(b.image[Q],!0,s.maxCubemapSize):me[Q]=re?b.image[Q].image:b.image[Q],me[Q]=_t(b,me[Q]);const Me=me[0],Pe=r.convert(b.format,b.colorSpace),fe=r.convert(b.type),Xe=E(b.internalFormat,Pe,fe,b.colorSpace),D=b.isVideoTexture!==!0,Se=j.__version===void 0||X===!0,oe=ee.dataReady;let xe=S(b,Me);Ge(i.TEXTURE_CUBE_MAP,b);let se;if(Ue){D&&Se&&t.texStorage2D(i.TEXTURE_CUBE_MAP,xe,Xe,Me.width,Me.height);for(let Q=0;Q<6;Q++){se=me[Q].mipmaps;for(let ue=0;ue<se.length;ue++){const ze=se[ue];b.format!==qn?Pe!==null?D?oe&&t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,0,0,ze.width,ze.height,Pe,ze.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,Xe,ze.width,ze.height,0,ze.data):Be("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,0,0,ze.width,ze.height,Pe,fe,ze.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,Xe,ze.width,ze.height,0,Pe,fe,ze.data)}}}else{if(se=b.mipmaps,D&&Se){se.length>0&&xe++;const Q=Re(me[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,xe,Xe,Q.width,Q.height)}for(let Q=0;Q<6;Q++)if(re){D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,0,0,me[Q].width,me[Q].height,Pe,fe,me[Q].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,Xe,me[Q].width,me[Q].height,0,Pe,fe,me[Q].data);for(let ue=0;ue<se.length;ue++){const St=se[ue].image[Q].image;D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,0,0,St.width,St.height,Pe,fe,St.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,Xe,St.width,St.height,0,Pe,fe,St.data)}}else{D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,0,0,Pe,fe,me[Q]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,Xe,Pe,fe,me[Q]);for(let ue=0;ue<se.length;ue++){const ze=se[ue];D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,0,0,Pe,fe,ze.image[Q]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,Xe,Pe,fe,ze.image[Q])}}}m(b)&&p(i.TEXTURE_CUBE_MAP),j.__version=ee.version,b.onUpdate&&b.onUpdate(b)}A.__version=b.version}function Ce(A,b,L,X,ee,j){const ke=r.convert(L.format,L.colorSpace),he=r.convert(L.type),Ae=E(L.internalFormat,ke,he,L.colorSpace),Ue=n.get(b),re=n.get(L);if(re.__renderTarget=b,!Ue.__hasExternalTextures){const me=Math.max(1,b.width>>j),Me=Math.max(1,b.height>>j);ee===i.TEXTURE_3D||ee===i.TEXTURE_2D_ARRAY?t.texImage3D(ee,j,Ae,me,Me,b.depth,0,ke,he,null):t.texImage2D(ee,j,Ae,me,Me,0,ke,he,null)}t.bindFramebuffer(i.FRAMEBUFFER,A),Gt(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,X,ee,re.__webglTexture,0,I(b)):(ee===i.TEXTURE_2D||ee>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&ee<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,X,ee,re.__webglTexture,j),t.bindFramebuffer(i.FRAMEBUFFER,null)}function qe(A,b,L){if(i.bindRenderbuffer(i.RENDERBUFFER,A),b.depthBuffer){const X=b.depthTexture,ee=X&&X.isDepthTexture?X.type:null,j=y(b.stencilBuffer,ee),ke=b.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;Gt(b)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(b),j,b.width,b.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(b),j,b.width,b.height):i.renderbufferStorage(i.RENDERBUFFER,j,b.width,b.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,ke,i.RENDERBUFFER,A)}else{const X=b.textures;for(let ee=0;ee<X.length;ee++){const j=X[ee],ke=r.convert(j.format,j.colorSpace),he=r.convert(j.type),Ae=E(j.internalFormat,ke,he,j.colorSpace);Gt(b)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(b),Ae,b.width,b.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(b),Ae,b.width,b.height):i.renderbufferStorage(i.RENDERBUFFER,Ae,b.width,b.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function we(A,b,L){const X=b.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(i.FRAMEBUFFER,A),!(b.depthTexture&&b.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const ee=n.get(b.depthTexture);if(ee.__renderTarget=b,(!ee.__webglTexture||b.depthTexture.image.width!==b.width||b.depthTexture.image.height!==b.height)&&(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0),X){if(ee.__webglInit===void 0&&(ee.__webglInit=!0,b.depthTexture.addEventListener("dispose",C)),ee.__webglTexture===void 0){ee.__webglTexture=i.createTexture(),t.bindTexture(i.TEXTURE_CUBE_MAP,ee.__webglTexture),Ge(i.TEXTURE_CUBE_MAP,b.depthTexture);const Ue=r.convert(b.depthTexture.format),re=r.convert(b.depthTexture.type);let me;b.depthTexture.format===Ei?me=i.DEPTH_COMPONENT24:b.depthTexture.format===bs&&(me=i.DEPTH24_STENCIL8);for(let Me=0;Me<6;Me++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Me,0,me,b.width,b.height,0,Ue,re,null)}}else K(b.depthTexture,0);const j=ee.__webglTexture,ke=I(b),he=X?i.TEXTURE_CUBE_MAP_POSITIVE_X+L:i.TEXTURE_2D,Ae=b.depthTexture.format===bs?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;if(b.depthTexture.format===Ei)Gt(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Ae,he,j,0,ke):i.framebufferTexture2D(i.FRAMEBUFFER,Ae,he,j,0);else if(b.depthTexture.format===bs)Gt(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Ae,he,j,0,ke):i.framebufferTexture2D(i.FRAMEBUFFER,Ae,he,j,0);else throw new Error("Unknown depthTexture format")}function rt(A){const b=n.get(A),L=A.isWebGLCubeRenderTarget===!0;if(b.__boundDepthTexture!==A.depthTexture){const X=A.depthTexture;if(b.__depthDisposeCallback&&b.__depthDisposeCallback(),X){const ee=()=>{delete b.__boundDepthTexture,delete b.__depthDisposeCallback,X.removeEventListener("dispose",ee)};X.addEventListener("dispose",ee),b.__depthDisposeCallback=ee}b.__boundDepthTexture=X}if(A.depthTexture&&!b.__autoAllocateDepthBuffer)if(L)for(let X=0;X<6;X++)we(b.__webglFramebuffer[X],A,X);else{const X=A.texture.mipmaps;X&&X.length>0?we(b.__webglFramebuffer[0],A,0):we(b.__webglFramebuffer,A,0)}else if(L){b.__webglDepthbuffer=[];for(let X=0;X<6;X++)if(t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer[X]),b.__webglDepthbuffer[X]===void 0)b.__webglDepthbuffer[X]=i.createRenderbuffer(),qe(b.__webglDepthbuffer[X],A,!1);else{const ee=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=b.__webglDepthbuffer[X];i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,ee,i.RENDERBUFFER,j)}}else{const X=A.texture.mipmaps;if(X&&X.length>0?t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer),b.__webglDepthbuffer===void 0)b.__webglDepthbuffer=i.createRenderbuffer(),qe(b.__webglDepthbuffer,A,!1);else{const ee=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=b.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,ee,i.RENDERBUFFER,j)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function Yt(A,b,L){const X=n.get(A);b!==void 0&&Ce(X.__webglFramebuffer,A,A.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),L!==void 0&&rt(A)}function it(A){const b=A.texture,L=n.get(A),X=n.get(b);A.addEventListener("dispose",w);const ee=A.textures,j=A.isWebGLCubeRenderTarget===!0,ke=ee.length>1;if(ke||(X.__webglTexture===void 0&&(X.__webglTexture=i.createTexture()),X.__version=b.version,o.memory.textures++),j){L.__webglFramebuffer=[];for(let he=0;he<6;he++)if(b.mipmaps&&b.mipmaps.length>0){L.__webglFramebuffer[he]=[];for(let Ae=0;Ae<b.mipmaps.length;Ae++)L.__webglFramebuffer[he][Ae]=i.createFramebuffer()}else L.__webglFramebuffer[he]=i.createFramebuffer()}else{if(b.mipmaps&&b.mipmaps.length>0){L.__webglFramebuffer=[];for(let he=0;he<b.mipmaps.length;he++)L.__webglFramebuffer[he]=i.createFramebuffer()}else L.__webglFramebuffer=i.createFramebuffer();if(ke)for(let he=0,Ae=ee.length;he<Ae;he++){const Ue=n.get(ee[he]);Ue.__webglTexture===void 0&&(Ue.__webglTexture=i.createTexture(),o.memory.textures++)}if(A.samples>0&&Gt(A)===!1){L.__webglMultisampledFramebuffer=i.createFramebuffer(),L.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,L.__webglMultisampledFramebuffer);for(let he=0;he<ee.length;he++){const Ae=ee[he];L.__webglColorRenderbuffer[he]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,L.__webglColorRenderbuffer[he]);const Ue=r.convert(Ae.format,Ae.colorSpace),re=r.convert(Ae.type),me=E(Ae.internalFormat,Ue,re,Ae.colorSpace,A.isXRRenderTarget===!0),Me=I(A);i.renderbufferStorageMultisample(i.RENDERBUFFER,Me,me,A.width,A.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+he,i.RENDERBUFFER,L.__webglColorRenderbuffer[he])}i.bindRenderbuffer(i.RENDERBUFFER,null),A.depthBuffer&&(L.__webglDepthRenderbuffer=i.createRenderbuffer(),qe(L.__webglDepthRenderbuffer,A,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(j){t.bindTexture(i.TEXTURE_CUBE_MAP,X.__webglTexture),Ge(i.TEXTURE_CUBE_MAP,b);for(let he=0;he<6;he++)if(b.mipmaps&&b.mipmaps.length>0)for(let Ae=0;Ae<b.mipmaps.length;Ae++)Ce(L.__webglFramebuffer[he][Ae],A,b,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+he,Ae);else Ce(L.__webglFramebuffer[he],A,b,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+he,0);m(b)&&p(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(ke){for(let he=0,Ae=ee.length;he<Ae;he++){const Ue=ee[he],re=n.get(Ue);let me=i.TEXTURE_2D;(A.isWebGL3DRenderTarget||A.isWebGLArrayRenderTarget)&&(me=A.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(me,re.__webglTexture),Ge(me,Ue),Ce(L.__webglFramebuffer,A,Ue,i.COLOR_ATTACHMENT0+he,me,0),m(Ue)&&p(me)}t.unbindTexture()}else{let he=i.TEXTURE_2D;if((A.isWebGL3DRenderTarget||A.isWebGLArrayRenderTarget)&&(he=A.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(he,X.__webglTexture),Ge(he,b),b.mipmaps&&b.mipmaps.length>0)for(let Ae=0;Ae<b.mipmaps.length;Ae++)Ce(L.__webglFramebuffer[Ae],A,b,i.COLOR_ATTACHMENT0,he,Ae);else Ce(L.__webglFramebuffer,A,b,i.COLOR_ATTACHMENT0,he,0);m(b)&&p(he),t.unbindTexture()}A.depthBuffer&&rt(A)}function dt(A){const b=A.textures;for(let L=0,X=b.length;L<X;L++){const ee=b[L];if(m(ee)){const j=T(A),ke=n.get(ee).__webglTexture;t.bindTexture(j,ke),p(j),t.unbindTexture()}}}const yt=[],$e=[];function Vt(A){if(A.samples>0){if(Gt(A)===!1){const b=A.textures,L=A.width,X=A.height;let ee=i.COLOR_BUFFER_BIT;const j=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ke=n.get(A),he=b.length>1;if(he)for(let Ue=0;Ue<b.length;Ue++)t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,ke.__webglMultisampledFramebuffer);const Ae=A.texture.mipmaps;Ae&&Ae.length>0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglFramebuffer);for(let Ue=0;Ue<b.length;Ue++){if(A.resolveDepthBuffer&&(A.depthBuffer&&(ee|=i.DEPTH_BUFFER_BIT),A.stencilBuffer&&A.resolveStencilBuffer&&(ee|=i.STENCIL_BUFFER_BIT)),he){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,ke.__webglColorRenderbuffer[Ue]);const re=n.get(b[Ue]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,re,0)}i.blitFramebuffer(0,0,L,X,0,0,L,X,ee,i.NEAREST),c===!0&&(yt.length=0,$e.length=0,yt.push(i.COLOR_ATTACHMENT0+Ue),A.depthBuffer&&A.resolveDepthBuffer===!1&&(yt.push(j),$e.push(j),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,$e)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,yt))}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),he)for(let Ue=0;Ue<b.length;Ue++){t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.RENDERBUFFER,ke.__webglColorRenderbuffer[Ue]);const re=n.get(b[Ue]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.TEXTURE_2D,re,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglMultisampledFramebuffer)}else if(A.depthBuffer&&A.resolveDepthBuffer===!1&&c){const b=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[b])}}}function I(A){return Math.min(s.maxSamples,A.samples)}function Gt(A){const b=n.get(A);return A.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&b.__useRenderToTexture!==!1}function ct(A){const b=o.render.frame;d.get(A)!==b&&(d.set(A,b),A.update())}function _t(A,b){const L=A.colorSpace,X=A.format,ee=A.type;return A.isCompressedTexture===!0||A.isVideoTexture===!0||L!==er&&L!==Zi&&(nt.getTransfer(L)===lt?(X!==qn||ee!==Mn)&&Be("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):st("WebGLTextures: Unsupported texture color space:",L)),b}function Re(A){return typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement?(l.width=A.naturalWidth||A.width,l.height=A.naturalHeight||A.height):typeof VideoFrame<"u"&&A instanceof VideoFrame?(l.width=A.displayWidth,l.height=A.displayHeight):(l.width=A.width,l.height=A.height),l}this.allocateTextureUnit=F,this.resetTextureUnits=O,this.setTexture2D=K,this.setTexture2DArray=G,this.setTexture3D=W,this.setTextureCube=te,this.rebindTextures=Yt,this.setupRenderTarget=it,this.updateRenderTargetMipmap=dt,this.updateMultisampleRenderTarget=Vt,this.setupDepthRenderbuffer=rt,this.setupFrameBufferTexture=Ce,this.useMultisampledRTT=Gt,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function $E(i,e){function t(n,s=Zi){let r;const o=nt.getTransfer(s);if(n===Mn)return i.UNSIGNED_BYTE;if(n===Ul)return i.UNSIGNED_SHORT_4_4_4_4;if(n===Fl)return i.UNSIGNED_SHORT_5_5_5_1;if(n===Hp)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===Wp)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===Vp)return i.BYTE;if(n===Gp)return i.SHORT;if(n===Yr)return i.UNSIGNED_SHORT;if(n===Ol)return i.INT;if(n===si)return i.UNSIGNED_INT;if(n===ri)return i.FLOAT;if(n===Ci)return i.HALF_FLOAT;if(n===qp)return i.ALPHA;if(n===jp)return i.RGB;if(n===qn)return i.RGBA;if(n===Ei)return i.DEPTH_COMPONENT;if(n===bs)return i.DEPTH_STENCIL;if(n===$p)return i.RED;if(n===Bl)return i.RED_INTEGER;if(n===Qs)return i.RG;if(n===zl)return i.RG_INTEGER;if(n===Vl)return i.RGBA_INTEGER;if(n===lo||n===uo||n===ho||n===fo)if(o===lt)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===lo)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===uo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===ho)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===fo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===lo)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===uo)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===ho)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===fo)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Gl||n===Hl||n===Wl||n===ql)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===Gl)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===Hl)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Wl)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===ql)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===jl||n===$l||n===Xl||n===Kl||n===Yl||n===Jl||n===Zl)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(n===jl||n===$l)return o===lt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===Xl)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===Kl)return r.COMPRESSED_R11_EAC;if(n===Yl)return r.COMPRESSED_SIGNED_R11_EAC;if(n===Jl)return r.COMPRESSED_RG11_EAC;if(n===Zl)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===Ql||n===ed||n===td||n===nd||n===id||n===sd||n===rd||n===ad||n===od||n===cd||n===ld||n===dd||n===ud||n===hd)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(n===Ql)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===ed)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===td)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===nd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===id)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===sd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===rd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===ad)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===od)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===cd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===ld)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===dd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===ud)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===hd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===fd||n===pd||n===md)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(n===fd)return o===lt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===pd)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===md)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===gd||n===vd||n===yd||n===bd)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(n===gd)return r.COMPRESSED_RED_RGTC1_EXT;if(n===vd)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===yd)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===bd)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Jr?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const XE=`
4078
+ }`,VE=[new U(1,0,0),new U(-1,0,0),new U(0,1,0),new U(0,-1,0),new U(0,0,1),new U(0,0,-1)],GE=[new U(0,-1,0),new U(0,-1,0),new U(0,0,1),new U(0,0,-1),new U(0,-1,0),new U(0,-1,0)],dg=new At,fa=new U,uu=new U;function HE(i,e,t){let n=new Kd;const s=new tt,r=new tt,o=new Dt,a=new NS,c=new OS,l={},d=t.maxTextureSize,u={[_i]:nn,[nn]:_i,[Si]:Si},h=new tn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new tt},radius:{value:4}},vertexShader:BE,fragmentShader:zE}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const g=new fn;g.setAttribute("position",new Sn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new xn(g,h),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=ao;let p=this.type;this.render=function(C,w,k){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||C.length===0)return;C.type===x_&&(Be("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),C.type=ao);const _=i.getRenderTarget(),x=i.getActiveCubeFace(),R=i.getActiveMipmapLevel(),O=i.state;O.setBlending(xi),O.buffers.depth.getReversed()===!0?O.buffers.color.setClear(0,0,0,0):O.buffers.color.setClear(1,1,1,1),O.buffers.depth.setTest(!0),O.setScissorTest(!1);const F=p!==this.type;F&&w.traverse(function(q){q.material&&(Array.isArray(q.material)?q.material.forEach(K=>K.needsUpdate=!0):q.material.needsUpdate=!0)});for(let q=0,K=C.length;q<K;q++){const G=C[q],W=G.shadow;if(W===void 0){Be("WebGLShadowMap:",G,"has no shadow.");continue}if(W.autoUpdate===!1&&W.needsUpdate===!1)continue;s.copy(W.mapSize);const te=W.getFrameExtents();if(s.multiply(te),r.copy(W.mapSize),(s.x>d||s.y>d)&&(s.x>d&&(r.x=Math.floor(d/te.x),s.x=r.x*te.x,W.mapSize.x=r.x),s.y>d&&(r.y=Math.floor(d/te.y),s.y=r.y*te.y,W.mapSize.y=r.y)),W.map===null||F===!0){if(W.map!==null&&(W.map.depthTexture!==null&&(W.map.depthTexture.dispose(),W.map.depthTexture=null),W.map.dispose()),this.type===Kr){if(G.isPointLight){Be("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}W.map=new oi(s.x,s.y,{format:Qs,type:Ci,minFilter:sn,magFilter:sn,generateMipmaps:!1}),W.map.texture.name=G.name+".shadowMap",W.map.depthTexture=new da(s.x,s.y,ri),W.map.depthTexture.name=G.name+".shadowMapDepth",W.map.depthTexture.format=Ei,W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=en,W.map.depthTexture.magFilter=en}else{G.isPointLight?(W.map=new Em(s.x),W.map.depthTexture=new DS(s.x,si)):(W.map=new oi(s.x,s.y),W.map.depthTexture=new da(s.x,s.y,si)),W.map.depthTexture.name=G.name+".shadowMap",W.map.depthTexture.format=Ei;const ue=i.state.buffers.depth.getReversed();this.type===ao?(W.map.depthTexture.compareFunction=ue?Sd:_d,W.map.depthTexture.minFilter=sn,W.map.depthTexture.magFilter=sn):(W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=en,W.map.depthTexture.magFilter=en)}W.camera.updateProjectionMatrix()}const ye=W.map.isWebGLCubeRenderTarget?6:1;for(let ue=0;ue<ye;ue++){if(W.map.isWebGLCubeRenderTarget)i.setRenderTarget(W.map,ue),i.clear();else{ue===0&&(i.setRenderTarget(W.map),i.clear());const _e=W.getViewport(ue);o.set(r.x*_e.x,r.y*_e.y,r.x*_e.z,r.y*_e.w),O.viewport(o)}if(G.isPointLight){const _e=W.camera,Ge=W.matrix,Ve=G.distance||_e.far;Ve!==_e.far&&(_e.far=Ve,_e.updateProjectionMatrix()),fa.setFromMatrixPosition(G.matrixWorld),_e.position.copy(fa),uu.copy(_e.position),uu.add(VE[ue]),_e.up.copy(GE[ue]),_e.lookAt(uu),_e.updateMatrixWorld(),Ge.makeTranslation(-fa.x,-fa.y,-fa.z),dg.multiplyMatrices(_e.projectionMatrix,_e.matrixWorldInverse),W._frustum.setFromProjectionMatrix(dg,_e.coordinateSystem,_e.reversedDepth)}else W.updateMatrices(G);n=W.getFrustum(),y(w,k,W.camera,G,this.type)}W.isPointLightShadow!==!0&&this.type===Kr&&T(W,k),W.needsUpdate=!1}p=this.type,m.needsUpdate=!1,i.setRenderTarget(_,x,R)};function T(C,w){const k=e.update(v);h.defines.VSM_SAMPLES!==C.blurSamples&&(h.defines.VSM_SAMPLES=C.blurSamples,f.defines.VSM_SAMPLES=C.blurSamples,h.needsUpdate=!0,f.needsUpdate=!0),C.mapPass===null&&(C.mapPass=new oi(s.x,s.y,{format:Qs,type:Ci})),h.uniforms.shadow_pass.value=C.map.depthTexture,h.uniforms.resolution.value=C.mapSize,h.uniforms.radius.value=C.radius,i.setRenderTarget(C.mapPass),i.clear(),i.renderBufferDirect(w,null,k,h,v,null),f.uniforms.shadow_pass.value=C.mapPass.texture,f.uniforms.resolution.value=C.mapSize,f.uniforms.radius.value=C.radius,i.setRenderTarget(C.map),i.clear(),i.renderBufferDirect(w,null,k,f,v,null)}function E(C,w,k,_){let x=null;const R=k.isPointLight===!0?C.customDistanceMaterial:C.customDepthMaterial;if(R!==void 0)x=R;else if(x=k.isPointLight===!0?c:a,i.localClippingEnabled&&w.clipShadows===!0&&Array.isArray(w.clippingPlanes)&&w.clippingPlanes.length!==0||w.displacementMap&&w.displacementScale!==0||w.alphaMap&&w.alphaTest>0||w.map&&w.alphaTest>0||w.alphaToCoverage===!0){const O=x.uuid,F=w.uuid;let q=l[O];q===void 0&&(q={},l[O]=q);let K=q[F];K===void 0&&(K=x.clone(),q[F]=K,w.addEventListener("dispose",S)),x=K}if(x.visible=w.visible,x.wireframe=w.wireframe,_===Kr?x.side=w.shadowSide!==null?w.shadowSide:w.side:x.side=w.shadowSide!==null?w.shadowSide:u[w.side],x.alphaMap=w.alphaMap,x.alphaTest=w.alphaToCoverage===!0?.5:w.alphaTest,x.map=w.map,x.clipShadows=w.clipShadows,x.clippingPlanes=w.clippingPlanes,x.clipIntersection=w.clipIntersection,x.displacementMap=w.displacementMap,x.displacementScale=w.displacementScale,x.displacementBias=w.displacementBias,x.wireframeLinewidth=w.wireframeLinewidth,x.linewidth=w.linewidth,k.isPointLight===!0&&x.isMeshDistanceMaterial===!0){const O=i.properties.get(x);O.light=k}return x}function y(C,w,k,_,x){if(C.visible===!1)return;if(C.layers.test(w.layers)&&(C.isMesh||C.isLine||C.isPoints)&&(C.castShadow||C.receiveShadow&&x===Kr)&&(!C.frustumCulled||n.intersectsObject(C))){C.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse,C.matrixWorld);const F=e.update(C),q=C.material;if(Array.isArray(q)){const K=F.groups;for(let G=0,W=K.length;G<W;G++){const te=K[G],ye=q[te.materialIndex];if(ye&&ye.visible){const ue=E(C,ye,_,x);C.onBeforeShadow(i,C,w,k,F,ue,te),i.renderBufferDirect(k,null,F,ue,C,te),C.onAfterShadow(i,C,w,k,F,ue,te)}}}else if(q.visible){const K=E(C,q,_,x);C.onBeforeShadow(i,C,w,k,F,K,null),i.renderBufferDirect(k,null,F,K,C,null),C.onAfterShadow(i,C,w,k,F,K,null)}}const O=C.children;for(let F=0,q=O.length;F<q;F++)y(O[F],w,k,_,x)}function S(C){C.target.removeEventListener("dispose",S);for(const k in l){const _=l[k],x=C.target.uuid;x in _&&(_[x].dispose(),delete _[x])}}}const WE={[Cl]:El,[Ml]:Rl,[wl]:Pl,[Js]:Al,[El]:Cl,[Rl]:Ml,[Pl]:wl,[Al]:Js};function qE(i,e){function t(){let D=!1;const Se=new Dt;let oe=null;const xe=new Dt(0,0,0,0);return{setMask:function(se){oe!==se&&!D&&(i.colorMask(se,se,se,se),oe=se)},setLocked:function(se){D=se},setClear:function(se,Q,he,ze,St){St===!0&&(se*=ze,Q*=ze,he*=ze),Se.set(se,Q,he,ze),xe.equals(Se)===!1&&(i.clearColor(se,Q,he,ze),xe.copy(Se))},reset:function(){D=!1,oe=null,xe.set(-1,0,0,0)}}}function n(){let D=!1,Se=!1,oe=null,xe=null,se=null;return{setReversed:function(Q){if(Se!==Q){const he=e.get("EXT_clip_control");Q?he.clipControlEXT(he.LOWER_LEFT_EXT,he.ZERO_TO_ONE_EXT):he.clipControlEXT(he.LOWER_LEFT_EXT,he.NEGATIVE_ONE_TO_ONE_EXT),Se=Q;const ze=se;se=null,this.setClear(ze)}},getReversed:function(){return Se},setTest:function(Q){Q?ie(i.DEPTH_TEST):Ce(i.DEPTH_TEST)},setMask:function(Q){oe!==Q&&!D&&(i.depthMask(Q),oe=Q)},setFunc:function(Q){if(Se&&(Q=WE[Q]),xe!==Q){switch(Q){case Cl:i.depthFunc(i.NEVER);break;case El:i.depthFunc(i.ALWAYS);break;case Ml:i.depthFunc(i.LESS);break;case Js:i.depthFunc(i.LEQUAL);break;case wl:i.depthFunc(i.EQUAL);break;case Al:i.depthFunc(i.GEQUAL);break;case Rl:i.depthFunc(i.GREATER);break;case Pl:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}xe=Q}},setLocked:function(Q){D=Q},setClear:function(Q){se!==Q&&(Se&&(Q=1-Q),i.clearDepth(Q),se=Q)},reset:function(){D=!1,oe=null,xe=null,se=null,Se=!1}}}function s(){let D=!1,Se=null,oe=null,xe=null,se=null,Q=null,he=null,ze=null,St=null;return{setTest:function(ut){D||(ut?ie(i.STENCIL_TEST):Ce(i.STENCIL_TEST))},setMask:function(ut){Se!==ut&&!D&&(i.stencilMask(ut),Se=ut)},setFunc:function(ut,hi,Di){(oe!==ut||xe!==hi||se!==Di)&&(i.stencilFunc(ut,hi,Di),oe=ut,xe=hi,se=Di)},setOp:function(ut,hi,Di){(Q!==ut||he!==hi||ze!==Di)&&(i.stencilOp(ut,hi,Di),Q=ut,he=hi,ze=Di)},setLocked:function(ut){D=ut},setClear:function(ut){St!==ut&&(i.clearStencil(ut),St=ut)},reset:function(){D=!1,Se=null,oe=null,xe=null,se=null,Q=null,he=null,ze=null,St=null}}}const r=new t,o=new n,a=new s,c=new WeakMap,l=new WeakMap;let d={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,T=null,E=null,y=null,S=null,C=null,w=new Fe(0,0,0),k=0,_=!1,x=null,R=null,O=null,F=null,q=null;const K=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let G=!1,W=0;const te=i.getParameter(i.VERSION);te.indexOf("WebGL")!==-1?(W=parseFloat(/^WebGL (\d)/.exec(te)[1]),G=W>=1):te.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(te)[1]),G=W>=2);let ye=null,ue={};const _e=i.getParameter(i.SCISSOR_BOX),Ge=i.getParameter(i.VIEWPORT),Ve=new Dt().fromArray(_e),Mt=new Dt().fromArray(Ge);function pt(D,Se,oe,xe){const se=new Uint8Array(4),Q=i.createTexture();i.bindTexture(D,Q),i.texParameteri(D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(D,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let he=0;he<oe;he++)D===i.TEXTURE_3D||D===i.TEXTURE_2D_ARRAY?i.texImage3D(Se,0,i.RGBA,1,1,xe,0,i.RGBA,i.UNSIGNED_BYTE,se):i.texImage2D(Se+he,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,se);return Q}const Y={};Y[i.TEXTURE_2D]=pt(i.TEXTURE_2D,i.TEXTURE_2D,1),Y[i.TEXTURE_CUBE_MAP]=pt(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),Y[i.TEXTURE_2D_ARRAY]=pt(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),Y[i.TEXTURE_3D]=pt(i.TEXTURE_3D,i.TEXTURE_3D,1,1),r.setClear(0,0,0,1),o.setClear(1),a.setClear(0),ie(i.DEPTH_TEST),o.setFunc(Js),$e(!1),Vt(Rp),ie(i.CULL_FACE),dt(xi);function ie(D){d[D]!==!0&&(i.enable(D),d[D]=!0)}function Ce(D){d[D]!==!1&&(i.disable(D),d[D]=!1)}function qe(D,Se){return u[D]!==Se?(i.bindFramebuffer(D,Se),u[D]=Se,D===i.DRAW_FRAMEBUFFER&&(u[i.FRAMEBUFFER]=Se),D===i.FRAMEBUFFER&&(u[i.DRAW_FRAMEBUFFER]=Se),!0):!1}function we(D,Se){let oe=f,xe=!1;if(D){oe=h.get(Se),oe===void 0&&(oe=[],h.set(Se,oe));const se=D.textures;if(oe.length!==se.length||oe[0]!==i.COLOR_ATTACHMENT0){for(let Q=0,he=se.length;Q<he;Q++)oe[Q]=i.COLOR_ATTACHMENT0+Q;oe.length=se.length,xe=!0}}else oe[0]!==i.BACK&&(oe[0]=i.BACK,xe=!0);xe&&i.drawBuffers(oe)}function rt(D){return g!==D?(i.useProgram(D),g=D,!0):!1}const Jt={[gs]:i.FUNC_ADD,[C_]:i.FUNC_SUBTRACT,[E_]:i.FUNC_REVERSE_SUBTRACT};Jt[M_]=i.MIN,Jt[w_]=i.MAX;const it={[A_]:i.ZERO,[R_]:i.ONE,[P_]:i.SRC_COLOR,[xl]:i.SRC_ALPHA,[O_]:i.SRC_ALPHA_SATURATE,[L_]:i.DST_COLOR,[I_]:i.DST_ALPHA,[k_]:i.ONE_MINUS_SRC_COLOR,[Tl]:i.ONE_MINUS_SRC_ALPHA,[N_]:i.ONE_MINUS_DST_COLOR,[D_]:i.ONE_MINUS_DST_ALPHA,[U_]:i.CONSTANT_COLOR,[F_]:i.ONE_MINUS_CONSTANT_COLOR,[B_]:i.CONSTANT_ALPHA,[z_]:i.ONE_MINUS_CONSTANT_ALPHA};function dt(D,Se,oe,xe,se,Q,he,ze,St,ut){if(D===xi){v===!0&&(Ce(i.BLEND),v=!1);return}if(v===!1&&(ie(i.BLEND),v=!0),D!==T_){if(D!==m||ut!==_){if((p!==gs||y!==gs)&&(i.blendEquation(i.FUNC_ADD),p=gs,y=gs),ut)switch(D){case Ys:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Ji:i.blendFunc(i.ONE,i.ONE);break;case Pp:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case kp:i.blendFuncSeparate(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE);break;default:st("WebGLState: Invalid blending: ",D);break}else switch(D){case Ys:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Ji:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE,i.ONE,i.ONE);break;case Pp:st("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case kp:st("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:st("WebGLState: Invalid blending: ",D);break}T=null,E=null,S=null,C=null,w.set(0,0,0),k=0,m=D,_=ut}return}se=se||Se,Q=Q||oe,he=he||xe,(Se!==p||se!==y)&&(i.blendEquationSeparate(Jt[Se],Jt[se]),p=Se,y=se),(oe!==T||xe!==E||Q!==S||he!==C)&&(i.blendFuncSeparate(it[oe],it[xe],it[Q],it[he]),T=oe,E=xe,S=Q,C=he),(ze.equals(w)===!1||St!==k)&&(i.blendColor(ze.r,ze.g,ze.b,St),w.copy(ze),k=St),m=D,_=!1}function yt(D,Se){D.side===Si?Ce(i.CULL_FACE):ie(i.CULL_FACE);let oe=D.side===nn;Se&&(oe=!oe),$e(oe),D.blending===Ys&&D.transparent===!1?dt(xi):dt(D.blending,D.blendEquation,D.blendSrc,D.blendDst,D.blendEquationAlpha,D.blendSrcAlpha,D.blendDstAlpha,D.blendColor,D.blendAlpha,D.premultipliedAlpha),o.setFunc(D.depthFunc),o.setTest(D.depthTest),o.setMask(D.depthWrite),r.setMask(D.colorWrite);const xe=D.stencilWrite;a.setTest(xe),xe&&(a.setMask(D.stencilWriteMask),a.setFunc(D.stencilFunc,D.stencilRef,D.stencilFuncMask),a.setOp(D.stencilFail,D.stencilZFail,D.stencilZPass)),Gt(D.polygonOffset,D.polygonOffsetFactor,D.polygonOffsetUnits),D.alphaToCoverage===!0?ie(i.SAMPLE_ALPHA_TO_COVERAGE):Ce(i.SAMPLE_ALPHA_TO_COVERAGE)}function $e(D){x!==D&&(D?i.frontFace(i.CW):i.frontFace(i.CCW),x=D)}function Vt(D){D!==__?(ie(i.CULL_FACE),D!==R&&(D===Rp?i.cullFace(i.BACK):D===S_?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):Ce(i.CULL_FACE),R=D}function I(D){D!==O&&(G&&i.lineWidth(D),O=D)}function Gt(D,Se,oe){D?(ie(i.POLYGON_OFFSET_FILL),(F!==Se||q!==oe)&&(i.polygonOffset(Se,oe),F=Se,q=oe)):Ce(i.POLYGON_OFFSET_FILL)}function ct(D){D?ie(i.SCISSOR_TEST):Ce(i.SCISSOR_TEST)}function _t(D){D===void 0&&(D=i.TEXTURE0+K-1),ye!==D&&(i.activeTexture(D),ye=D)}function Re(D,Se,oe){oe===void 0&&(ye===null?oe=i.TEXTURE0+K-1:oe=ye);let xe=ue[oe];xe===void 0&&(xe={type:void 0,texture:void 0},ue[oe]=xe),(xe.type!==D||xe.texture!==Se)&&(ye!==oe&&(i.activeTexture(oe),ye=oe),i.bindTexture(D,Se||Y[D]),xe.type=D,xe.texture=Se)}function A(){const D=ue[ye];D!==void 0&&D.type!==void 0&&(i.bindTexture(D.type,null),D.type=void 0,D.texture=void 0)}function b(){try{i.compressedTexImage2D(...arguments)}catch(D){st("WebGLState:",D)}}function L(){try{i.compressedTexImage3D(...arguments)}catch(D){st("WebGLState:",D)}}function X(){try{i.texSubImage2D(...arguments)}catch(D){st("WebGLState:",D)}}function ee(){try{i.texSubImage3D(...arguments)}catch(D){st("WebGLState:",D)}}function j(){try{i.compressedTexSubImage2D(...arguments)}catch(D){st("WebGLState:",D)}}function ke(){try{i.compressedTexSubImage3D(...arguments)}catch(D){st("WebGLState:",D)}}function fe(){try{i.texStorage2D(...arguments)}catch(D){st("WebGLState:",D)}}function Ae(){try{i.texStorage3D(...arguments)}catch(D){st("WebGLState:",D)}}function Ue(){try{i.texImage2D(...arguments)}catch(D){st("WebGLState:",D)}}function re(){try{i.texImage3D(...arguments)}catch(D){st("WebGLState:",D)}}function me(D){Ve.equals(D)===!1&&(i.scissor(D.x,D.y,D.z,D.w),Ve.copy(D))}function Me(D){Mt.equals(D)===!1&&(i.viewport(D.x,D.y,D.z,D.w),Mt.copy(D))}function Pe(D,Se){let oe=l.get(Se);oe===void 0&&(oe=new WeakMap,l.set(Se,oe));let xe=oe.get(D);xe===void 0&&(xe=i.getUniformBlockIndex(Se,D.name),oe.set(D,xe))}function pe(D,Se){const xe=l.get(Se).get(D);c.get(Se)!==xe&&(i.uniformBlockBinding(Se,xe,D.__bindingPointIndex),c.set(Se,xe))}function Xe(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.blendColor(0,0,0,0),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),o.setReversed(!1),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),d={},ye=null,ue={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,T=null,E=null,y=null,S=null,C=null,w=new Fe(0,0,0),k=0,_=!1,x=null,R=null,O=null,F=null,q=null,Ve.set(0,0,i.canvas.width,i.canvas.height),Mt.set(0,0,i.canvas.width,i.canvas.height),r.reset(),o.reset(),a.reset()}return{buffers:{color:r,depth:o,stencil:a},enable:ie,disable:Ce,bindFramebuffer:qe,drawBuffers:we,useProgram:rt,setBlending:dt,setMaterial:yt,setFlipSided:$e,setCullFace:Vt,setLineWidth:I,setPolygonOffset:Gt,setScissorTest:ct,activeTexture:_t,bindTexture:Re,unbindTexture:A,compressedTexImage2D:b,compressedTexImage3D:L,texImage2D:Ue,texImage3D:re,updateUBOMapping:Pe,uniformBlockBinding:pe,texStorage2D:fe,texStorage3D:Ae,texSubImage2D:X,texSubImage3D:ee,compressedTexSubImage2D:j,compressedTexSubImage3D:ke,scissor:me,viewport:Me,reset:Xe}}function jE(i,e,t,n,s,r,o){const a=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new tt,d=new WeakMap;let u;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(A,b){return f?new OffscreenCanvas(A,b):go("canvas")}function v(A,b,L){let X=1;const ee=Re(A);if((ee.width>L||ee.height>L)&&(X=L/Math.max(ee.width,ee.height)),X<1)if(typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&A instanceof ImageBitmap||typeof VideoFrame<"u"&&A instanceof VideoFrame){const j=Math.floor(X*ee.width),ke=Math.floor(X*ee.height);u===void 0&&(u=g(j,ke));const fe=b?g(j,ke):u;return fe.width=j,fe.height=ke,fe.getContext("2d").drawImage(A,0,0,j,ke),Be("WebGLRenderer: Texture has been resized from ("+ee.width+"x"+ee.height+") to ("+j+"x"+ke+")."),fe}else return"data"in A&&Be("WebGLRenderer: Image in DataTexture is too big ("+ee.width+"x"+ee.height+")."),A;return A}function m(A){return A.generateMipmaps}function p(A){i.generateMipmap(A)}function T(A){return A.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:A.isWebGL3DRenderTarget?i.TEXTURE_3D:A.isWebGLArrayRenderTarget||A.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function E(A,b,L,X,ee=!1){if(A!==null){if(i[A]!==void 0)return i[A];Be("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+A+"'")}let j=b;if(b===i.RED&&(L===i.FLOAT&&(j=i.R32F),L===i.HALF_FLOAT&&(j=i.R16F),L===i.UNSIGNED_BYTE&&(j=i.R8)),b===i.RED_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.R8UI),L===i.UNSIGNED_SHORT&&(j=i.R16UI),L===i.UNSIGNED_INT&&(j=i.R32UI),L===i.BYTE&&(j=i.R8I),L===i.SHORT&&(j=i.R16I),L===i.INT&&(j=i.R32I)),b===i.RG&&(L===i.FLOAT&&(j=i.RG32F),L===i.HALF_FLOAT&&(j=i.RG16F),L===i.UNSIGNED_BYTE&&(j=i.RG8)),b===i.RG_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RG8UI),L===i.UNSIGNED_SHORT&&(j=i.RG16UI),L===i.UNSIGNED_INT&&(j=i.RG32UI),L===i.BYTE&&(j=i.RG8I),L===i.SHORT&&(j=i.RG16I),L===i.INT&&(j=i.RG32I)),b===i.RGB_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGB8UI),L===i.UNSIGNED_SHORT&&(j=i.RGB16UI),L===i.UNSIGNED_INT&&(j=i.RGB32UI),L===i.BYTE&&(j=i.RGB8I),L===i.SHORT&&(j=i.RGB16I),L===i.INT&&(j=i.RGB32I)),b===i.RGBA_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGBA8UI),L===i.UNSIGNED_SHORT&&(j=i.RGBA16UI),L===i.UNSIGNED_INT&&(j=i.RGBA32UI),L===i.BYTE&&(j=i.RGBA8I),L===i.SHORT&&(j=i.RGBA16I),L===i.INT&&(j=i.RGBA32I)),b===i.RGB&&(L===i.UNSIGNED_INT_5_9_9_9_REV&&(j=i.RGB9_E5),L===i.UNSIGNED_INT_10F_11F_11F_REV&&(j=i.R11F_G11F_B10F)),b===i.RGBA){const ke=ee?po:nt.getTransfer(X);L===i.FLOAT&&(j=i.RGBA32F),L===i.HALF_FLOAT&&(j=i.RGBA16F),L===i.UNSIGNED_BYTE&&(j=ke===lt?i.SRGB8_ALPHA8:i.RGBA8),L===i.UNSIGNED_SHORT_4_4_4_4&&(j=i.RGBA4),L===i.UNSIGNED_SHORT_5_5_5_1&&(j=i.RGB5_A1)}return(j===i.R16F||j===i.R32F||j===i.RG16F||j===i.RG32F||j===i.RGBA16F||j===i.RGBA32F)&&e.get("EXT_color_buffer_float"),j}function y(A,b){let L;return A?b===null||b===si||b===Jr?L=i.DEPTH24_STENCIL8:b===ri?L=i.DEPTH32F_STENCIL8:b===Yr&&(L=i.DEPTH24_STENCIL8,Be("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):b===null||b===si||b===Jr?L=i.DEPTH_COMPONENT24:b===ri?L=i.DEPTH_COMPONENT32F:b===Yr&&(L=i.DEPTH_COMPONENT16),L}function S(A,b){return m(A)===!0||A.isFramebufferTexture&&A.minFilter!==en&&A.minFilter!==sn?Math.log2(Math.max(b.width,b.height))+1:A.mipmaps!==void 0&&A.mipmaps.length>0?A.mipmaps.length:A.isCompressedTexture&&Array.isArray(A.image)?b.mipmaps.length:1}function C(A){const b=A.target;b.removeEventListener("dispose",C),k(b),b.isVideoTexture&&d.delete(b)}function w(A){const b=A.target;b.removeEventListener("dispose",w),x(b)}function k(A){const b=n.get(A);if(b.__webglInit===void 0)return;const L=A.source,X=h.get(L);if(X){const ee=X[b.__cacheKey];ee.usedTimes--,ee.usedTimes===0&&_(A),Object.keys(X).length===0&&h.delete(L)}n.remove(A)}function _(A){const b=n.get(A);i.deleteTexture(b.__webglTexture);const L=A.source,X=h.get(L);delete X[b.__cacheKey],o.memory.textures--}function x(A){const b=n.get(A);if(A.depthTexture&&(A.depthTexture.dispose(),n.remove(A.depthTexture)),A.isWebGLCubeRenderTarget)for(let X=0;X<6;X++){if(Array.isArray(b.__webglFramebuffer[X]))for(let ee=0;ee<b.__webglFramebuffer[X].length;ee++)i.deleteFramebuffer(b.__webglFramebuffer[X][ee]);else i.deleteFramebuffer(b.__webglFramebuffer[X]);b.__webglDepthbuffer&&i.deleteRenderbuffer(b.__webglDepthbuffer[X])}else{if(Array.isArray(b.__webglFramebuffer))for(let X=0;X<b.__webglFramebuffer.length;X++)i.deleteFramebuffer(b.__webglFramebuffer[X]);else i.deleteFramebuffer(b.__webglFramebuffer);if(b.__webglDepthbuffer&&i.deleteRenderbuffer(b.__webglDepthbuffer),b.__webglMultisampledFramebuffer&&i.deleteFramebuffer(b.__webglMultisampledFramebuffer),b.__webglColorRenderbuffer)for(let X=0;X<b.__webglColorRenderbuffer.length;X++)b.__webglColorRenderbuffer[X]&&i.deleteRenderbuffer(b.__webglColorRenderbuffer[X]);b.__webglDepthRenderbuffer&&i.deleteRenderbuffer(b.__webglDepthRenderbuffer)}const L=A.textures;for(let X=0,ee=L.length;X<ee;X++){const j=n.get(L[X]);j.__webglTexture&&(i.deleteTexture(j.__webglTexture),o.memory.textures--),n.remove(L[X])}n.remove(A)}let R=0;function O(){R=0}function F(){const A=R;return A>=s.maxTextures&&Be("WebGLTextures: Trying to use "+A+" texture units while this GPU supports only "+s.maxTextures),R+=1,A}function q(A){const b=[];return b.push(A.wrapS),b.push(A.wrapT),b.push(A.wrapR||0),b.push(A.magFilter),b.push(A.minFilter),b.push(A.anisotropy),b.push(A.internalFormat),b.push(A.format),b.push(A.type),b.push(A.generateMipmaps),b.push(A.premultiplyAlpha),b.push(A.flipY),b.push(A.unpackAlignment),b.push(A.colorSpace),b.join()}function K(A,b){const L=n.get(A);if(A.isVideoTexture&&ct(A),A.isRenderTargetTexture===!1&&A.isExternalTexture!==!0&&A.version>0&&L.__version!==A.version){const X=A.image;if(X===null)Be("WebGLRenderer: Texture marked for update but no image data found.");else if(X.complete===!1)Be("WebGLRenderer: Texture marked for update but image is incomplete");else{Y(L,A,b);return}}else A.isExternalTexture&&(L.__webglTexture=A.sourceTexture?A.sourceTexture:null);t.bindTexture(i.TEXTURE_2D,L.__webglTexture,i.TEXTURE0+b)}function G(A,b){const L=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&L.__version!==A.version){Y(L,A,b);return}else A.isExternalTexture&&(L.__webglTexture=A.sourceTexture?A.sourceTexture:null);t.bindTexture(i.TEXTURE_2D_ARRAY,L.__webglTexture,i.TEXTURE0+b)}function W(A,b){const L=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&L.__version!==A.version){Y(L,A,b);return}t.bindTexture(i.TEXTURE_3D,L.__webglTexture,i.TEXTURE0+b)}function te(A,b){const L=n.get(A);if(A.isCubeDepthTexture!==!0&&A.version>0&&L.__version!==A.version){ie(L,A,b);return}t.bindTexture(i.TEXTURE_CUBE_MAP,L.__webglTexture,i.TEXTURE0+b)}const ye={[Dl]:i.REPEAT,[Ti]:i.CLAMP_TO_EDGE,[Ll]:i.MIRRORED_REPEAT},ue={[en]:i.NEAREST,[H_]:i.NEAREST_MIPMAP_NEAREST,[co]:i.NEAREST_MIPMAP_LINEAR,[sn]:i.LINEAR,[Nl]:i.LINEAR_MIPMAP_NEAREST,[ys]:i.LINEAR_MIPMAP_LINEAR},_e={[$_]:i.NEVER,[Z_]:i.ALWAYS,[X_]:i.LESS,[_d]:i.LEQUAL,[K_]:i.EQUAL,[Sd]:i.GEQUAL,[Y_]:i.GREATER,[J_]:i.NOTEQUAL};function Ge(A,b){if(b.type===ri&&e.has("OES_texture_float_linear")===!1&&(b.magFilter===sn||b.magFilter===Nl||b.magFilter===co||b.magFilter===ys||b.minFilter===sn||b.minFilter===Nl||b.minFilter===co||b.minFilter===ys)&&Be("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(A,i.TEXTURE_WRAP_S,ye[b.wrapS]),i.texParameteri(A,i.TEXTURE_WRAP_T,ye[b.wrapT]),(A===i.TEXTURE_3D||A===i.TEXTURE_2D_ARRAY)&&i.texParameteri(A,i.TEXTURE_WRAP_R,ye[b.wrapR]),i.texParameteri(A,i.TEXTURE_MAG_FILTER,ue[b.magFilter]),i.texParameteri(A,i.TEXTURE_MIN_FILTER,ue[b.minFilter]),b.compareFunction&&(i.texParameteri(A,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(A,i.TEXTURE_COMPARE_FUNC,_e[b.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(b.magFilter===en||b.minFilter!==co&&b.minFilter!==ys||b.type===ri&&e.has("OES_texture_float_linear")===!1)return;if(b.anisotropy>1||n.get(b).__currentAnisotropy){const L=e.get("EXT_texture_filter_anisotropic");i.texParameterf(A,L.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(b.anisotropy,s.getMaxAnisotropy())),n.get(b).__currentAnisotropy=b.anisotropy}}}function Ve(A,b){let L=!1;A.__webglInit===void 0&&(A.__webglInit=!0,b.addEventListener("dispose",C));const X=b.source;let ee=h.get(X);ee===void 0&&(ee={},h.set(X,ee));const j=q(b);if(j!==A.__cacheKey){ee[j]===void 0&&(ee[j]={texture:i.createTexture(),usedTimes:0},o.memory.textures++,L=!0),ee[j].usedTimes++;const ke=ee[A.__cacheKey];ke!==void 0&&(ee[A.__cacheKey].usedTimes--,ke.usedTimes===0&&_(b)),A.__cacheKey=j,A.__webglTexture=ee[j].texture}return L}function Mt(A,b,L){return Math.floor(Math.floor(A/L)/b)}function pt(A,b,L,X){const j=A.updateRanges;if(j.length===0)t.texSubImage2D(i.TEXTURE_2D,0,0,0,b.width,b.height,L,X,b.data);else{j.sort((re,me)=>re.start-me.start);let ke=0;for(let re=1;re<j.length;re++){const me=j[ke],Me=j[re],Pe=me.start+me.count,pe=Mt(Me.start,b.width,4),Xe=Mt(me.start,b.width,4);Me.start<=Pe+1&&pe===Xe&&Mt(Me.start+Me.count-1,b.width,4)===pe?me.count=Math.max(me.count,Me.start+Me.count-me.start):(++ke,j[ke]=Me)}j.length=ke+1;const fe=i.getParameter(i.UNPACK_ROW_LENGTH),Ae=i.getParameter(i.UNPACK_SKIP_PIXELS),Ue=i.getParameter(i.UNPACK_SKIP_ROWS);i.pixelStorei(i.UNPACK_ROW_LENGTH,b.width);for(let re=0,me=j.length;re<me;re++){const Me=j[re],Pe=Math.floor(Me.start/4),pe=Math.ceil(Me.count/4),Xe=Pe%b.width,D=Math.floor(Pe/b.width),Se=pe,oe=1;i.pixelStorei(i.UNPACK_SKIP_PIXELS,Xe),i.pixelStorei(i.UNPACK_SKIP_ROWS,D),t.texSubImage2D(i.TEXTURE_2D,0,Xe,D,Se,oe,L,X,b.data)}A.clearUpdateRanges(),i.pixelStorei(i.UNPACK_ROW_LENGTH,fe),i.pixelStorei(i.UNPACK_SKIP_PIXELS,Ae),i.pixelStorei(i.UNPACK_SKIP_ROWS,Ue)}}function Y(A,b,L){let X=i.TEXTURE_2D;(b.isDataArrayTexture||b.isCompressedArrayTexture)&&(X=i.TEXTURE_2D_ARRAY),b.isData3DTexture&&(X=i.TEXTURE_3D);const ee=Ve(A,b),j=b.source;t.bindTexture(X,A.__webglTexture,i.TEXTURE0+L);const ke=n.get(j);if(j.version!==ke.__version||ee===!0){t.activeTexture(i.TEXTURE0+L);const fe=nt.getPrimaries(nt.workingColorSpace),Ae=b.colorSpace===Zi?null:nt.getPrimaries(b.colorSpace),Ue=b.colorSpace===Zi||fe===Ae?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,b.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,b.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ue);let re=v(b.image,!1,s.maxTextureSize);re=_t(b,re);const me=r.convert(b.format,b.colorSpace),Me=r.convert(b.type);let Pe=E(b.internalFormat,me,Me,b.colorSpace,b.isVideoTexture);Ge(X,b);let pe;const Xe=b.mipmaps,D=b.isVideoTexture!==!0,Se=ke.__version===void 0||ee===!0,oe=j.dataReady,xe=S(b,re);if(b.isDepthTexture)Pe=y(b.format===bs,b.type),Se&&(D?t.texStorage2D(i.TEXTURE_2D,1,Pe,re.width,re.height):t.texImage2D(i.TEXTURE_2D,0,Pe,re.width,re.height,0,me,Me,null));else if(b.isDataTexture)if(Xe.length>0){D&&Se&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,Xe[0].width,Xe[0].height);for(let se=0,Q=Xe.length;se<Q;se++)pe=Xe[se],D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,pe.width,pe.height,me,Me,pe.data):t.texImage2D(i.TEXTURE_2D,se,Pe,pe.width,pe.height,0,me,Me,pe.data);b.generateMipmaps=!1}else D?(Se&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,re.width,re.height),oe&&pt(b,re,me,Me)):t.texImage2D(i.TEXTURE_2D,0,Pe,re.width,re.height,0,me,Me,re.data);else if(b.isCompressedTexture)if(b.isCompressedArrayTexture){D&&Se&&t.texStorage3D(i.TEXTURE_2D_ARRAY,xe,Pe,Xe[0].width,Xe[0].height,re.depth);for(let se=0,Q=Xe.length;se<Q;se++)if(pe=Xe[se],b.format!==qn)if(me!==null)if(D){if(oe)if(b.layerUpdates.size>0){const he=Om(pe.width,pe.height,b.format,b.type);for(const ze of b.layerUpdates){const St=pe.data.subarray(ze*he/pe.data.BYTES_PER_ELEMENT,(ze+1)*he/pe.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,ze,pe.width,pe.height,1,me,St)}b.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,0,pe.width,pe.height,re.depth,me,pe.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,se,Pe,pe.width,pe.height,re.depth,0,pe.data,0,0);else Be("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else D?oe&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,0,pe.width,pe.height,re.depth,me,Me,pe.data):t.texImage3D(i.TEXTURE_2D_ARRAY,se,Pe,pe.width,pe.height,re.depth,0,me,Me,pe.data)}else{D&&Se&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,Xe[0].width,Xe[0].height);for(let se=0,Q=Xe.length;se<Q;se++)pe=Xe[se],b.format!==qn?me!==null?D?oe&&t.compressedTexSubImage2D(i.TEXTURE_2D,se,0,0,pe.width,pe.height,me,pe.data):t.compressedTexImage2D(i.TEXTURE_2D,se,Pe,pe.width,pe.height,0,pe.data):Be("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,pe.width,pe.height,me,Me,pe.data):t.texImage2D(i.TEXTURE_2D,se,Pe,pe.width,pe.height,0,me,Me,pe.data)}else if(b.isDataArrayTexture)if(D){if(Se&&t.texStorage3D(i.TEXTURE_2D_ARRAY,xe,Pe,re.width,re.height,re.depth),oe)if(b.layerUpdates.size>0){const se=Om(re.width,re.height,b.format,b.type);for(const Q of b.layerUpdates){const he=re.data.subarray(Q*se/re.data.BYTES_PER_ELEMENT,(Q+1)*se/re.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,Q,re.width,re.height,1,me,Me,he)}b.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,re.width,re.height,re.depth,me,Me,re.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,Pe,re.width,re.height,re.depth,0,me,Me,re.data);else if(b.isData3DTexture)D?(Se&&t.texStorage3D(i.TEXTURE_3D,xe,Pe,re.width,re.height,re.depth),oe&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,re.width,re.height,re.depth,me,Me,re.data)):t.texImage3D(i.TEXTURE_3D,0,Pe,re.width,re.height,re.depth,0,me,Me,re.data);else if(b.isFramebufferTexture){if(Se)if(D)t.texStorage2D(i.TEXTURE_2D,xe,Pe,re.width,re.height);else{let se=re.width,Q=re.height;for(let he=0;he<xe;he++)t.texImage2D(i.TEXTURE_2D,he,Pe,se,Q,0,me,Me,null),se>>=1,Q>>=1}}else if(Xe.length>0){if(D&&Se){const se=Re(Xe[0]);t.texStorage2D(i.TEXTURE_2D,xe,Pe,se.width,se.height)}for(let se=0,Q=Xe.length;se<Q;se++)pe=Xe[se],D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,me,Me,pe):t.texImage2D(i.TEXTURE_2D,se,Pe,me,Me,pe);b.generateMipmaps=!1}else if(D){if(Se){const se=Re(re);t.texStorage2D(i.TEXTURE_2D,xe,Pe,se.width,se.height)}oe&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,me,Me,re)}else t.texImage2D(i.TEXTURE_2D,0,Pe,me,Me,re);m(b)&&p(X),ke.__version=j.version,b.onUpdate&&b.onUpdate(b)}A.__version=b.version}function ie(A,b,L){if(b.image.length!==6)return;const X=Ve(A,b),ee=b.source;t.bindTexture(i.TEXTURE_CUBE_MAP,A.__webglTexture,i.TEXTURE0+L);const j=n.get(ee);if(ee.version!==j.__version||X===!0){t.activeTexture(i.TEXTURE0+L);const ke=nt.getPrimaries(nt.workingColorSpace),fe=b.colorSpace===Zi?null:nt.getPrimaries(b.colorSpace),Ae=b.colorSpace===Zi||ke===fe?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,b.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,b.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ae);const Ue=b.isCompressedTexture||b.image[0].isCompressedTexture,re=b.image[0]&&b.image[0].isDataTexture,me=[];for(let Q=0;Q<6;Q++)!Ue&&!re?me[Q]=v(b.image[Q],!0,s.maxCubemapSize):me[Q]=re?b.image[Q].image:b.image[Q],me[Q]=_t(b,me[Q]);const Me=me[0],Pe=r.convert(b.format,b.colorSpace),pe=r.convert(b.type),Xe=E(b.internalFormat,Pe,pe,b.colorSpace),D=b.isVideoTexture!==!0,Se=j.__version===void 0||X===!0,oe=ee.dataReady;let xe=S(b,Me);Ge(i.TEXTURE_CUBE_MAP,b);let se;if(Ue){D&&Se&&t.texStorage2D(i.TEXTURE_CUBE_MAP,xe,Xe,Me.width,Me.height);for(let Q=0;Q<6;Q++){se=me[Q].mipmaps;for(let he=0;he<se.length;he++){const ze=se[he];b.format!==qn?Pe!==null?D?oe&&t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,he,0,0,ze.width,ze.height,Pe,ze.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,he,Xe,ze.width,ze.height,0,ze.data):Be("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,he,0,0,ze.width,ze.height,Pe,pe,ze.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,he,Xe,ze.width,ze.height,0,Pe,pe,ze.data)}}}else{if(se=b.mipmaps,D&&Se){se.length>0&&xe++;const Q=Re(me[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,xe,Xe,Q.width,Q.height)}for(let Q=0;Q<6;Q++)if(re){D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,0,0,me[Q].width,me[Q].height,Pe,pe,me[Q].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,Xe,me[Q].width,me[Q].height,0,Pe,pe,me[Q].data);for(let he=0;he<se.length;he++){const St=se[he].image[Q].image;D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,he+1,0,0,St.width,St.height,Pe,pe,St.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,he+1,Xe,St.width,St.height,0,Pe,pe,St.data)}}else{D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,0,0,Pe,pe,me[Q]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,Xe,Pe,pe,me[Q]);for(let he=0;he<se.length;he++){const ze=se[he];D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,he+1,0,0,Pe,pe,ze.image[Q]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,he+1,Xe,Pe,pe,ze.image[Q])}}}m(b)&&p(i.TEXTURE_CUBE_MAP),j.__version=ee.version,b.onUpdate&&b.onUpdate(b)}A.__version=b.version}function Ce(A,b,L,X,ee,j){const ke=r.convert(L.format,L.colorSpace),fe=r.convert(L.type),Ae=E(L.internalFormat,ke,fe,L.colorSpace),Ue=n.get(b),re=n.get(L);if(re.__renderTarget=b,!Ue.__hasExternalTextures){const me=Math.max(1,b.width>>j),Me=Math.max(1,b.height>>j);ee===i.TEXTURE_3D||ee===i.TEXTURE_2D_ARRAY?t.texImage3D(ee,j,Ae,me,Me,b.depth,0,ke,fe,null):t.texImage2D(ee,j,Ae,me,Me,0,ke,fe,null)}t.bindFramebuffer(i.FRAMEBUFFER,A),Gt(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,X,ee,re.__webglTexture,0,I(b)):(ee===i.TEXTURE_2D||ee>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&ee<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,X,ee,re.__webglTexture,j),t.bindFramebuffer(i.FRAMEBUFFER,null)}function qe(A,b,L){if(i.bindRenderbuffer(i.RENDERBUFFER,A),b.depthBuffer){const X=b.depthTexture,ee=X&&X.isDepthTexture?X.type:null,j=y(b.stencilBuffer,ee),ke=b.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;Gt(b)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(b),j,b.width,b.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(b),j,b.width,b.height):i.renderbufferStorage(i.RENDERBUFFER,j,b.width,b.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,ke,i.RENDERBUFFER,A)}else{const X=b.textures;for(let ee=0;ee<X.length;ee++){const j=X[ee],ke=r.convert(j.format,j.colorSpace),fe=r.convert(j.type),Ae=E(j.internalFormat,ke,fe,j.colorSpace);Gt(b)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(b),Ae,b.width,b.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(b),Ae,b.width,b.height):i.renderbufferStorage(i.RENDERBUFFER,Ae,b.width,b.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function we(A,b,L){const X=b.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(i.FRAMEBUFFER,A),!(b.depthTexture&&b.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const ee=n.get(b.depthTexture);if(ee.__renderTarget=b,(!ee.__webglTexture||b.depthTexture.image.width!==b.width||b.depthTexture.image.height!==b.height)&&(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0),X){if(ee.__webglInit===void 0&&(ee.__webglInit=!0,b.depthTexture.addEventListener("dispose",C)),ee.__webglTexture===void 0){ee.__webglTexture=i.createTexture(),t.bindTexture(i.TEXTURE_CUBE_MAP,ee.__webglTexture),Ge(i.TEXTURE_CUBE_MAP,b.depthTexture);const Ue=r.convert(b.depthTexture.format),re=r.convert(b.depthTexture.type);let me;b.depthTexture.format===Ei?me=i.DEPTH_COMPONENT24:b.depthTexture.format===bs&&(me=i.DEPTH24_STENCIL8);for(let Me=0;Me<6;Me++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Me,0,me,b.width,b.height,0,Ue,re,null)}}else K(b.depthTexture,0);const j=ee.__webglTexture,ke=I(b),fe=X?i.TEXTURE_CUBE_MAP_POSITIVE_X+L:i.TEXTURE_2D,Ae=b.depthTexture.format===bs?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;if(b.depthTexture.format===Ei)Gt(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Ae,fe,j,0,ke):i.framebufferTexture2D(i.FRAMEBUFFER,Ae,fe,j,0);else if(b.depthTexture.format===bs)Gt(b)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Ae,fe,j,0,ke):i.framebufferTexture2D(i.FRAMEBUFFER,Ae,fe,j,0);else throw new Error("Unknown depthTexture format")}function rt(A){const b=n.get(A),L=A.isWebGLCubeRenderTarget===!0;if(b.__boundDepthTexture!==A.depthTexture){const X=A.depthTexture;if(b.__depthDisposeCallback&&b.__depthDisposeCallback(),X){const ee=()=>{delete b.__boundDepthTexture,delete b.__depthDisposeCallback,X.removeEventListener("dispose",ee)};X.addEventListener("dispose",ee),b.__depthDisposeCallback=ee}b.__boundDepthTexture=X}if(A.depthTexture&&!b.__autoAllocateDepthBuffer)if(L)for(let X=0;X<6;X++)we(b.__webglFramebuffer[X],A,X);else{const X=A.texture.mipmaps;X&&X.length>0?we(b.__webglFramebuffer[0],A,0):we(b.__webglFramebuffer,A,0)}else if(L){b.__webglDepthbuffer=[];for(let X=0;X<6;X++)if(t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer[X]),b.__webglDepthbuffer[X]===void 0)b.__webglDepthbuffer[X]=i.createRenderbuffer(),qe(b.__webglDepthbuffer[X],A,!1);else{const ee=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=b.__webglDepthbuffer[X];i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,ee,i.RENDERBUFFER,j)}}else{const X=A.texture.mipmaps;if(X&&X.length>0?t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,b.__webglFramebuffer),b.__webglDepthbuffer===void 0)b.__webglDepthbuffer=i.createRenderbuffer(),qe(b.__webglDepthbuffer,A,!1);else{const ee=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=b.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,ee,i.RENDERBUFFER,j)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function Jt(A,b,L){const X=n.get(A);b!==void 0&&Ce(X.__webglFramebuffer,A,A.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),L!==void 0&&rt(A)}function it(A){const b=A.texture,L=n.get(A),X=n.get(b);A.addEventListener("dispose",w);const ee=A.textures,j=A.isWebGLCubeRenderTarget===!0,ke=ee.length>1;if(ke||(X.__webglTexture===void 0&&(X.__webglTexture=i.createTexture()),X.__version=b.version,o.memory.textures++),j){L.__webglFramebuffer=[];for(let fe=0;fe<6;fe++)if(b.mipmaps&&b.mipmaps.length>0){L.__webglFramebuffer[fe]=[];for(let Ae=0;Ae<b.mipmaps.length;Ae++)L.__webglFramebuffer[fe][Ae]=i.createFramebuffer()}else L.__webglFramebuffer[fe]=i.createFramebuffer()}else{if(b.mipmaps&&b.mipmaps.length>0){L.__webglFramebuffer=[];for(let fe=0;fe<b.mipmaps.length;fe++)L.__webglFramebuffer[fe]=i.createFramebuffer()}else L.__webglFramebuffer=i.createFramebuffer();if(ke)for(let fe=0,Ae=ee.length;fe<Ae;fe++){const Ue=n.get(ee[fe]);Ue.__webglTexture===void 0&&(Ue.__webglTexture=i.createTexture(),o.memory.textures++)}if(A.samples>0&&Gt(A)===!1){L.__webglMultisampledFramebuffer=i.createFramebuffer(),L.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,L.__webglMultisampledFramebuffer);for(let fe=0;fe<ee.length;fe++){const Ae=ee[fe];L.__webglColorRenderbuffer[fe]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,L.__webglColorRenderbuffer[fe]);const Ue=r.convert(Ae.format,Ae.colorSpace),re=r.convert(Ae.type),me=E(Ae.internalFormat,Ue,re,Ae.colorSpace,A.isXRRenderTarget===!0),Me=I(A);i.renderbufferStorageMultisample(i.RENDERBUFFER,Me,me,A.width,A.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+fe,i.RENDERBUFFER,L.__webglColorRenderbuffer[fe])}i.bindRenderbuffer(i.RENDERBUFFER,null),A.depthBuffer&&(L.__webglDepthRenderbuffer=i.createRenderbuffer(),qe(L.__webglDepthRenderbuffer,A,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(j){t.bindTexture(i.TEXTURE_CUBE_MAP,X.__webglTexture),Ge(i.TEXTURE_CUBE_MAP,b);for(let fe=0;fe<6;fe++)if(b.mipmaps&&b.mipmaps.length>0)for(let Ae=0;Ae<b.mipmaps.length;Ae++)Ce(L.__webglFramebuffer[fe][Ae],A,b,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae);else Ce(L.__webglFramebuffer[fe],A,b,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+fe,0);m(b)&&p(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(ke){for(let fe=0,Ae=ee.length;fe<Ae;fe++){const Ue=ee[fe],re=n.get(Ue);let me=i.TEXTURE_2D;(A.isWebGL3DRenderTarget||A.isWebGLArrayRenderTarget)&&(me=A.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(me,re.__webglTexture),Ge(me,Ue),Ce(L.__webglFramebuffer,A,Ue,i.COLOR_ATTACHMENT0+fe,me,0),m(Ue)&&p(me)}t.unbindTexture()}else{let fe=i.TEXTURE_2D;if((A.isWebGL3DRenderTarget||A.isWebGLArrayRenderTarget)&&(fe=A.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(fe,X.__webglTexture),Ge(fe,b),b.mipmaps&&b.mipmaps.length>0)for(let Ae=0;Ae<b.mipmaps.length;Ae++)Ce(L.__webglFramebuffer[Ae],A,b,i.COLOR_ATTACHMENT0,fe,Ae);else Ce(L.__webglFramebuffer,A,b,i.COLOR_ATTACHMENT0,fe,0);m(b)&&p(fe),t.unbindTexture()}A.depthBuffer&&rt(A)}function dt(A){const b=A.textures;for(let L=0,X=b.length;L<X;L++){const ee=b[L];if(m(ee)){const j=T(A),ke=n.get(ee).__webglTexture;t.bindTexture(j,ke),p(j),t.unbindTexture()}}}const yt=[],$e=[];function Vt(A){if(A.samples>0){if(Gt(A)===!1){const b=A.textures,L=A.width,X=A.height;let ee=i.COLOR_BUFFER_BIT;const j=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ke=n.get(A),fe=b.length>1;if(fe)for(let Ue=0;Ue<b.length;Ue++)t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,ke.__webglMultisampledFramebuffer);const Ae=A.texture.mipmaps;Ae&&Ae.length>0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglFramebuffer);for(let Ue=0;Ue<b.length;Ue++){if(A.resolveDepthBuffer&&(A.depthBuffer&&(ee|=i.DEPTH_BUFFER_BIT),A.stencilBuffer&&A.resolveStencilBuffer&&(ee|=i.STENCIL_BUFFER_BIT)),fe){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,ke.__webglColorRenderbuffer[Ue]);const re=n.get(b[Ue]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,re,0)}i.blitFramebuffer(0,0,L,X,0,0,L,X,ee,i.NEAREST),c===!0&&(yt.length=0,$e.length=0,yt.push(i.COLOR_ATTACHMENT0+Ue),A.depthBuffer&&A.resolveDepthBuffer===!1&&(yt.push(j),$e.push(j),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,$e)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,yt))}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),fe)for(let Ue=0;Ue<b.length;Ue++){t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.RENDERBUFFER,ke.__webglColorRenderbuffer[Ue]);const re=n.get(b[Ue]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.TEXTURE_2D,re,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglMultisampledFramebuffer)}else if(A.depthBuffer&&A.resolveDepthBuffer===!1&&c){const b=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[b])}}}function I(A){return Math.min(s.maxSamples,A.samples)}function Gt(A){const b=n.get(A);return A.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&b.__useRenderToTexture!==!1}function ct(A){const b=o.render.frame;d.get(A)!==b&&(d.set(A,b),A.update())}function _t(A,b){const L=A.colorSpace,X=A.format,ee=A.type;return A.isCompressedTexture===!0||A.isVideoTexture===!0||L!==er&&L!==Zi&&(nt.getTransfer(L)===lt?(X!==qn||ee!==wn)&&Be("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):st("WebGLTextures: Unsupported texture color space:",L)),b}function Re(A){return typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement?(l.width=A.naturalWidth||A.width,l.height=A.naturalHeight||A.height):typeof VideoFrame<"u"&&A instanceof VideoFrame?(l.width=A.displayWidth,l.height=A.displayHeight):(l.width=A.width,l.height=A.height),l}this.allocateTextureUnit=F,this.resetTextureUnits=O,this.setTexture2D=K,this.setTexture2DArray=G,this.setTexture3D=W,this.setTextureCube=te,this.rebindTextures=Jt,this.setupRenderTarget=it,this.updateRenderTargetMipmap=dt,this.updateMultisampleRenderTarget=Vt,this.setupDepthRenderbuffer=rt,this.setupFrameBufferTexture=Ce,this.useMultisampledRTT=Gt,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function $E(i,e){function t(n,s=Zi){let r;const o=nt.getTransfer(s);if(n===wn)return i.UNSIGNED_BYTE;if(n===Ul)return i.UNSIGNED_SHORT_4_4_4_4;if(n===Fl)return i.UNSIGNED_SHORT_5_5_5_1;if(n===Hp)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===Wp)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===Vp)return i.BYTE;if(n===Gp)return i.SHORT;if(n===Yr)return i.UNSIGNED_SHORT;if(n===Ol)return i.INT;if(n===si)return i.UNSIGNED_INT;if(n===ri)return i.FLOAT;if(n===Ci)return i.HALF_FLOAT;if(n===qp)return i.ALPHA;if(n===jp)return i.RGB;if(n===qn)return i.RGBA;if(n===Ei)return i.DEPTH_COMPONENT;if(n===bs)return i.DEPTH_STENCIL;if(n===$p)return i.RED;if(n===Bl)return i.RED_INTEGER;if(n===Qs)return i.RG;if(n===zl)return i.RG_INTEGER;if(n===Vl)return i.RGBA_INTEGER;if(n===lo||n===uo||n===ho||n===fo)if(o===lt)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===lo)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===uo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===ho)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===fo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===lo)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===uo)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===ho)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===fo)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Gl||n===Hl||n===Wl||n===ql)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===Gl)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===Hl)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Wl)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===ql)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===jl||n===$l||n===Xl||n===Kl||n===Yl||n===Jl||n===Zl)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(n===jl||n===$l)return o===lt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===Xl)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===Kl)return r.COMPRESSED_R11_EAC;if(n===Yl)return r.COMPRESSED_SIGNED_R11_EAC;if(n===Jl)return r.COMPRESSED_RG11_EAC;if(n===Zl)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===Ql||n===ed||n===td||n===nd||n===id||n===sd||n===rd||n===ad||n===od||n===cd||n===ld||n===dd||n===ud||n===hd)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(n===Ql)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===ed)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===td)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===nd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===id)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===sd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===rd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===ad)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===od)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===cd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===ld)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===dd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===ud)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===hd)return o===lt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===fd||n===pd||n===md)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(n===fd)return o===lt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===pd)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===md)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===gd||n===vd||n===yd||n===bd)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(n===gd)return r.COMPRESSED_RED_RGTC1_EXT;if(n===vd)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===yd)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===bd)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Jr?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const XE=`
4079
4079
  void main() {
4080
4080
 
4081
4081
  gl_Position = vec4( position, 1.0 );
@@ -4099,7 +4099,7 @@ void main() {
4099
4099
 
4100
4100
  }
4101
4101
 
4102
- }`;class YE{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new km(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new en({vertexShader:XE,fragmentShader:KE,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Sn(new Vo(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class JE extends nr{constructor(e,t){super();const n=this;let s=null,r=1,o=null,a="local-floor",c=1,l=null,d=null,u=null,h=null,f=null,g=null;const v=typeof XRWebGLBinding<"u",m=new YE,p={},T=t.getContextAttributes();let E=null,y=null;const S=[],C=[],w=new tt;let k=null;const _=new xn;_.viewport=new Dt;const x=new xn;x.viewport=new Dt;const R=[_,x],O=new VS;let F=null,q=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Y){let ie=S[Y];return ie===void 0&&(ie=new $d,S[Y]=ie),ie.getTargetRaySpace()},this.getControllerGrip=function(Y){let ie=S[Y];return ie===void 0&&(ie=new $d,S[Y]=ie),ie.getGripSpace()},this.getHand=function(Y){let ie=S[Y];return ie===void 0&&(ie=new $d,S[Y]=ie),ie.getHandSpace()};function K(Y){const ie=C.indexOf(Y.inputSource);if(ie===-1)return;const Ce=S[ie];Ce!==void 0&&(Ce.update(Y.inputSource,Y.frame,l||o),Ce.dispatchEvent({type:Y.type,data:Y.inputSource}))}function G(){s.removeEventListener("select",K),s.removeEventListener("selectstart",K),s.removeEventListener("selectend",K),s.removeEventListener("squeeze",K),s.removeEventListener("squeezestart",K),s.removeEventListener("squeezeend",K),s.removeEventListener("end",G),s.removeEventListener("inputsourceschange",W);for(let Y=0;Y<S.length;Y++){const ie=C[Y];ie!==null&&(C[Y]=null,S[Y].disconnect(ie))}F=null,q=null,m.reset();for(const Y in p)delete p[Y];e.setRenderTarget(E),f=null,h=null,u=null,s=null,y=null,pt.stop(),n.isPresenting=!1,e.setPixelRatio(k),e.setSize(w.width,w.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Y){r=Y,n.isPresenting===!0&&Be("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Y){a=Y,n.isPresenting===!0&&Be("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||o},this.setReferenceSpace=function(Y){l=Y},this.getBaseLayer=function(){return h!==null?h:f},this.getBinding=function(){return u===null&&v&&(u=new XRWebGLBinding(s,t)),u},this.getFrame=function(){return g},this.getSession=function(){return s},this.setSession=async function(Y){if(s=Y,s!==null){if(E=e.getRenderTarget(),s.addEventListener("select",K),s.addEventListener("selectstart",K),s.addEventListener("selectend",K),s.addEventListener("squeeze",K),s.addEventListener("squeezestart",K),s.addEventListener("squeezeend",K),s.addEventListener("end",G),s.addEventListener("inputsourceschange",W),T.xrCompatible!==!0&&await t.makeXRCompatible(),k=e.getPixelRatio(),e.getSize(w),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let Ce=null,qe=null,we=null;T.depth&&(we=T.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,Ce=T.stencil?bs:Ei,qe=T.stencil?Jr:si);const rt={colorFormat:t.RGBA8,depthFormat:we,scaleFactor:r};u=this.getBinding(),h=u.createProjectionLayer(rt),s.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),y=new oi(h.textureWidth,h.textureHeight,{format:qn,type:Mn,depthTexture:new da(h.textureWidth,h.textureHeight,qe,void 0,void 0,void 0,void 0,void 0,void 0,Ce),stencilBuffer:T.stencil,colorSpace:e.outputColorSpace,samples:T.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1})}else{const Ce={antialias:T.antialias,alpha:!0,depth:T.depth,stencil:T.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(s,t,Ce),s.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new oi(f.framebufferWidth,f.framebufferHeight,{format:qn,type:Mn,colorSpace:e.outputColorSpace,stencilBuffer:T.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(c),l=null,o=await s.requestReferenceSpace(a),pt.setContext(s),pt.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function W(Y){for(let ie=0;ie<Y.removed.length;ie++){const Ce=Y.removed[ie],qe=C.indexOf(Ce);qe>=0&&(C[qe]=null,S[qe].disconnect(Ce))}for(let ie=0;ie<Y.added.length;ie++){const Ce=Y.added[ie];let qe=C.indexOf(Ce);if(qe===-1){for(let rt=0;rt<S.length;rt++)if(rt>=C.length){C.push(Ce),qe=rt;break}else if(C[rt]===null){C[rt]=Ce,qe=rt;break}if(qe===-1)break}const we=S[qe];we&&we.connect(Ce)}}const te=new U,ye=new U;function de(Y,ie,Ce){te.setFromMatrixPosition(ie.matrixWorld),ye.setFromMatrixPosition(Ce.matrixWorld);const qe=te.distanceTo(ye),we=ie.projectionMatrix.elements,rt=Ce.projectionMatrix.elements,Yt=we[14]/(we[10]-1),it=we[14]/(we[10]+1),dt=(we[9]+1)/we[5],yt=(we[9]-1)/we[5],$e=(we[8]-1)/we[0],Vt=(rt[8]+1)/rt[0],I=Yt*$e,Gt=Yt*Vt,ct=qe/(-$e+Vt),_t=ct*-$e;if(ie.matrixWorld.decompose(Y.position,Y.quaternion,Y.scale),Y.translateX(_t),Y.translateZ(ct),Y.matrixWorld.compose(Y.position,Y.quaternion,Y.scale),Y.matrixWorldInverse.copy(Y.matrixWorld).invert(),we[10]===-1)Y.projectionMatrix.copy(ie.projectionMatrix),Y.projectionMatrixInverse.copy(ie.projectionMatrixInverse);else{const Re=Yt+ct,A=it+ct,b=I-_t,L=Gt+(qe-_t),X=dt*it/A*Re,ee=yt*it/A*Re;Y.projectionMatrix.makePerspective(b,L,X,ee,Re,A),Y.projectionMatrixInverse.copy(Y.projectionMatrix).invert()}}function _e(Y,ie){ie===null?Y.matrixWorld.copy(Y.matrix):Y.matrixWorld.multiplyMatrices(ie.matrixWorld,Y.matrix),Y.matrixWorldInverse.copy(Y.matrixWorld).invert()}this.updateCamera=function(Y){if(s===null)return;let ie=Y.near,Ce=Y.far;m.texture!==null&&(m.depthNear>0&&(ie=m.depthNear),m.depthFar>0&&(Ce=m.depthFar)),O.near=x.near=_.near=ie,O.far=x.far=_.far=Ce,(F!==O.near||q!==O.far)&&(s.updateRenderState({depthNear:O.near,depthFar:O.far}),F=O.near,q=O.far),O.layers.mask=Y.layers.mask|6,_.layers.mask=O.layers.mask&3,x.layers.mask=O.layers.mask&5;const qe=Y.parent,we=O.cameras;_e(O,qe);for(let rt=0;rt<we.length;rt++)_e(we[rt],qe);we.length===2?de(O,_,x):O.projectionMatrix.copy(_.projectionMatrix),Ge(Y,O,qe)};function Ge(Y,ie,Ce){Ce===null?Y.matrix.copy(ie.matrixWorld):(Y.matrix.copy(Ce.matrixWorld),Y.matrix.invert(),Y.matrix.multiply(ie.matrixWorld)),Y.matrix.decompose(Y.position,Y.quaternion,Y.scale),Y.updateMatrixWorld(!0),Y.projectionMatrix.copy(ie.projectionMatrix),Y.projectionMatrixInverse.copy(ie.projectionMatrixInverse),Y.isPerspectiveCamera&&(Y.fov=Td*2*Math.atan(1/Y.projectionMatrix.elements[5]),Y.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(!(h===null&&f===null))return c},this.setFoveation=function(Y){c=Y,h!==null&&(h.fixedFoveation=Y),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=Y)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(O)},this.getCameraTexture=function(Y){return p[Y]};let Ve=null;function Mt(Y,ie){if(d=ie.getViewerPose(l||o),g=ie,d!==null){const Ce=d.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let qe=!1;Ce.length!==O.cameras.length&&(O.cameras.length=0,qe=!0);for(let it=0;it<Ce.length;it++){const dt=Ce[it];let yt=null;if(f!==null)yt=f.getViewport(dt);else{const Vt=u.getViewSubImage(h,dt);yt=Vt.viewport,it===0&&(e.setRenderTargetTextures(y,Vt.colorTexture,Vt.depthStencilTexture),e.setRenderTarget(y))}let $e=R[it];$e===void 0&&($e=new xn,$e.layers.enable(it),$e.viewport=new Dt,R[it]=$e),$e.matrix.fromArray(dt.transform.matrix),$e.matrix.decompose($e.position,$e.quaternion,$e.scale),$e.projectionMatrix.fromArray(dt.projectionMatrix),$e.projectionMatrixInverse.copy($e.projectionMatrix).invert(),$e.viewport.set(yt.x,yt.y,yt.width,yt.height),it===0&&(O.matrix.copy($e.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),qe===!0&&O.cameras.push($e)}const we=s.enabledFeatures;if(we&&we.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&v){u=n.getBinding();const it=u.getDepthInformation(Ce[0]);it&&it.isValid&&it.texture&&m.init(it,s.renderState)}if(we&&we.includes("camera-access")&&v){e.state.unbindTexture(),u=n.getBinding();for(let it=0;it<Ce.length;it++){const dt=Ce[it].camera;if(dt){let yt=p[dt];yt||(yt=new km,p[dt]=yt);const $e=u.getCameraImage(dt);yt.sourceTexture=$e}}}}for(let Ce=0;Ce<S.length;Ce++){const qe=C[Ce],we=S[Ce];qe!==null&&we!==void 0&&we.update(qe,ie,l||o)}Ve&&Ve(Y,ie),ie.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:ie}),g=null}const pt=new Um;pt.setAnimationLoop(Mt),this.setAnimationLoop=function(Y){Ve=Y},this.dispose=function(){}}}const ws=new Ri,ZE=new At;function QE(i,e){function t(m,p){m.matrixAutoUpdate===!0&&m.updateMatrix(),p.value.copy(m.matrix)}function n(m,p){p.color.getRGB(m.fogColor.value,_m(i)),p.isFog?(m.fogNear.value=p.near,m.fogFar.value=p.far):p.isFogExp2&&(m.fogDensity.value=p.density)}function s(m,p,T,E,y){p.isMeshBasicMaterial||p.isMeshLambertMaterial?r(m,p):p.isMeshToonMaterial?(r(m,p),u(m,p)):p.isMeshPhongMaterial?(r(m,p),d(m,p)):p.isMeshStandardMaterial?(r(m,p),h(m,p),p.isMeshPhysicalMaterial&&f(m,p,y)):p.isMeshMatcapMaterial?(r(m,p),g(m,p)):p.isMeshDepthMaterial?r(m,p):p.isMeshDistanceMaterial?(r(m,p),v(m,p)):p.isMeshNormalMaterial?r(m,p):p.isLineBasicMaterial?(o(m,p),p.isLineDashedMaterial&&a(m,p)):p.isPointsMaterial?c(m,p,T,E):p.isSpriteMaterial?l(m,p):p.isShadowMaterial?(m.color.value.copy(p.color),m.opacity.value=p.opacity):p.isShaderMaterial&&(p.uniformsNeedUpdate=!1)}function r(m,p){m.opacity.value=p.opacity,p.color&&m.diffuse.value.copy(p.color),p.emissive&&m.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity),p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.bumpMap&&(m.bumpMap.value=p.bumpMap,t(p.bumpMap,m.bumpMapTransform),m.bumpScale.value=p.bumpScale,p.side===tn&&(m.bumpScale.value*=-1)),p.normalMap&&(m.normalMap.value=p.normalMap,t(p.normalMap,m.normalMapTransform),m.normalScale.value.copy(p.normalScale),p.side===tn&&m.normalScale.value.negate()),p.displacementMap&&(m.displacementMap.value=p.displacementMap,t(p.displacementMap,m.displacementMapTransform),m.displacementScale.value=p.displacementScale,m.displacementBias.value=p.displacementBias),p.emissiveMap&&(m.emissiveMap.value=p.emissiveMap,t(p.emissiveMap,m.emissiveMapTransform)),p.specularMap&&(m.specularMap.value=p.specularMap,t(p.specularMap,m.specularMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest);const T=e.get(p),E=T.envMap,y=T.envMapRotation;E&&(m.envMap.value=E,ws.copy(y),ws.x*=-1,ws.y*=-1,ws.z*=-1,E.isCubeTexture&&E.isRenderTargetTexture===!1&&(ws.y*=-1,ws.z*=-1),m.envMapRotation.value.setFromMatrix4(ZE.makeRotationFromEuler(ws)),m.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=p.reflectivity,m.ior.value=p.ior,m.refractionRatio.value=p.refractionRatio),p.lightMap&&(m.lightMap.value=p.lightMap,m.lightMapIntensity.value=p.lightMapIntensity,t(p.lightMap,m.lightMapTransform)),p.aoMap&&(m.aoMap.value=p.aoMap,m.aoMapIntensity.value=p.aoMapIntensity,t(p.aoMap,m.aoMapTransform))}function o(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform))}function a(m,p){m.dashSize.value=p.dashSize,m.totalSize.value=p.dashSize+p.gapSize,m.scale.value=p.scale}function c(m,p,T,E){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.size.value=p.size*T,m.scale.value=E*.5,p.map&&(m.map.value=p.map,t(p.map,m.uvTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function l(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.rotation.value=p.rotation,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function d(m,p){m.specular.value.copy(p.specular),m.shininess.value=Math.max(p.shininess,1e-4)}function u(m,p){p.gradientMap&&(m.gradientMap.value=p.gradientMap)}function h(m,p){m.metalness.value=p.metalness,p.metalnessMap&&(m.metalnessMap.value=p.metalnessMap,t(p.metalnessMap,m.metalnessMapTransform)),m.roughness.value=p.roughness,p.roughnessMap&&(m.roughnessMap.value=p.roughnessMap,t(p.roughnessMap,m.roughnessMapTransform)),p.envMap&&(m.envMapIntensity.value=p.envMapIntensity)}function f(m,p,T){m.ior.value=p.ior,p.sheen>0&&(m.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen),m.sheenRoughness.value=p.sheenRoughness,p.sheenColorMap&&(m.sheenColorMap.value=p.sheenColorMap,t(p.sheenColorMap,m.sheenColorMapTransform)),p.sheenRoughnessMap&&(m.sheenRoughnessMap.value=p.sheenRoughnessMap,t(p.sheenRoughnessMap,m.sheenRoughnessMapTransform))),p.clearcoat>0&&(m.clearcoat.value=p.clearcoat,m.clearcoatRoughness.value=p.clearcoatRoughness,p.clearcoatMap&&(m.clearcoatMap.value=p.clearcoatMap,t(p.clearcoatMap,m.clearcoatMapTransform)),p.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=p.clearcoatRoughnessMap,t(p.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),p.clearcoatNormalMap&&(m.clearcoatNormalMap.value=p.clearcoatNormalMap,t(p.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(p.clearcoatNormalScale),p.side===tn&&m.clearcoatNormalScale.value.negate())),p.dispersion>0&&(m.dispersion.value=p.dispersion),p.iridescence>0&&(m.iridescence.value=p.iridescence,m.iridescenceIOR.value=p.iridescenceIOR,m.iridescenceThicknessMinimum.value=p.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=p.iridescenceThicknessRange[1],p.iridescenceMap&&(m.iridescenceMap.value=p.iridescenceMap,t(p.iridescenceMap,m.iridescenceMapTransform)),p.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=p.iridescenceThicknessMap,t(p.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),p.transmission>0&&(m.transmission.value=p.transmission,m.transmissionSamplerMap.value=T.texture,m.transmissionSamplerSize.value.set(T.width,T.height),p.transmissionMap&&(m.transmissionMap.value=p.transmissionMap,t(p.transmissionMap,m.transmissionMapTransform)),m.thickness.value=p.thickness,p.thicknessMap&&(m.thicknessMap.value=p.thicknessMap,t(p.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=p.attenuationDistance,m.attenuationColor.value.copy(p.attenuationColor)),p.anisotropy>0&&(m.anisotropyVector.value.set(p.anisotropy*Math.cos(p.anisotropyRotation),p.anisotropy*Math.sin(p.anisotropyRotation)),p.anisotropyMap&&(m.anisotropyMap.value=p.anisotropyMap,t(p.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=p.specularIntensity,m.specularColor.value.copy(p.specularColor),p.specularColorMap&&(m.specularColorMap.value=p.specularColorMap,t(p.specularColorMap,m.specularColorMapTransform)),p.specularIntensityMap&&(m.specularIntensityMap.value=p.specularIntensityMap,t(p.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,p){p.matcap&&(m.matcap.value=p.matcap)}function v(m,p){const T=e.get(p).light;m.referencePosition.value.setFromMatrixPosition(T.matrixWorld),m.nearDistance.value=T.shadow.camera.near,m.farDistance.value=T.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function eM(i,e,t,n){let s={},r={},o=[];const a=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(T,E){const y=E.program;n.uniformBlockBinding(T,y)}function l(T,E){let y=s[T.id];y===void 0&&(g(T),y=d(T),s[T.id]=y,T.addEventListener("dispose",m));const S=E.program;n.updateUBOMapping(T,S);const C=e.render.frame;r[T.id]!==C&&(h(T),r[T.id]=C)}function d(T){const E=u();T.__bindingPointIndex=E;const y=i.createBuffer(),S=T.__size,C=T.usage;return i.bindBuffer(i.UNIFORM_BUFFER,y),i.bufferData(i.UNIFORM_BUFFER,S,C),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,E,y),y}function u(){for(let T=0;T<a;T++)if(o.indexOf(T)===-1)return o.push(T),T;return st("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(T){const E=s[T.id],y=T.uniforms,S=T.__cache;i.bindBuffer(i.UNIFORM_BUFFER,E);for(let C=0,w=y.length;C<w;C++){const k=Array.isArray(y[C])?y[C]:[y[C]];for(let _=0,x=k.length;_<x;_++){const R=k[_];if(f(R,C,_,S)===!0){const O=R.__offset,F=Array.isArray(R.value)?R.value:[R.value];let q=0;for(let K=0;K<F.length;K++){const G=F[K],W=v(G);typeof G=="number"||typeof G=="boolean"?(R.__data[0]=G,i.bufferSubData(i.UNIFORM_BUFFER,O+q,R.__data)):G.isMatrix3?(R.__data[0]=G.elements[0],R.__data[1]=G.elements[1],R.__data[2]=G.elements[2],R.__data[3]=0,R.__data[4]=G.elements[3],R.__data[5]=G.elements[4],R.__data[6]=G.elements[5],R.__data[7]=0,R.__data[8]=G.elements[6],R.__data[9]=G.elements[7],R.__data[10]=G.elements[8],R.__data[11]=0):(G.toArray(R.__data,q),q+=W.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,O,R.__data)}}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function f(T,E,y,S){const C=T.value,w=E+"_"+y;if(S[w]===void 0)return typeof C=="number"||typeof C=="boolean"?S[w]=C:S[w]=C.clone(),!0;{const k=S[w];if(typeof C=="number"||typeof C=="boolean"){if(k!==C)return S[w]=C,!0}else if(k.equals(C)===!1)return k.copy(C),!0}return!1}function g(T){const E=T.uniforms;let y=0;const S=16;for(let w=0,k=E.length;w<k;w++){const _=Array.isArray(E[w])?E[w]:[E[w]];for(let x=0,R=_.length;x<R;x++){const O=_[x],F=Array.isArray(O.value)?O.value:[O.value];for(let q=0,K=F.length;q<K;q++){const G=F[q],W=v(G),te=y%S,ye=te%W.boundary,de=te+ye;y+=ye,de!==0&&S-de<W.storage&&(y+=S-de),O.__data=new Float32Array(W.storage/Float32Array.BYTES_PER_ELEMENT),O.__offset=y,y+=W.storage}}}const C=y%S;return C>0&&(y+=S-C),T.__size=y,T.__cache={},this}function v(T){const E={boundary:0,storage:0};return typeof T=="number"||typeof T=="boolean"?(E.boundary=4,E.storage=4):T.isVector2?(E.boundary=8,E.storage=8):T.isVector3||T.isColor?(E.boundary=16,E.storage=12):T.isVector4?(E.boundary=16,E.storage=16):T.isMatrix3?(E.boundary=48,E.storage=48):T.isMatrix4?(E.boundary=64,E.storage=64):T.isTexture?Be("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Be("WebGLRenderer: Unsupported uniform value type.",T),E}function m(T){const E=T.target;E.removeEventListener("dispose",m);const y=o.indexOf(E.__bindingPointIndex);o.splice(y,1),i.deleteBuffer(s[E.id]),delete s[E.id],delete r[E.id]}function p(){for(const T in s)i.deleteBuffer(s[T]);o=[],s={},r={}}return{bind:c,update:l,dispose:p}}const tM=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 li=null;function nM(){return li===null&&(li=new ES(tM,16,16,Qs,Ci),li.name="DFG_LUT",li.minFilter=nn,li.magFilter=nn,li.wrapS=Ti,li.wrapT=Ti,li.generateMipmaps=!1,li.needsUpdate=!0),li}class ug{constructor(e={}){const{canvas:t=Q_(),context:n=null,depth:s=!0,stencil:r=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:h=!1,outputBufferType:f=Mn}=e;this.isWebGLRenderer=!0;let g;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=n.getContextAttributes().alpha}else g=o;const v=f,m=new Set([Vl,zl,Bl]),p=new Set([Mn,si,Yr,Jr,Ul,Fl]),T=new Uint32Array(4),E=new Int32Array(4);let y=null,S=null;const C=[],w=[];let k=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ii,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const _=this;let x=!1;this._outputColorSpace=Nn;let R=0,O=0,F=null,q=-1,K=null;const G=new Dt,W=new Dt;let te=null;const ye=new Fe(0);let de=0,_e=t.width,Ge=t.height,Ve=1,Mt=null,pt=null;const Y=new Dt(0,0,_e,Ge),ie=new Dt(0,0,_e,Ge);let Ce=!1;const qe=new Kd;let we=!1,rt=!1;const Yt=new At,it=new U,dt=new Dt,yt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let $e=!1;function Vt(){return F===null?Ve:1}let I=n;function Gt(M,N){return t.getContext(M,N)}try{const M={alpha:!0,depth:s,stencil:r,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:d,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Sl}`),t.addEventListener("webglcontextlost",ze,!1),t.addEventListener("webglcontextrestored",St,!1),t.addEventListener("webglcontextcreationerror",ut,!1),I===null){const N="webgl2";if(I=Gt(N,M),I===null)throw Gt(N)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(M){throw st("WebGLRenderer: "+M.message),M}let ct,_t,Re,A,b,L,X,ee,j,ke,he,Ae,Ue,re,me,Me,Pe,fe,Xe,D,Se,oe,xe,se;function Q(){ct=new nC(I),ct.init(),oe=new $E(I,ct),_t=new $T(I,ct,e,oe),Re=new qE(I,ct),_t.reversedDepthBuffer&&h&&Re.buffers.depth.setReversed(!0),A=new rC(I),b=new PE,L=new jE(I,ct,Re,b,_t,oe,A),X=new KT(_),ee=new tC(_),j=new HS(I),xe=new qT(I,j),ke=new iC(I,j,A,xe),he=new oC(I,ke,j,A),Xe=new aC(I,_t,L),Me=new XT(b),Ae=new RE(_,X,ee,ct,_t,xe,Me),Ue=new QE(_,b),re=new IE,me=new FE(ct),fe=new WT(_,X,ee,Re,he,g,c),Pe=new HE(_,he,_t),se=new eM(I,A,_t,Re),D=new jT(I,ct,A),Se=new sC(I,ct,A),A.programs=Ae.programs,_.capabilities=_t,_.extensions=ct,_.properties=b,_.renderLists=re,_.shadowMap=Pe,_.state=Re,_.info=A}Q(),v!==Mn&&(k=new lC(v,t.width,t.height,s,r));const ue=new JE(_,I);this.xr=ue,this.getContext=function(){return I},this.getContextAttributes=function(){return I.getContextAttributes()},this.forceContextLoss=function(){const M=ct.get("WEBGL_lose_context");M&&M.loseContext()},this.forceContextRestore=function(){const M=ct.get("WEBGL_lose_context");M&&M.restoreContext()},this.getPixelRatio=function(){return Ve},this.setPixelRatio=function(M){M!==void 0&&(Ve=M,this.setSize(_e,Ge,!1))},this.getSize=function(M){return M.set(_e,Ge)},this.setSize=function(M,N,H=!0){if(ue.isPresenting){Be("WebGLRenderer: Can't change size while VR device is presenting.");return}_e=M,Ge=N,t.width=Math.floor(M*Ve),t.height=Math.floor(N*Ve),H===!0&&(t.style.width=M+"px",t.style.height=N+"px"),k!==null&&k.setSize(t.width,t.height),this.setViewport(0,0,M,N)},this.getDrawingBufferSize=function(M){return M.set(_e*Ve,Ge*Ve).floor()},this.setDrawingBufferSize=function(M,N,H){_e=M,Ge=N,Ve=H,t.width=Math.floor(M*H),t.height=Math.floor(N*H),this.setViewport(0,0,M,N)},this.setEffects=function(M){if(v===Mn){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(M){for(let N=0;N<M.length;N++)if(M[N].isOutputPass===!0){console.warn("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}k.setEffects(M||[])},this.getCurrentViewport=function(M){return M.copy(G)},this.getViewport=function(M){return M.copy(Y)},this.setViewport=function(M,N,H,V){M.isVector4?Y.set(M.x,M.y,M.z,M.w):Y.set(M,N,H,V),Re.viewport(G.copy(Y).multiplyScalar(Ve).round())},this.getScissor=function(M){return M.copy(ie)},this.setScissor=function(M,N,H,V){M.isVector4?ie.set(M.x,M.y,M.z,M.w):ie.set(M,N,H,V),Re.scissor(W.copy(ie).multiplyScalar(Ve).round())},this.getScissorTest=function(){return Ce},this.setScissorTest=function(M){Re.setScissorTest(Ce=M)},this.setOpaqueSort=function(M){Mt=M},this.setTransparentSort=function(M){pt=M},this.getClearColor=function(M){return M.copy(fe.getClearColor())},this.setClearColor=function(){fe.setClearColor(...arguments)},this.getClearAlpha=function(){return fe.getClearAlpha()},this.setClearAlpha=function(){fe.setClearAlpha(...arguments)},this.clear=function(M=!0,N=!0,H=!0){let V=0;if(M){let B=!1;if(F!==null){const ge=F.texture.format;B=m.has(ge)}if(B){const ge=F.texture.type,Te=p.has(ge),be=fe.getClearColor(),Ee=fe.getClearAlpha(),Ie=be.r,Oe=be.g,De=be.b;Te?(T[0]=Ie,T[1]=Oe,T[2]=De,T[3]=Ee,I.clearBufferuiv(I.COLOR,0,T)):(E[0]=Ie,E[1]=Oe,E[2]=De,E[3]=Ee,I.clearBufferiv(I.COLOR,0,E))}else V|=I.COLOR_BUFFER_BIT}N&&(V|=I.DEPTH_BUFFER_BIT),H&&(V|=I.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),I.clear(V)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",ze,!1),t.removeEventListener("webglcontextrestored",St,!1),t.removeEventListener("webglcontextcreationerror",ut,!1),fe.dispose(),re.dispose(),me.dispose(),b.dispose(),X.dispose(),ee.dispose(),he.dispose(),xe.dispose(),se.dispose(),Ae.dispose(),ue.dispose(),ue.removeEventListener("sessionstart",vg),ue.removeEventListener("sessionend",yg),Rs.stop()};function ze(M){M.preventDefault(),Qp("WebGLRenderer: Context Lost."),x=!0}function St(){Qp("WebGLRenderer: Context Restored."),x=!1;const M=A.autoReset,N=Pe.enabled,H=Pe.autoUpdate,V=Pe.needsUpdate,B=Pe.type;Q(),A.autoReset=M,Pe.enabled=N,Pe.autoUpdate=H,Pe.needsUpdate=V,Pe.type=B}function ut(M){st("WebGLRenderer: A WebGL context could not be created. Reason: ",M.statusMessage)}function hi(M){const N=M.target;N.removeEventListener("dispose",hi),Di(N)}function Di(M){TM(M),b.remove(M)}function TM(M){const N=b.get(M).programs;N!==void 0&&(N.forEach(function(H){Ae.releaseProgram(H)}),M.isShaderMaterial&&Ae.releaseShaderCache(M))}this.renderBufferDirect=function(M,N,H,V,B,ge){N===null&&(N=yt);const Te=B.isMesh&&B.matrixWorld.determinant()<0,be=EM(M,N,H,V,B);Re.setMaterial(V,Te);let Ee=H.index,Ie=1;if(V.wireframe===!0){if(Ee=ke.getWireframeAttribute(H),Ee===void 0)return;Ie=2}const Oe=H.drawRange,De=H.attributes.position;let Ye=Oe.start*Ie,mt=(Oe.start+Oe.count)*Ie;ge!==null&&(Ye=Math.max(Ye,ge.start*Ie),mt=Math.min(mt,(ge.start+ge.count)*Ie)),Ee!==null?(Ye=Math.max(Ye,0),mt=Math.min(mt,Ee.count)):De!=null&&(Ye=Math.max(Ye,0),mt=Math.min(mt,De.count));const Lt=mt-Ye;if(Lt<0||Lt===1/0)return;xe.setup(B,V,be,H,Ee);let Nt,bt=D;if(Ee!==null&&(Nt=j.get(Ee),bt=Se,bt.setIndex(Nt)),B.isMesh)V.wireframe===!0?(Re.setLineWidth(V.wireframeLinewidth*Vt()),bt.setMode(I.LINES)):bt.setMode(I.TRIANGLES);else if(B.isLine){let Le=V.linewidth;Le===void 0&&(Le=1),Re.setLineWidth(Le*Vt()),B.isLineSegments?bt.setMode(I.LINES):B.isLineLoop?bt.setMode(I.LINE_LOOP):bt.setMode(I.LINE_STRIP)}else B.isPoints?bt.setMode(I.POINTS):B.isSprite&&bt.setMode(I.TRIANGLES);if(B.isBatchedMesh)if(B._multiDrawInstances!==null)Zr("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),bt.renderMultiDrawInstances(B._multiDrawStarts,B._multiDrawCounts,B._multiDrawCount,B._multiDrawInstances);else if(ct.get("WEBGL_multi_draw"))bt.renderMultiDraw(B._multiDrawStarts,B._multiDrawCounts,B._multiDrawCount);else{const Le=B._multiDrawStarts,ht=B._multiDrawCounts,at=B._multiDrawCount,Pn=Ee?j.get(Ee).bytesPerElement:1,xr=b.get(V).currentProgram.getUniforms();for(let kn=0;kn<at;kn++)xr.setValue(I,"_gl_DrawID",kn),bt.render(Le[kn]/Pn,ht[kn])}else if(B.isInstancedMesh)bt.renderInstances(Ye,Lt,B.count);else if(H.isInstancedBufferGeometry){const Le=H._maxInstanceCount!==void 0?H._maxInstanceCount:1/0,ht=Math.min(H.instanceCount,Le);bt.renderInstances(Ye,Lt,ht)}else bt.render(Ye,Lt)};function gg(M,N,H){M.transparent===!0&&M.side===Si&&M.forceSinglePass===!1?(M.side=tn,M.needsUpdate=!0,Ko(M,N,H),M.side=_i,M.needsUpdate=!0,Ko(M,N,H),M.side=Si):Ko(M,N,H)}this.compile=function(M,N,H=null){H===null&&(H=M),S=me.get(H),S.init(N),w.push(S),H.traverseVisible(function(B){B.isLight&&B.layers.test(N.layers)&&(S.pushLight(B),B.castShadow&&S.pushShadow(B))}),M!==H&&M.traverseVisible(function(B){B.isLight&&B.layers.test(N.layers)&&(S.pushLight(B),B.castShadow&&S.pushShadow(B))}),S.setupLights();const V=new Set;return M.traverse(function(B){if(!(B.isMesh||B.isPoints||B.isLine||B.isSprite))return;const ge=B.material;if(ge)if(Array.isArray(ge))for(let Te=0;Te<ge.length;Te++){const be=ge[Te];gg(be,H,B),V.add(be)}else gg(ge,H,B),V.add(ge)}),S=w.pop(),V},this.compileAsync=function(M,N,H=null){const V=this.compile(M,N,H);return new Promise(B=>{function ge(){if(V.forEach(function(Te){b.get(Te).currentProgram.isReady()&&V.delete(Te)}),V.size===0){B(M);return}setTimeout(ge,10)}ct.get("KHR_parallel_shader_compile")!==null?ge():setTimeout(ge,10)})};let mu=null;function CM(M){mu&&mu(M)}function vg(){Rs.stop()}function yg(){Rs.start()}const Rs=new Um;Rs.setAnimationLoop(CM),typeof self<"u"&&Rs.setContext(self),this.setAnimationLoop=function(M){mu=M,ue.setAnimationLoop(M),M===null?Rs.stop():Rs.start()},ue.addEventListener("sessionstart",vg),ue.addEventListener("sessionend",yg),this.render=function(M,N){if(N!==void 0&&N.isCamera!==!0){st("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(x===!0)return;const H=ue.enabled===!0&&ue.isPresenting===!0,V=k!==null&&(F===null||H)&&k.begin(_,F);if(M.matrixWorldAutoUpdate===!0&&M.updateMatrixWorld(),N.parent===null&&N.matrixWorldAutoUpdate===!0&&N.updateMatrixWorld(),ue.enabled===!0&&ue.isPresenting===!0&&(k===null||k.isCompositing()===!1)&&(ue.cameraAutoUpdate===!0&&ue.updateCamera(N),N=ue.getCamera()),M.isScene===!0&&M.onBeforeRender(_,M,N,F),S=me.get(M,w.length),S.init(N),w.push(S),Yt.multiplyMatrices(N.projectionMatrix,N.matrixWorldInverse),qe.setFromProjectionMatrix(Yt,ai,N.reversedDepth),rt=this.localClippingEnabled,we=Me.init(this.clippingPlanes,rt),y=re.get(M,C.length),y.init(),C.push(y),ue.enabled===!0&&ue.isPresenting===!0){const Te=_.xr.getDepthSensingMesh();Te!==null&&gu(Te,N,-1/0,_.sortObjects)}gu(M,N,0,_.sortObjects),y.finish(),_.sortObjects===!0&&y.sort(Mt,pt),$e=ue.enabled===!1||ue.isPresenting===!1||ue.hasDepthSensing()===!1,$e&&fe.addToRenderList(y,M),this.info.render.frame++,we===!0&&Me.beginShadows();const B=S.state.shadowsArray;if(Pe.render(B,M,N),we===!0&&Me.endShadows(),this.info.autoReset===!0&&this.info.reset(),(V&&k.hasRenderPass())===!1){const Te=y.opaque,be=y.transmissive;if(S.setupLights(),N.isArrayCamera){const Ee=N.cameras;if(be.length>0)for(let Ie=0,Oe=Ee.length;Ie<Oe;Ie++){const De=Ee[Ie];_g(Te,be,M,De)}$e&&fe.render(M);for(let Ie=0,Oe=Ee.length;Ie<Oe;Ie++){const De=Ee[Ie];bg(y,M,De,De.viewport)}}else be.length>0&&_g(Te,be,M,N),$e&&fe.render(M),bg(y,M,N)}F!==null&&O===0&&(L.updateMultisampleRenderTarget(F),L.updateRenderTargetMipmap(F)),V&&k.end(_),M.isScene===!0&&M.onAfterRender(_,M,N),xe.resetDefaultState(),q=-1,K=null,w.pop(),w.length>0?(S=w[w.length-1],we===!0&&Me.setGlobalState(_.clippingPlanes,S.state.camera)):S=null,C.pop(),C.length>0?y=C[C.length-1]:y=null};function gu(M,N,H,V){if(M.visible===!1)return;if(M.layers.test(N.layers)){if(M.isGroup)H=M.renderOrder;else if(M.isLOD)M.autoUpdate===!0&&M.update(N);else if(M.isLight)S.pushLight(M),M.castShadow&&S.pushShadow(M);else if(M.isSprite){if(!M.frustumCulled||qe.intersectsSprite(M)){V&&dt.setFromMatrixPosition(M.matrixWorld).applyMatrix4(Yt);const Te=he.update(M),be=M.material;be.visible&&y.push(M,Te,be,H,dt.z,null)}}else if((M.isMesh||M.isLine||M.isPoints)&&(!M.frustumCulled||qe.intersectsObject(M))){const Te=he.update(M),be=M.material;if(V&&(M.boundingSphere!==void 0?(M.boundingSphere===null&&M.computeBoundingSphere(),dt.copy(M.boundingSphere.center)):(Te.boundingSphere===null&&Te.computeBoundingSphere(),dt.copy(Te.boundingSphere.center)),dt.applyMatrix4(M.matrixWorld).applyMatrix4(Yt)),Array.isArray(be)){const Ee=Te.groups;for(let Ie=0,Oe=Ee.length;Ie<Oe;Ie++){const De=Ee[Ie],Ye=be[De.materialIndex];Ye&&Ye.visible&&y.push(M,Te,Ye,H,dt.z,De)}}else be.visible&&y.push(M,Te,be,H,dt.z,null)}}const ge=M.children;for(let Te=0,be=ge.length;Te<be;Te++)gu(ge[Te],N,H,V)}function bg(M,N,H,V){const{opaque:B,transmissive:ge,transparent:Te}=M;S.setupLightsView(H),we===!0&&Me.setGlobalState(_.clippingPlanes,H),V&&Re.viewport(G.copy(V)),B.length>0&&Xo(B,N,H),ge.length>0&&Xo(ge,N,H),Te.length>0&&Xo(Te,N,H),Re.buffers.depth.setTest(!0),Re.buffers.depth.setMask(!0),Re.buffers.color.setMask(!0),Re.setPolygonOffset(!1)}function _g(M,N,H,V){if((H.isScene===!0?H.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[V.id]===void 0){const Ye=ct.has("EXT_color_buffer_half_float")||ct.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[V.id]=new oi(1,1,{generateMipmaps:!0,type:Ye?Ci:Mn,minFilter:ys,samples:_t.samples,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:nt.workingColorSpace})}const ge=S.state.transmissionRenderTarget[V.id],Te=V.viewport||G;ge.setSize(Te.z*_.transmissionResolutionScale,Te.w*_.transmissionResolutionScale);const be=_.getRenderTarget(),Ee=_.getActiveCubeFace(),Ie=_.getActiveMipmapLevel();_.setRenderTarget(ge),_.getClearColor(ye),de=_.getClearAlpha(),de<1&&_.setClearColor(16777215,.5),_.clear(),$e&&fe.render(H);const Oe=_.toneMapping;_.toneMapping=ii;const De=V.viewport;if(V.viewport!==void 0&&(V.viewport=void 0),S.setupLightsView(V),we===!0&&Me.setGlobalState(_.clippingPlanes,V),Xo(M,H,V),L.updateMultisampleRenderTarget(ge),L.updateRenderTargetMipmap(ge),ct.has("WEBGL_multisampled_render_to_texture")===!1){let Ye=!1;for(let mt=0,Lt=N.length;mt<Lt;mt++){const Nt=N[mt],{object:bt,geometry:Le,material:ht,group:at}=Nt;if(ht.side===Si&&bt.layers.test(V.layers)){const Pn=ht.side;ht.side=tn,ht.needsUpdate=!0,Sg(bt,H,V,Le,ht,at),ht.side=Pn,ht.needsUpdate=!0,Ye=!0}}Ye===!0&&(L.updateMultisampleRenderTarget(ge),L.updateRenderTargetMipmap(ge))}_.setRenderTarget(be,Ee,Ie),_.setClearColor(ye,de),De!==void 0&&(V.viewport=De),_.toneMapping=Oe}function Xo(M,N,H){const V=N.isScene===!0?N.overrideMaterial:null;for(let B=0,ge=M.length;B<ge;B++){const Te=M[B],{object:be,geometry:Ee,group:Ie}=Te;let Oe=Te.material;Oe.allowOverride===!0&&V!==null&&(Oe=V),be.layers.test(H.layers)&&Sg(be,N,H,Ee,Oe,Ie)}}function Sg(M,N,H,V,B,ge){M.onBeforeRender(_,N,H,V,B,ge),M.modelViewMatrix.multiplyMatrices(H.matrixWorldInverse,M.matrixWorld),M.normalMatrix.getNormalMatrix(M.modelViewMatrix),B.onBeforeRender(_,N,H,V,M,ge),B.transparent===!0&&B.side===Si&&B.forceSinglePass===!1?(B.side=tn,B.needsUpdate=!0,_.renderBufferDirect(H,N,V,B,M,ge),B.side=_i,B.needsUpdate=!0,_.renderBufferDirect(H,N,V,B,M,ge),B.side=Si):_.renderBufferDirect(H,N,V,B,M,ge),M.onAfterRender(_,N,H,V,B,ge)}function Ko(M,N,H){N.isScene!==!0&&(N=yt);const V=b.get(M),B=S.state.lights,ge=S.state.shadowsArray,Te=B.state.version,be=Ae.getParameters(M,B.state,ge,N,H),Ee=Ae.getProgramCacheKey(be);let Ie=V.programs;V.environment=M.isMeshStandardMaterial?N.environment:null,V.fog=N.fog,V.envMap=(M.isMeshStandardMaterial?ee:X).get(M.envMap||V.environment),V.envMapRotation=V.environment!==null&&M.envMap===null?N.environmentRotation:M.envMapRotation,Ie===void 0&&(M.addEventListener("dispose",hi),Ie=new Map,V.programs=Ie);let Oe=Ie.get(Ee);if(Oe!==void 0){if(V.currentProgram===Oe&&V.lightsStateVersion===Te)return Tg(M,be),Oe}else be.uniforms=Ae.getUniforms(M),M.onBeforeCompile(be,_),Oe=Ae.acquireProgram(be,Ee),Ie.set(Ee,Oe),V.uniforms=be.uniforms;const De=V.uniforms;return(!M.isShaderMaterial&&!M.isRawShaderMaterial||M.clipping===!0)&&(De.clippingPlanes=Me.uniform),Tg(M,be),V.needsLights=wM(M),V.lightsStateVersion=Te,V.needsLights&&(De.ambientLightColor.value=B.state.ambient,De.lightProbe.value=B.state.probe,De.directionalLights.value=B.state.directional,De.directionalLightShadows.value=B.state.directionalShadow,De.spotLights.value=B.state.spot,De.spotLightShadows.value=B.state.spotShadow,De.rectAreaLights.value=B.state.rectArea,De.ltc_1.value=B.state.rectAreaLTC1,De.ltc_2.value=B.state.rectAreaLTC2,De.pointLights.value=B.state.point,De.pointLightShadows.value=B.state.pointShadow,De.hemisphereLights.value=B.state.hemi,De.directionalShadowMap.value=B.state.directionalShadowMap,De.directionalShadowMatrix.value=B.state.directionalShadowMatrix,De.spotShadowMap.value=B.state.spotShadowMap,De.spotLightMatrix.value=B.state.spotLightMatrix,De.spotLightMap.value=B.state.spotLightMap,De.pointShadowMap.value=B.state.pointShadowMap,De.pointShadowMatrix.value=B.state.pointShadowMatrix),V.currentProgram=Oe,V.uniformsList=null,Oe}function xg(M){if(M.uniformsList===null){const N=M.currentProgram.getUniforms();M.uniformsList=qo.seqWithValue(N.seq,M.uniforms)}return M.uniformsList}function Tg(M,N){const H=b.get(M);H.outputColorSpace=N.outputColorSpace,H.batching=N.batching,H.batchingColor=N.batchingColor,H.instancing=N.instancing,H.instancingColor=N.instancingColor,H.instancingMorph=N.instancingMorph,H.skinning=N.skinning,H.morphTargets=N.morphTargets,H.morphNormals=N.morphNormals,H.morphColors=N.morphColors,H.morphTargetsCount=N.morphTargetsCount,H.numClippingPlanes=N.numClippingPlanes,H.numIntersection=N.numClipIntersection,H.vertexAlphas=N.vertexAlphas,H.vertexTangents=N.vertexTangents,H.toneMapping=N.toneMapping}function EM(M,N,H,V,B){N.isScene!==!0&&(N=yt),L.resetTextureUnits();const ge=N.fog,Te=V.isMeshStandardMaterial?N.environment:null,be=F===null?_.outputColorSpace:F.isXRRenderTarget===!0?F.texture.colorSpace:er,Ee=(V.isMeshStandardMaterial?ee:X).get(V.envMap||Te),Ie=V.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,Oe=!!H.attributes.tangent&&(!!V.normalMap||V.anisotropy>0),De=!!H.morphAttributes.position,Ye=!!H.morphAttributes.normal,mt=!!H.morphAttributes.color;let Lt=ii;V.toneMapped&&(F===null||F.isXRRenderTarget===!0)&&(Lt=_.toneMapping);const Nt=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,bt=Nt!==void 0?Nt.length:0,Le=b.get(V),ht=S.state.lights;if(we===!0&&(rt===!0||M!==K)){const pn=M===K&&V.id===q;Me.setState(V,M,pn)}let at=!1;V.version===Le.__version?(Le.needsLights&&Le.lightsStateVersion!==ht.state.version||Le.outputColorSpace!==be||B.isBatchedMesh&&Le.batching===!1||!B.isBatchedMesh&&Le.batching===!0||B.isBatchedMesh&&Le.batchingColor===!0&&B.colorTexture===null||B.isBatchedMesh&&Le.batchingColor===!1&&B.colorTexture!==null||B.isInstancedMesh&&Le.instancing===!1||!B.isInstancedMesh&&Le.instancing===!0||B.isSkinnedMesh&&Le.skinning===!1||!B.isSkinnedMesh&&Le.skinning===!0||B.isInstancedMesh&&Le.instancingColor===!0&&B.instanceColor===null||B.isInstancedMesh&&Le.instancingColor===!1&&B.instanceColor!==null||B.isInstancedMesh&&Le.instancingMorph===!0&&B.morphTexture===null||B.isInstancedMesh&&Le.instancingMorph===!1&&B.morphTexture!==null||Le.envMap!==Ee||V.fog===!0&&Le.fog!==ge||Le.numClippingPlanes!==void 0&&(Le.numClippingPlanes!==Me.numPlanes||Le.numIntersection!==Me.numIntersection)||Le.vertexAlphas!==Ie||Le.vertexTangents!==Oe||Le.morphTargets!==De||Le.morphNormals!==Ye||Le.morphColors!==mt||Le.toneMapping!==Lt||Le.morphTargetsCount!==bt)&&(at=!0):(at=!0,Le.__version=V.version);let Pn=Le.currentProgram;at===!0&&(Pn=Ko(V,N,B));let xr=!1,kn=!1,ma=!1;const xt=Pn.getUniforms(),Tn=Le.uniforms;if(Re.useProgram(Pn.program)&&(xr=!0,kn=!0,ma=!0),V.id!==q&&(q=V.id,kn=!0),xr||K!==M){Re.buffers.depth.getReversed()&&M.reversedDepth!==!0&&(M._reversedDepth=!0,M.updateProjectionMatrix()),xt.setValue(I,"projectionMatrix",M.projectionMatrix),xt.setValue(I,"viewMatrix",M.matrixWorldInverse);const Cn=xt.map.cameraPosition;Cn!==void 0&&Cn.setValue(I,it.setFromMatrixPosition(M.matrixWorld)),_t.logarithmicDepthBuffer&&xt.setValue(I,"logDepthBufFC",2/(Math.log(M.far+1)/Math.LN2)),(V.isMeshPhongMaterial||V.isMeshToonMaterial||V.isMeshLambertMaterial||V.isMeshBasicMaterial||V.isMeshStandardMaterial||V.isShaderMaterial)&&xt.setValue(I,"isOrthographic",M.isOrthographicCamera===!0),K!==M&&(K=M,kn=!0,ma=!0)}if(Le.needsLights&&(ht.state.directionalShadowMap.length>0&&xt.setValue(I,"directionalShadowMap",ht.state.directionalShadowMap,L),ht.state.spotShadowMap.length>0&&xt.setValue(I,"spotShadowMap",ht.state.spotShadowMap,L),ht.state.pointShadowMap.length>0&&xt.setValue(I,"pointShadowMap",ht.state.pointShadowMap,L)),B.isSkinnedMesh){xt.setOptional(I,B,"bindMatrix"),xt.setOptional(I,B,"bindMatrixInverse");const pn=B.skeleton;pn&&(pn.boneTexture===null&&pn.computeBoneTexture(),xt.setValue(I,"boneTexture",pn.boneTexture,L))}B.isBatchedMesh&&(xt.setOptional(I,B,"batchingTexture"),xt.setValue(I,"batchingTexture",B._matricesTexture,L),xt.setOptional(I,B,"batchingIdTexture"),xt.setValue(I,"batchingIdTexture",B._indirectTexture,L),xt.setOptional(I,B,"batchingColorTexture"),B._colorsTexture!==null&&xt.setValue(I,"batchingColorTexture",B._colorsTexture,L));const Un=H.morphAttributes;if((Un.position!==void 0||Un.normal!==void 0||Un.color!==void 0)&&Xe.update(B,H,Pn),(kn||Le.receiveShadow!==B.receiveShadow)&&(Le.receiveShadow=B.receiveShadow,xt.setValue(I,"receiveShadow",B.receiveShadow)),V.isMeshGouraudMaterial&&V.envMap!==null&&(Tn.envMap.value=Ee,Tn.flipEnvMap.value=Ee.isCubeTexture&&Ee.isRenderTargetTexture===!1?-1:1),V.isMeshStandardMaterial&&V.envMap===null&&N.environment!==null&&(Tn.envMapIntensity.value=N.environmentIntensity),Tn.dfgLUT!==void 0&&(Tn.dfgLUT.value=nM()),kn&&(xt.setValue(I,"toneMappingExposure",_.toneMappingExposure),Le.needsLights&&MM(Tn,ma),ge&&V.fog===!0&&Ue.refreshFogUniforms(Tn,ge),Ue.refreshMaterialUniforms(Tn,V,Ve,Ge,S.state.transmissionRenderTarget[M.id]),qo.upload(I,xg(Le),Tn,L)),V.isShaderMaterial&&V.uniformsNeedUpdate===!0&&(qo.upload(I,xg(Le),Tn,L),V.uniformsNeedUpdate=!1),V.isSpriteMaterial&&xt.setValue(I,"center",B.center),xt.setValue(I,"modelViewMatrix",B.modelViewMatrix),xt.setValue(I,"normalMatrix",B.normalMatrix),xt.setValue(I,"modelMatrix",B.matrixWorld),V.isShaderMaterial||V.isRawShaderMaterial){const pn=V.uniformsGroups;for(let Cn=0,vu=pn.length;Cn<vu;Cn++){const Ps=pn[Cn];se.update(Ps,Pn),se.bind(Ps,Pn)}}return Pn}function MM(M,N){M.ambientLightColor.needsUpdate=N,M.lightProbe.needsUpdate=N,M.directionalLights.needsUpdate=N,M.directionalLightShadows.needsUpdate=N,M.pointLights.needsUpdate=N,M.pointLightShadows.needsUpdate=N,M.spotLights.needsUpdate=N,M.spotLightShadows.needsUpdate=N,M.rectAreaLights.needsUpdate=N,M.hemisphereLights.needsUpdate=N}function wM(M){return M.isMeshLambertMaterial||M.isMeshToonMaterial||M.isMeshPhongMaterial||M.isMeshStandardMaterial||M.isShadowMaterial||M.isShaderMaterial&&M.lights===!0}this.getActiveCubeFace=function(){return R},this.getActiveMipmapLevel=function(){return O},this.getRenderTarget=function(){return F},this.setRenderTargetTextures=function(M,N,H){const V=b.get(M);V.__autoAllocateDepthBuffer=M.resolveDepthBuffer===!1,V.__autoAllocateDepthBuffer===!1&&(V.__useRenderToTexture=!1),b.get(M.texture).__webglTexture=N,b.get(M.depthTexture).__webglTexture=V.__autoAllocateDepthBuffer?void 0:H,V.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(M,N){const H=b.get(M);H.__webglFramebuffer=N,H.__useDefaultFramebuffer=N===void 0};const AM=I.createFramebuffer();this.setRenderTarget=function(M,N=0,H=0){F=M,R=N,O=H;let V=null,B=!1,ge=!1;if(M){const be=b.get(M);if(be.__useDefaultFramebuffer!==void 0){Re.bindFramebuffer(I.FRAMEBUFFER,be.__webglFramebuffer),G.copy(M.viewport),W.copy(M.scissor),te=M.scissorTest,Re.viewport(G),Re.scissor(W),Re.setScissorTest(te),q=-1;return}else if(be.__webglFramebuffer===void 0)L.setupRenderTarget(M);else if(be.__hasExternalTextures)L.rebindTextures(M,b.get(M.texture).__webglTexture,b.get(M.depthTexture).__webglTexture);else if(M.depthBuffer){const Oe=M.depthTexture;if(be.__boundDepthTexture!==Oe){if(Oe!==null&&b.has(Oe)&&(M.width!==Oe.image.width||M.height!==Oe.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");L.setupDepthRenderbuffer(M)}}const Ee=M.texture;(Ee.isData3DTexture||Ee.isDataArrayTexture||Ee.isCompressedArrayTexture)&&(ge=!0);const Ie=b.get(M).__webglFramebuffer;M.isWebGLCubeRenderTarget?(Array.isArray(Ie[N])?V=Ie[N][H]:V=Ie[N],B=!0):M.samples>0&&L.useMultisampledRTT(M)===!1?V=b.get(M).__webglMultisampledFramebuffer:Array.isArray(Ie)?V=Ie[H]:V=Ie,G.copy(M.viewport),W.copy(M.scissor),te=M.scissorTest}else G.copy(Y).multiplyScalar(Ve).floor(),W.copy(ie).multiplyScalar(Ve).floor(),te=Ce;if(H!==0&&(V=AM),Re.bindFramebuffer(I.FRAMEBUFFER,V)&&Re.drawBuffers(M,V),Re.viewport(G),Re.scissor(W),Re.setScissorTest(te),B){const be=b.get(M.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_CUBE_MAP_POSITIVE_X+N,be.__webglTexture,H)}else if(ge){const be=N;for(let Ee=0;Ee<M.textures.length;Ee++){const Ie=b.get(M.textures[Ee]);I.framebufferTextureLayer(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0+Ee,Ie.__webglTexture,H,be)}}else if(M!==null&&H!==0){const be=b.get(M.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,be.__webglTexture,H)}q=-1},this.readRenderTargetPixels=function(M,N,H,V,B,ge,Te,be=0){if(!(M&&M.isWebGLRenderTarget)){st("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ee=b.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);try{const Ie=M.textures[be],Oe=Ie.format,De=Ie.type;if(!_t.textureFormatReadable(Oe)){st("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!_t.textureTypeReadable(De)){st("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}N>=0&&N<=M.width-V&&H>=0&&H<=M.height-B&&(M.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+be),I.readPixels(N,H,V,B,oe.convert(Oe),oe.convert(De),ge))}finally{const Ie=F!==null?b.get(F).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,Ie)}}},this.readRenderTargetPixelsAsync=async function(M,N,H,V,B,ge,Te,be=0){if(!(M&&M.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ee=b.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee)if(N>=0&&N<=M.width-V&&H>=0&&H<=M.height-B){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);const Ie=M.textures[be],Oe=Ie.format,De=Ie.type;if(!_t.textureFormatReadable(Oe))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!_t.textureTypeReadable(De))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Ye=I.createBuffer();I.bindBuffer(I.PIXEL_PACK_BUFFER,Ye),I.bufferData(I.PIXEL_PACK_BUFFER,ge.byteLength,I.STREAM_READ),M.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+be),I.readPixels(N,H,V,B,oe.convert(Oe),oe.convert(De),0);const mt=F!==null?b.get(F).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,mt);const Lt=I.fenceSync(I.SYNC_GPU_COMMANDS_COMPLETE,0);return I.flush(),await eS(I,Lt,4),I.bindBuffer(I.PIXEL_PACK_BUFFER,Ye),I.getBufferSubData(I.PIXEL_PACK_BUFFER,0,ge),I.deleteBuffer(Ye),I.deleteSync(Lt),ge}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(M,N=null,H=0){const V=Math.pow(2,-H),B=Math.floor(M.image.width*V),ge=Math.floor(M.image.height*V),Te=N!==null?N.x:0,be=N!==null?N.y:0;L.setTexture2D(M,0),I.copyTexSubImage2D(I.TEXTURE_2D,H,0,0,Te,be,B,ge),Re.unbindTexture()};const RM=I.createFramebuffer(),PM=I.createFramebuffer();this.copyTextureToTexture=function(M,N,H=null,V=null,B=0,ge=null){ge===null&&(B!==0?(Zr("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),ge=B,B=0):ge=0);let Te,be,Ee,Ie,Oe,De,Ye,mt,Lt;const Nt=M.isCompressedTexture?M.mipmaps[ge]:M.image;if(H!==null)Te=H.max.x-H.min.x,be=H.max.y-H.min.y,Ee=H.isBox3?H.max.z-H.min.z:1,Ie=H.min.x,Oe=H.min.y,De=H.isBox3?H.min.z:0;else{const Un=Math.pow(2,-B);Te=Math.floor(Nt.width*Un),be=Math.floor(Nt.height*Un),M.isDataArrayTexture?Ee=Nt.depth:M.isData3DTexture?Ee=Math.floor(Nt.depth*Un):Ee=1,Ie=0,Oe=0,De=0}V!==null?(Ye=V.x,mt=V.y,Lt=V.z):(Ye=0,mt=0,Lt=0);const bt=oe.convert(N.format),Le=oe.convert(N.type);let ht;N.isData3DTexture?(L.setTexture3D(N,0),ht=I.TEXTURE_3D):N.isDataArrayTexture||N.isCompressedArrayTexture?(L.setTexture2DArray(N,0),ht=I.TEXTURE_2D_ARRAY):(L.setTexture2D(N,0),ht=I.TEXTURE_2D),I.pixelStorei(I.UNPACK_FLIP_Y_WEBGL,N.flipY),I.pixelStorei(I.UNPACK_PREMULTIPLY_ALPHA_WEBGL,N.premultiplyAlpha),I.pixelStorei(I.UNPACK_ALIGNMENT,N.unpackAlignment);const at=I.getParameter(I.UNPACK_ROW_LENGTH),Pn=I.getParameter(I.UNPACK_IMAGE_HEIGHT),xr=I.getParameter(I.UNPACK_SKIP_PIXELS),kn=I.getParameter(I.UNPACK_SKIP_ROWS),ma=I.getParameter(I.UNPACK_SKIP_IMAGES);I.pixelStorei(I.UNPACK_ROW_LENGTH,Nt.width),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Nt.height),I.pixelStorei(I.UNPACK_SKIP_PIXELS,Ie),I.pixelStorei(I.UNPACK_SKIP_ROWS,Oe),I.pixelStorei(I.UNPACK_SKIP_IMAGES,De);const xt=M.isDataArrayTexture||M.isData3DTexture,Tn=N.isDataArrayTexture||N.isData3DTexture;if(M.isDepthTexture){const Un=b.get(M),pn=b.get(N),Cn=b.get(Un.__renderTarget),vu=b.get(pn.__renderTarget);Re.bindFramebuffer(I.READ_FRAMEBUFFER,Cn.__webglFramebuffer),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,vu.__webglFramebuffer);for(let Ps=0;Ps<Ee;Ps++)xt&&(I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,b.get(M).__webglTexture,B,De+Ps),I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,b.get(N).__webglTexture,ge,Lt+Ps)),I.blitFramebuffer(Ie,Oe,Te,be,Ye,mt,Te,be,I.DEPTH_BUFFER_BIT,I.NEAREST);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else if(B!==0||M.isRenderTargetTexture||b.has(M)){const Un=b.get(M),pn=b.get(N);Re.bindFramebuffer(I.READ_FRAMEBUFFER,RM),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,PM);for(let Cn=0;Cn<Ee;Cn++)xt?I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,Un.__webglTexture,B,De+Cn):I.framebufferTexture2D(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,Un.__webglTexture,B),Tn?I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,pn.__webglTexture,ge,Lt+Cn):I.framebufferTexture2D(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,pn.__webglTexture,ge),B!==0?I.blitFramebuffer(Ie,Oe,Te,be,Ye,mt,Te,be,I.COLOR_BUFFER_BIT,I.NEAREST):Tn?I.copyTexSubImage3D(ht,ge,Ye,mt,Lt+Cn,Ie,Oe,Te,be):I.copyTexSubImage2D(ht,ge,Ye,mt,Ie,Oe,Te,be);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else Tn?M.isDataTexture||M.isData3DTexture?I.texSubImage3D(ht,ge,Ye,mt,Lt,Te,be,Ee,bt,Le,Nt.data):N.isCompressedArrayTexture?I.compressedTexSubImage3D(ht,ge,Ye,mt,Lt,Te,be,Ee,bt,Nt.data):I.texSubImage3D(ht,ge,Ye,mt,Lt,Te,be,Ee,bt,Le,Nt):M.isDataTexture?I.texSubImage2D(I.TEXTURE_2D,ge,Ye,mt,Te,be,bt,Le,Nt.data):M.isCompressedTexture?I.compressedTexSubImage2D(I.TEXTURE_2D,ge,Ye,mt,Nt.width,Nt.height,bt,Nt.data):I.texSubImage2D(I.TEXTURE_2D,ge,Ye,mt,Te,be,bt,Le,Nt);I.pixelStorei(I.UNPACK_ROW_LENGTH,at),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Pn),I.pixelStorei(I.UNPACK_SKIP_PIXELS,xr),I.pixelStorei(I.UNPACK_SKIP_ROWS,kn),I.pixelStorei(I.UNPACK_SKIP_IMAGES,ma),ge===0&&N.generateMipmaps&&I.generateMipmap(ht),Re.unbindTexture()},this.initRenderTarget=function(M){b.get(M).__webglFramebuffer===void 0&&L.setupRenderTarget(M)},this.initTexture=function(M){M.isCubeTexture?L.setTextureCube(M,0):M.isData3DTexture?L.setTexture3D(M,0):M.isDataArrayTexture||M.isCompressedArrayTexture?L.setTexture2DArray(M,0):L.setTexture2D(M,0),Re.unbindTexture()},this.resetState=function(){R=0,O=0,F=null,Re.reset(),xe.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ai}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=nt._getDrawingBufferColorSpace(e),t.unpackColorSpace=nt._getUnpackColorSpace()}}const iM=`
4102
+ }`;class YE{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new km(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new tn({vertexShader:XE,fragmentShader:KE,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new xn(new Vo(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class JE extends nr{constructor(e,t){super();const n=this;let s=null,r=1,o=null,a="local-floor",c=1,l=null,d=null,u=null,h=null,f=null,g=null;const v=typeof XRWebGLBinding<"u",m=new YE,p={},T=t.getContextAttributes();let E=null,y=null;const S=[],C=[],w=new tt;let k=null;const _=new Tn;_.viewport=new Dt;const x=new Tn;x.viewport=new Dt;const R=[_,x],O=new VS;let F=null,q=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Y){let ie=S[Y];return ie===void 0&&(ie=new $d,S[Y]=ie),ie.getTargetRaySpace()},this.getControllerGrip=function(Y){let ie=S[Y];return ie===void 0&&(ie=new $d,S[Y]=ie),ie.getGripSpace()},this.getHand=function(Y){let ie=S[Y];return ie===void 0&&(ie=new $d,S[Y]=ie),ie.getHandSpace()};function K(Y){const ie=C.indexOf(Y.inputSource);if(ie===-1)return;const Ce=S[ie];Ce!==void 0&&(Ce.update(Y.inputSource,Y.frame,l||o),Ce.dispatchEvent({type:Y.type,data:Y.inputSource}))}function G(){s.removeEventListener("select",K),s.removeEventListener("selectstart",K),s.removeEventListener("selectend",K),s.removeEventListener("squeeze",K),s.removeEventListener("squeezestart",K),s.removeEventListener("squeezeend",K),s.removeEventListener("end",G),s.removeEventListener("inputsourceschange",W);for(let Y=0;Y<S.length;Y++){const ie=C[Y];ie!==null&&(C[Y]=null,S[Y].disconnect(ie))}F=null,q=null,m.reset();for(const Y in p)delete p[Y];e.setRenderTarget(E),f=null,h=null,u=null,s=null,y=null,pt.stop(),n.isPresenting=!1,e.setPixelRatio(k),e.setSize(w.width,w.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Y){r=Y,n.isPresenting===!0&&Be("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Y){a=Y,n.isPresenting===!0&&Be("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||o},this.setReferenceSpace=function(Y){l=Y},this.getBaseLayer=function(){return h!==null?h:f},this.getBinding=function(){return u===null&&v&&(u=new XRWebGLBinding(s,t)),u},this.getFrame=function(){return g},this.getSession=function(){return s},this.setSession=async function(Y){if(s=Y,s!==null){if(E=e.getRenderTarget(),s.addEventListener("select",K),s.addEventListener("selectstart",K),s.addEventListener("selectend",K),s.addEventListener("squeeze",K),s.addEventListener("squeezestart",K),s.addEventListener("squeezeend",K),s.addEventListener("end",G),s.addEventListener("inputsourceschange",W),T.xrCompatible!==!0&&await t.makeXRCompatible(),k=e.getPixelRatio(),e.getSize(w),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let Ce=null,qe=null,we=null;T.depth&&(we=T.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,Ce=T.stencil?bs:Ei,qe=T.stencil?Jr:si);const rt={colorFormat:t.RGBA8,depthFormat:we,scaleFactor:r};u=this.getBinding(),h=u.createProjectionLayer(rt),s.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),y=new oi(h.textureWidth,h.textureHeight,{format:qn,type:wn,depthTexture:new da(h.textureWidth,h.textureHeight,qe,void 0,void 0,void 0,void 0,void 0,void 0,Ce),stencilBuffer:T.stencil,colorSpace:e.outputColorSpace,samples:T.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1})}else{const Ce={antialias:T.antialias,alpha:!0,depth:T.depth,stencil:T.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(s,t,Ce),s.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new oi(f.framebufferWidth,f.framebufferHeight,{format:qn,type:wn,colorSpace:e.outputColorSpace,stencilBuffer:T.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(c),l=null,o=await s.requestReferenceSpace(a),pt.setContext(s),pt.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function W(Y){for(let ie=0;ie<Y.removed.length;ie++){const Ce=Y.removed[ie],qe=C.indexOf(Ce);qe>=0&&(C[qe]=null,S[qe].disconnect(Ce))}for(let ie=0;ie<Y.added.length;ie++){const Ce=Y.added[ie];let qe=C.indexOf(Ce);if(qe===-1){for(let rt=0;rt<S.length;rt++)if(rt>=C.length){C.push(Ce),qe=rt;break}else if(C[rt]===null){C[rt]=Ce,qe=rt;break}if(qe===-1)break}const we=S[qe];we&&we.connect(Ce)}}const te=new U,ye=new U;function ue(Y,ie,Ce){te.setFromMatrixPosition(ie.matrixWorld),ye.setFromMatrixPosition(Ce.matrixWorld);const qe=te.distanceTo(ye),we=ie.projectionMatrix.elements,rt=Ce.projectionMatrix.elements,Jt=we[14]/(we[10]-1),it=we[14]/(we[10]+1),dt=(we[9]+1)/we[5],yt=(we[9]-1)/we[5],$e=(we[8]-1)/we[0],Vt=(rt[8]+1)/rt[0],I=Jt*$e,Gt=Jt*Vt,ct=qe/(-$e+Vt),_t=ct*-$e;if(ie.matrixWorld.decompose(Y.position,Y.quaternion,Y.scale),Y.translateX(_t),Y.translateZ(ct),Y.matrixWorld.compose(Y.position,Y.quaternion,Y.scale),Y.matrixWorldInverse.copy(Y.matrixWorld).invert(),we[10]===-1)Y.projectionMatrix.copy(ie.projectionMatrix),Y.projectionMatrixInverse.copy(ie.projectionMatrixInverse);else{const Re=Jt+ct,A=it+ct,b=I-_t,L=Gt+(qe-_t),X=dt*it/A*Re,ee=yt*it/A*Re;Y.projectionMatrix.makePerspective(b,L,X,ee,Re,A),Y.projectionMatrixInverse.copy(Y.projectionMatrix).invert()}}function _e(Y,ie){ie===null?Y.matrixWorld.copy(Y.matrix):Y.matrixWorld.multiplyMatrices(ie.matrixWorld,Y.matrix),Y.matrixWorldInverse.copy(Y.matrixWorld).invert()}this.updateCamera=function(Y){if(s===null)return;let ie=Y.near,Ce=Y.far;m.texture!==null&&(m.depthNear>0&&(ie=m.depthNear),m.depthFar>0&&(Ce=m.depthFar)),O.near=x.near=_.near=ie,O.far=x.far=_.far=Ce,(F!==O.near||q!==O.far)&&(s.updateRenderState({depthNear:O.near,depthFar:O.far}),F=O.near,q=O.far),O.layers.mask=Y.layers.mask|6,_.layers.mask=O.layers.mask&3,x.layers.mask=O.layers.mask&5;const qe=Y.parent,we=O.cameras;_e(O,qe);for(let rt=0;rt<we.length;rt++)_e(we[rt],qe);we.length===2?ue(O,_,x):O.projectionMatrix.copy(_.projectionMatrix),Ge(Y,O,qe)};function Ge(Y,ie,Ce){Ce===null?Y.matrix.copy(ie.matrixWorld):(Y.matrix.copy(Ce.matrixWorld),Y.matrix.invert(),Y.matrix.multiply(ie.matrixWorld)),Y.matrix.decompose(Y.position,Y.quaternion,Y.scale),Y.updateMatrixWorld(!0),Y.projectionMatrix.copy(ie.projectionMatrix),Y.projectionMatrixInverse.copy(ie.projectionMatrixInverse),Y.isPerspectiveCamera&&(Y.fov=Td*2*Math.atan(1/Y.projectionMatrix.elements[5]),Y.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(!(h===null&&f===null))return c},this.setFoveation=function(Y){c=Y,h!==null&&(h.fixedFoveation=Y),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=Y)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(O)},this.getCameraTexture=function(Y){return p[Y]};let Ve=null;function Mt(Y,ie){if(d=ie.getViewerPose(l||o),g=ie,d!==null){const Ce=d.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let qe=!1;Ce.length!==O.cameras.length&&(O.cameras.length=0,qe=!0);for(let it=0;it<Ce.length;it++){const dt=Ce[it];let yt=null;if(f!==null)yt=f.getViewport(dt);else{const Vt=u.getViewSubImage(h,dt);yt=Vt.viewport,it===0&&(e.setRenderTargetTextures(y,Vt.colorTexture,Vt.depthStencilTexture),e.setRenderTarget(y))}let $e=R[it];$e===void 0&&($e=new Tn,$e.layers.enable(it),$e.viewport=new Dt,R[it]=$e),$e.matrix.fromArray(dt.transform.matrix),$e.matrix.decompose($e.position,$e.quaternion,$e.scale),$e.projectionMatrix.fromArray(dt.projectionMatrix),$e.projectionMatrixInverse.copy($e.projectionMatrix).invert(),$e.viewport.set(yt.x,yt.y,yt.width,yt.height),it===0&&(O.matrix.copy($e.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),qe===!0&&O.cameras.push($e)}const we=s.enabledFeatures;if(we&&we.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&v){u=n.getBinding();const it=u.getDepthInformation(Ce[0]);it&&it.isValid&&it.texture&&m.init(it,s.renderState)}if(we&&we.includes("camera-access")&&v){e.state.unbindTexture(),u=n.getBinding();for(let it=0;it<Ce.length;it++){const dt=Ce[it].camera;if(dt){let yt=p[dt];yt||(yt=new km,p[dt]=yt);const $e=u.getCameraImage(dt);yt.sourceTexture=$e}}}}for(let Ce=0;Ce<S.length;Ce++){const qe=C[Ce],we=S[Ce];qe!==null&&we!==void 0&&we.update(qe,ie,l||o)}Ve&&Ve(Y,ie),ie.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:ie}),g=null}const pt=new Um;pt.setAnimationLoop(Mt),this.setAnimationLoop=function(Y){Ve=Y},this.dispose=function(){}}}const ws=new Ri,ZE=new At;function QE(i,e){function t(m,p){m.matrixAutoUpdate===!0&&m.updateMatrix(),p.value.copy(m.matrix)}function n(m,p){p.color.getRGB(m.fogColor.value,_m(i)),p.isFog?(m.fogNear.value=p.near,m.fogFar.value=p.far):p.isFogExp2&&(m.fogDensity.value=p.density)}function s(m,p,T,E,y){p.isMeshBasicMaterial||p.isMeshLambertMaterial?r(m,p):p.isMeshToonMaterial?(r(m,p),u(m,p)):p.isMeshPhongMaterial?(r(m,p),d(m,p)):p.isMeshStandardMaterial?(r(m,p),h(m,p),p.isMeshPhysicalMaterial&&f(m,p,y)):p.isMeshMatcapMaterial?(r(m,p),g(m,p)):p.isMeshDepthMaterial?r(m,p):p.isMeshDistanceMaterial?(r(m,p),v(m,p)):p.isMeshNormalMaterial?r(m,p):p.isLineBasicMaterial?(o(m,p),p.isLineDashedMaterial&&a(m,p)):p.isPointsMaterial?c(m,p,T,E):p.isSpriteMaterial?l(m,p):p.isShadowMaterial?(m.color.value.copy(p.color),m.opacity.value=p.opacity):p.isShaderMaterial&&(p.uniformsNeedUpdate=!1)}function r(m,p){m.opacity.value=p.opacity,p.color&&m.diffuse.value.copy(p.color),p.emissive&&m.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity),p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.bumpMap&&(m.bumpMap.value=p.bumpMap,t(p.bumpMap,m.bumpMapTransform),m.bumpScale.value=p.bumpScale,p.side===nn&&(m.bumpScale.value*=-1)),p.normalMap&&(m.normalMap.value=p.normalMap,t(p.normalMap,m.normalMapTransform),m.normalScale.value.copy(p.normalScale),p.side===nn&&m.normalScale.value.negate()),p.displacementMap&&(m.displacementMap.value=p.displacementMap,t(p.displacementMap,m.displacementMapTransform),m.displacementScale.value=p.displacementScale,m.displacementBias.value=p.displacementBias),p.emissiveMap&&(m.emissiveMap.value=p.emissiveMap,t(p.emissiveMap,m.emissiveMapTransform)),p.specularMap&&(m.specularMap.value=p.specularMap,t(p.specularMap,m.specularMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest);const T=e.get(p),E=T.envMap,y=T.envMapRotation;E&&(m.envMap.value=E,ws.copy(y),ws.x*=-1,ws.y*=-1,ws.z*=-1,E.isCubeTexture&&E.isRenderTargetTexture===!1&&(ws.y*=-1,ws.z*=-1),m.envMapRotation.value.setFromMatrix4(ZE.makeRotationFromEuler(ws)),m.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=p.reflectivity,m.ior.value=p.ior,m.refractionRatio.value=p.refractionRatio),p.lightMap&&(m.lightMap.value=p.lightMap,m.lightMapIntensity.value=p.lightMapIntensity,t(p.lightMap,m.lightMapTransform)),p.aoMap&&(m.aoMap.value=p.aoMap,m.aoMapIntensity.value=p.aoMapIntensity,t(p.aoMap,m.aoMapTransform))}function o(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform))}function a(m,p){m.dashSize.value=p.dashSize,m.totalSize.value=p.dashSize+p.gapSize,m.scale.value=p.scale}function c(m,p,T,E){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.size.value=p.size*T,m.scale.value=E*.5,p.map&&(m.map.value=p.map,t(p.map,m.uvTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function l(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.rotation.value=p.rotation,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function d(m,p){m.specular.value.copy(p.specular),m.shininess.value=Math.max(p.shininess,1e-4)}function u(m,p){p.gradientMap&&(m.gradientMap.value=p.gradientMap)}function h(m,p){m.metalness.value=p.metalness,p.metalnessMap&&(m.metalnessMap.value=p.metalnessMap,t(p.metalnessMap,m.metalnessMapTransform)),m.roughness.value=p.roughness,p.roughnessMap&&(m.roughnessMap.value=p.roughnessMap,t(p.roughnessMap,m.roughnessMapTransform)),p.envMap&&(m.envMapIntensity.value=p.envMapIntensity)}function f(m,p,T){m.ior.value=p.ior,p.sheen>0&&(m.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen),m.sheenRoughness.value=p.sheenRoughness,p.sheenColorMap&&(m.sheenColorMap.value=p.sheenColorMap,t(p.sheenColorMap,m.sheenColorMapTransform)),p.sheenRoughnessMap&&(m.sheenRoughnessMap.value=p.sheenRoughnessMap,t(p.sheenRoughnessMap,m.sheenRoughnessMapTransform))),p.clearcoat>0&&(m.clearcoat.value=p.clearcoat,m.clearcoatRoughness.value=p.clearcoatRoughness,p.clearcoatMap&&(m.clearcoatMap.value=p.clearcoatMap,t(p.clearcoatMap,m.clearcoatMapTransform)),p.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=p.clearcoatRoughnessMap,t(p.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),p.clearcoatNormalMap&&(m.clearcoatNormalMap.value=p.clearcoatNormalMap,t(p.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(p.clearcoatNormalScale),p.side===nn&&m.clearcoatNormalScale.value.negate())),p.dispersion>0&&(m.dispersion.value=p.dispersion),p.iridescence>0&&(m.iridescence.value=p.iridescence,m.iridescenceIOR.value=p.iridescenceIOR,m.iridescenceThicknessMinimum.value=p.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=p.iridescenceThicknessRange[1],p.iridescenceMap&&(m.iridescenceMap.value=p.iridescenceMap,t(p.iridescenceMap,m.iridescenceMapTransform)),p.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=p.iridescenceThicknessMap,t(p.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),p.transmission>0&&(m.transmission.value=p.transmission,m.transmissionSamplerMap.value=T.texture,m.transmissionSamplerSize.value.set(T.width,T.height),p.transmissionMap&&(m.transmissionMap.value=p.transmissionMap,t(p.transmissionMap,m.transmissionMapTransform)),m.thickness.value=p.thickness,p.thicknessMap&&(m.thicknessMap.value=p.thicknessMap,t(p.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=p.attenuationDistance,m.attenuationColor.value.copy(p.attenuationColor)),p.anisotropy>0&&(m.anisotropyVector.value.set(p.anisotropy*Math.cos(p.anisotropyRotation),p.anisotropy*Math.sin(p.anisotropyRotation)),p.anisotropyMap&&(m.anisotropyMap.value=p.anisotropyMap,t(p.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=p.specularIntensity,m.specularColor.value.copy(p.specularColor),p.specularColorMap&&(m.specularColorMap.value=p.specularColorMap,t(p.specularColorMap,m.specularColorMapTransform)),p.specularIntensityMap&&(m.specularIntensityMap.value=p.specularIntensityMap,t(p.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,p){p.matcap&&(m.matcap.value=p.matcap)}function v(m,p){const T=e.get(p).light;m.referencePosition.value.setFromMatrixPosition(T.matrixWorld),m.nearDistance.value=T.shadow.camera.near,m.farDistance.value=T.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function eM(i,e,t,n){let s={},r={},o=[];const a=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(T,E){const y=E.program;n.uniformBlockBinding(T,y)}function l(T,E){let y=s[T.id];y===void 0&&(g(T),y=d(T),s[T.id]=y,T.addEventListener("dispose",m));const S=E.program;n.updateUBOMapping(T,S);const C=e.render.frame;r[T.id]!==C&&(h(T),r[T.id]=C)}function d(T){const E=u();T.__bindingPointIndex=E;const y=i.createBuffer(),S=T.__size,C=T.usage;return i.bindBuffer(i.UNIFORM_BUFFER,y),i.bufferData(i.UNIFORM_BUFFER,S,C),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,E,y),y}function u(){for(let T=0;T<a;T++)if(o.indexOf(T)===-1)return o.push(T),T;return st("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(T){const E=s[T.id],y=T.uniforms,S=T.__cache;i.bindBuffer(i.UNIFORM_BUFFER,E);for(let C=0,w=y.length;C<w;C++){const k=Array.isArray(y[C])?y[C]:[y[C]];for(let _=0,x=k.length;_<x;_++){const R=k[_];if(f(R,C,_,S)===!0){const O=R.__offset,F=Array.isArray(R.value)?R.value:[R.value];let q=0;for(let K=0;K<F.length;K++){const G=F[K],W=v(G);typeof G=="number"||typeof G=="boolean"?(R.__data[0]=G,i.bufferSubData(i.UNIFORM_BUFFER,O+q,R.__data)):G.isMatrix3?(R.__data[0]=G.elements[0],R.__data[1]=G.elements[1],R.__data[2]=G.elements[2],R.__data[3]=0,R.__data[4]=G.elements[3],R.__data[5]=G.elements[4],R.__data[6]=G.elements[5],R.__data[7]=0,R.__data[8]=G.elements[6],R.__data[9]=G.elements[7],R.__data[10]=G.elements[8],R.__data[11]=0):(G.toArray(R.__data,q),q+=W.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,O,R.__data)}}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function f(T,E,y,S){const C=T.value,w=E+"_"+y;if(S[w]===void 0)return typeof C=="number"||typeof C=="boolean"?S[w]=C:S[w]=C.clone(),!0;{const k=S[w];if(typeof C=="number"||typeof C=="boolean"){if(k!==C)return S[w]=C,!0}else if(k.equals(C)===!1)return k.copy(C),!0}return!1}function g(T){const E=T.uniforms;let y=0;const S=16;for(let w=0,k=E.length;w<k;w++){const _=Array.isArray(E[w])?E[w]:[E[w]];for(let x=0,R=_.length;x<R;x++){const O=_[x],F=Array.isArray(O.value)?O.value:[O.value];for(let q=0,K=F.length;q<K;q++){const G=F[q],W=v(G),te=y%S,ye=te%W.boundary,ue=te+ye;y+=ye,ue!==0&&S-ue<W.storage&&(y+=S-ue),O.__data=new Float32Array(W.storage/Float32Array.BYTES_PER_ELEMENT),O.__offset=y,y+=W.storage}}}const C=y%S;return C>0&&(y+=S-C),T.__size=y,T.__cache={},this}function v(T){const E={boundary:0,storage:0};return typeof T=="number"||typeof T=="boolean"?(E.boundary=4,E.storage=4):T.isVector2?(E.boundary=8,E.storage=8):T.isVector3||T.isColor?(E.boundary=16,E.storage=12):T.isVector4?(E.boundary=16,E.storage=16):T.isMatrix3?(E.boundary=48,E.storage=48):T.isMatrix4?(E.boundary=64,E.storage=64):T.isTexture?Be("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Be("WebGLRenderer: Unsupported uniform value type.",T),E}function m(T){const E=T.target;E.removeEventListener("dispose",m);const y=o.indexOf(E.__bindingPointIndex);o.splice(y,1),i.deleteBuffer(s[E.id]),delete s[E.id],delete r[E.id]}function p(){for(const T in s)i.deleteBuffer(s[T]);o=[],s={},r={}}return{bind:c,update:l,dispose:p}}const tM=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 li=null;function nM(){return li===null&&(li=new ES(tM,16,16,Qs,Ci),li.name="DFG_LUT",li.minFilter=sn,li.magFilter=sn,li.wrapS=Ti,li.wrapT=Ti,li.generateMipmaps=!1,li.needsUpdate=!0),li}class ug{constructor(e={}){const{canvas:t=Q_(),context:n=null,depth:s=!0,stencil:r=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:h=!1,outputBufferType:f=wn}=e;this.isWebGLRenderer=!0;let g;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=n.getContextAttributes().alpha}else g=o;const v=f,m=new Set([Vl,zl,Bl]),p=new Set([wn,si,Yr,Jr,Ul,Fl]),T=new Uint32Array(4),E=new Int32Array(4);let y=null,S=null;const C=[],w=[];let k=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ii,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const _=this;let x=!1;this._outputColorSpace=Nn;let R=0,O=0,F=null,q=-1,K=null;const G=new Dt,W=new Dt;let te=null;const ye=new Fe(0);let ue=0,_e=t.width,Ge=t.height,Ve=1,Mt=null,pt=null;const Y=new Dt(0,0,_e,Ge),ie=new Dt(0,0,_e,Ge);let Ce=!1;const qe=new Kd;let we=!1,rt=!1;const Jt=new At,it=new U,dt=new Dt,yt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let $e=!1;function Vt(){return F===null?Ve:1}let I=n;function Gt(M,N){return t.getContext(M,N)}try{const M={alpha:!0,depth:s,stencil:r,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:d,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Sl}`),t.addEventListener("webglcontextlost",ze,!1),t.addEventListener("webglcontextrestored",St,!1),t.addEventListener("webglcontextcreationerror",ut,!1),I===null){const N="webgl2";if(I=Gt(N,M),I===null)throw Gt(N)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(M){throw st("WebGLRenderer: "+M.message),M}let ct,_t,Re,A,b,L,X,ee,j,ke,fe,Ae,Ue,re,me,Me,Pe,pe,Xe,D,Se,oe,xe,se;function Q(){ct=new nC(I),ct.init(),oe=new $E(I,ct),_t=new $T(I,ct,e,oe),Re=new qE(I,ct),_t.reversedDepthBuffer&&h&&Re.buffers.depth.setReversed(!0),A=new rC(I),b=new PE,L=new jE(I,ct,Re,b,_t,oe,A),X=new KT(_),ee=new tC(_),j=new HS(I),xe=new qT(I,j),ke=new iC(I,j,A,xe),fe=new oC(I,ke,j,A),Xe=new aC(I,_t,L),Me=new XT(b),Ae=new RE(_,X,ee,ct,_t,xe,Me),Ue=new QE(_,b),re=new IE,me=new FE(ct),pe=new WT(_,X,ee,Re,fe,g,c),Pe=new HE(_,fe,_t),se=new eM(I,A,_t,Re),D=new jT(I,ct,A),Se=new sC(I,ct,A),A.programs=Ae.programs,_.capabilities=_t,_.extensions=ct,_.properties=b,_.renderLists=re,_.shadowMap=Pe,_.state=Re,_.info=A}Q(),v!==wn&&(k=new lC(v,t.width,t.height,s,r));const he=new JE(_,I);this.xr=he,this.getContext=function(){return I},this.getContextAttributes=function(){return I.getContextAttributes()},this.forceContextLoss=function(){const M=ct.get("WEBGL_lose_context");M&&M.loseContext()},this.forceContextRestore=function(){const M=ct.get("WEBGL_lose_context");M&&M.restoreContext()},this.getPixelRatio=function(){return Ve},this.setPixelRatio=function(M){M!==void 0&&(Ve=M,this.setSize(_e,Ge,!1))},this.getSize=function(M){return M.set(_e,Ge)},this.setSize=function(M,N,H=!0){if(he.isPresenting){Be("WebGLRenderer: Can't change size while VR device is presenting.");return}_e=M,Ge=N,t.width=Math.floor(M*Ve),t.height=Math.floor(N*Ve),H===!0&&(t.style.width=M+"px",t.style.height=N+"px"),k!==null&&k.setSize(t.width,t.height),this.setViewport(0,0,M,N)},this.getDrawingBufferSize=function(M){return M.set(_e*Ve,Ge*Ve).floor()},this.setDrawingBufferSize=function(M,N,H){_e=M,Ge=N,Ve=H,t.width=Math.floor(M*H),t.height=Math.floor(N*H),this.setViewport(0,0,M,N)},this.setEffects=function(M){if(v===wn){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(M){for(let N=0;N<M.length;N++)if(M[N].isOutputPass===!0){console.warn("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}k.setEffects(M||[])},this.getCurrentViewport=function(M){return M.copy(G)},this.getViewport=function(M){return M.copy(Y)},this.setViewport=function(M,N,H,V){M.isVector4?Y.set(M.x,M.y,M.z,M.w):Y.set(M,N,H,V),Re.viewport(G.copy(Y).multiplyScalar(Ve).round())},this.getScissor=function(M){return M.copy(ie)},this.setScissor=function(M,N,H,V){M.isVector4?ie.set(M.x,M.y,M.z,M.w):ie.set(M,N,H,V),Re.scissor(W.copy(ie).multiplyScalar(Ve).round())},this.getScissorTest=function(){return Ce},this.setScissorTest=function(M){Re.setScissorTest(Ce=M)},this.setOpaqueSort=function(M){Mt=M},this.setTransparentSort=function(M){pt=M},this.getClearColor=function(M){return M.copy(pe.getClearColor())},this.setClearColor=function(){pe.setClearColor(...arguments)},this.getClearAlpha=function(){return pe.getClearAlpha()},this.setClearAlpha=function(){pe.setClearAlpha(...arguments)},this.clear=function(M=!0,N=!0,H=!0){let V=0;if(M){let B=!1;if(F!==null){const ge=F.texture.format;B=m.has(ge)}if(B){const ge=F.texture.type,Te=p.has(ge),be=pe.getClearColor(),Ee=pe.getClearAlpha(),Ie=be.r,Oe=be.g,De=be.b;Te?(T[0]=Ie,T[1]=Oe,T[2]=De,T[3]=Ee,I.clearBufferuiv(I.COLOR,0,T)):(E[0]=Ie,E[1]=Oe,E[2]=De,E[3]=Ee,I.clearBufferiv(I.COLOR,0,E))}else V|=I.COLOR_BUFFER_BIT}N&&(V|=I.DEPTH_BUFFER_BIT),H&&(V|=I.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),I.clear(V)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",ze,!1),t.removeEventListener("webglcontextrestored",St,!1),t.removeEventListener("webglcontextcreationerror",ut,!1),pe.dispose(),re.dispose(),me.dispose(),b.dispose(),X.dispose(),ee.dispose(),fe.dispose(),xe.dispose(),se.dispose(),Ae.dispose(),he.dispose(),he.removeEventListener("sessionstart",vg),he.removeEventListener("sessionend",yg),Rs.stop()};function ze(M){M.preventDefault(),Qp("WebGLRenderer: Context Lost."),x=!0}function St(){Qp("WebGLRenderer: Context Restored."),x=!1;const M=A.autoReset,N=Pe.enabled,H=Pe.autoUpdate,V=Pe.needsUpdate,B=Pe.type;Q(),A.autoReset=M,Pe.enabled=N,Pe.autoUpdate=H,Pe.needsUpdate=V,Pe.type=B}function ut(M){st("WebGLRenderer: A WebGL context could not be created. Reason: ",M.statusMessage)}function hi(M){const N=M.target;N.removeEventListener("dispose",hi),Di(N)}function Di(M){TM(M),b.remove(M)}function TM(M){const N=b.get(M).programs;N!==void 0&&(N.forEach(function(H){Ae.releaseProgram(H)}),M.isShaderMaterial&&Ae.releaseShaderCache(M))}this.renderBufferDirect=function(M,N,H,V,B,ge){N===null&&(N=yt);const Te=B.isMesh&&B.matrixWorld.determinant()<0,be=EM(M,N,H,V,B);Re.setMaterial(V,Te);let Ee=H.index,Ie=1;if(V.wireframe===!0){if(Ee=ke.getWireframeAttribute(H),Ee===void 0)return;Ie=2}const Oe=H.drawRange,De=H.attributes.position;let Ye=Oe.start*Ie,mt=(Oe.start+Oe.count)*Ie;ge!==null&&(Ye=Math.max(Ye,ge.start*Ie),mt=Math.min(mt,(ge.start+ge.count)*Ie)),Ee!==null?(Ye=Math.max(Ye,0),mt=Math.min(mt,Ee.count)):De!=null&&(Ye=Math.max(Ye,0),mt=Math.min(mt,De.count));const Lt=mt-Ye;if(Lt<0||Lt===1/0)return;xe.setup(B,V,be,H,Ee);let Nt,bt=D;if(Ee!==null&&(Nt=j.get(Ee),bt=Se,bt.setIndex(Nt)),B.isMesh)V.wireframe===!0?(Re.setLineWidth(V.wireframeLinewidth*Vt()),bt.setMode(I.LINES)):bt.setMode(I.TRIANGLES);else if(B.isLine){let Le=V.linewidth;Le===void 0&&(Le=1),Re.setLineWidth(Le*Vt()),B.isLineSegments?bt.setMode(I.LINES):B.isLineLoop?bt.setMode(I.LINE_LOOP):bt.setMode(I.LINE_STRIP)}else B.isPoints?bt.setMode(I.POINTS):B.isSprite&&bt.setMode(I.TRIANGLES);if(B.isBatchedMesh)if(B._multiDrawInstances!==null)Zr("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),bt.renderMultiDrawInstances(B._multiDrawStarts,B._multiDrawCounts,B._multiDrawCount,B._multiDrawInstances);else if(ct.get("WEBGL_multi_draw"))bt.renderMultiDraw(B._multiDrawStarts,B._multiDrawCounts,B._multiDrawCount);else{const Le=B._multiDrawStarts,ht=B._multiDrawCounts,at=B._multiDrawCount,Pn=Ee?j.get(Ee).bytesPerElement:1,xr=b.get(V).currentProgram.getUniforms();for(let kn=0;kn<at;kn++)xr.setValue(I,"_gl_DrawID",kn),bt.render(Le[kn]/Pn,ht[kn])}else if(B.isInstancedMesh)bt.renderInstances(Ye,Lt,B.count);else if(H.isInstancedBufferGeometry){const Le=H._maxInstanceCount!==void 0?H._maxInstanceCount:1/0,ht=Math.min(H.instanceCount,Le);bt.renderInstances(Ye,Lt,ht)}else bt.render(Ye,Lt)};function gg(M,N,H){M.transparent===!0&&M.side===Si&&M.forceSinglePass===!1?(M.side=nn,M.needsUpdate=!0,Ko(M,N,H),M.side=_i,M.needsUpdate=!0,Ko(M,N,H),M.side=Si):Ko(M,N,H)}this.compile=function(M,N,H=null){H===null&&(H=M),S=me.get(H),S.init(N),w.push(S),H.traverseVisible(function(B){B.isLight&&B.layers.test(N.layers)&&(S.pushLight(B),B.castShadow&&S.pushShadow(B))}),M!==H&&M.traverseVisible(function(B){B.isLight&&B.layers.test(N.layers)&&(S.pushLight(B),B.castShadow&&S.pushShadow(B))}),S.setupLights();const V=new Set;return M.traverse(function(B){if(!(B.isMesh||B.isPoints||B.isLine||B.isSprite))return;const ge=B.material;if(ge)if(Array.isArray(ge))for(let Te=0;Te<ge.length;Te++){const be=ge[Te];gg(be,H,B),V.add(be)}else gg(ge,H,B),V.add(ge)}),S=w.pop(),V},this.compileAsync=function(M,N,H=null){const V=this.compile(M,N,H);return new Promise(B=>{function ge(){if(V.forEach(function(Te){b.get(Te).currentProgram.isReady()&&V.delete(Te)}),V.size===0){B(M);return}setTimeout(ge,10)}ct.get("KHR_parallel_shader_compile")!==null?ge():setTimeout(ge,10)})};let mu=null;function CM(M){mu&&mu(M)}function vg(){Rs.stop()}function yg(){Rs.start()}const Rs=new Um;Rs.setAnimationLoop(CM),typeof self<"u"&&Rs.setContext(self),this.setAnimationLoop=function(M){mu=M,he.setAnimationLoop(M),M===null?Rs.stop():Rs.start()},he.addEventListener("sessionstart",vg),he.addEventListener("sessionend",yg),this.render=function(M,N){if(N!==void 0&&N.isCamera!==!0){st("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(x===!0)return;const H=he.enabled===!0&&he.isPresenting===!0,V=k!==null&&(F===null||H)&&k.begin(_,F);if(M.matrixWorldAutoUpdate===!0&&M.updateMatrixWorld(),N.parent===null&&N.matrixWorldAutoUpdate===!0&&N.updateMatrixWorld(),he.enabled===!0&&he.isPresenting===!0&&(k===null||k.isCompositing()===!1)&&(he.cameraAutoUpdate===!0&&he.updateCamera(N),N=he.getCamera()),M.isScene===!0&&M.onBeforeRender(_,M,N,F),S=me.get(M,w.length),S.init(N),w.push(S),Jt.multiplyMatrices(N.projectionMatrix,N.matrixWorldInverse),qe.setFromProjectionMatrix(Jt,ai,N.reversedDepth),rt=this.localClippingEnabled,we=Me.init(this.clippingPlanes,rt),y=re.get(M,C.length),y.init(),C.push(y),he.enabled===!0&&he.isPresenting===!0){const Te=_.xr.getDepthSensingMesh();Te!==null&&gu(Te,N,-1/0,_.sortObjects)}gu(M,N,0,_.sortObjects),y.finish(),_.sortObjects===!0&&y.sort(Mt,pt),$e=he.enabled===!1||he.isPresenting===!1||he.hasDepthSensing()===!1,$e&&pe.addToRenderList(y,M),this.info.render.frame++,we===!0&&Me.beginShadows();const B=S.state.shadowsArray;if(Pe.render(B,M,N),we===!0&&Me.endShadows(),this.info.autoReset===!0&&this.info.reset(),(V&&k.hasRenderPass())===!1){const Te=y.opaque,be=y.transmissive;if(S.setupLights(),N.isArrayCamera){const Ee=N.cameras;if(be.length>0)for(let Ie=0,Oe=Ee.length;Ie<Oe;Ie++){const De=Ee[Ie];_g(Te,be,M,De)}$e&&pe.render(M);for(let Ie=0,Oe=Ee.length;Ie<Oe;Ie++){const De=Ee[Ie];bg(y,M,De,De.viewport)}}else be.length>0&&_g(Te,be,M,N),$e&&pe.render(M),bg(y,M,N)}F!==null&&O===0&&(L.updateMultisampleRenderTarget(F),L.updateRenderTargetMipmap(F)),V&&k.end(_),M.isScene===!0&&M.onAfterRender(_,M,N),xe.resetDefaultState(),q=-1,K=null,w.pop(),w.length>0?(S=w[w.length-1],we===!0&&Me.setGlobalState(_.clippingPlanes,S.state.camera)):S=null,C.pop(),C.length>0?y=C[C.length-1]:y=null};function gu(M,N,H,V){if(M.visible===!1)return;if(M.layers.test(N.layers)){if(M.isGroup)H=M.renderOrder;else if(M.isLOD)M.autoUpdate===!0&&M.update(N);else if(M.isLight)S.pushLight(M),M.castShadow&&S.pushShadow(M);else if(M.isSprite){if(!M.frustumCulled||qe.intersectsSprite(M)){V&&dt.setFromMatrixPosition(M.matrixWorld).applyMatrix4(Jt);const Te=fe.update(M),be=M.material;be.visible&&y.push(M,Te,be,H,dt.z,null)}}else if((M.isMesh||M.isLine||M.isPoints)&&(!M.frustumCulled||qe.intersectsObject(M))){const Te=fe.update(M),be=M.material;if(V&&(M.boundingSphere!==void 0?(M.boundingSphere===null&&M.computeBoundingSphere(),dt.copy(M.boundingSphere.center)):(Te.boundingSphere===null&&Te.computeBoundingSphere(),dt.copy(Te.boundingSphere.center)),dt.applyMatrix4(M.matrixWorld).applyMatrix4(Jt)),Array.isArray(be)){const Ee=Te.groups;for(let Ie=0,Oe=Ee.length;Ie<Oe;Ie++){const De=Ee[Ie],Ye=be[De.materialIndex];Ye&&Ye.visible&&y.push(M,Te,Ye,H,dt.z,De)}}else be.visible&&y.push(M,Te,be,H,dt.z,null)}}const ge=M.children;for(let Te=0,be=ge.length;Te<be;Te++)gu(ge[Te],N,H,V)}function bg(M,N,H,V){const{opaque:B,transmissive:ge,transparent:Te}=M;S.setupLightsView(H),we===!0&&Me.setGlobalState(_.clippingPlanes,H),V&&Re.viewport(G.copy(V)),B.length>0&&Xo(B,N,H),ge.length>0&&Xo(ge,N,H),Te.length>0&&Xo(Te,N,H),Re.buffers.depth.setTest(!0),Re.buffers.depth.setMask(!0),Re.buffers.color.setMask(!0),Re.setPolygonOffset(!1)}function _g(M,N,H,V){if((H.isScene===!0?H.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[V.id]===void 0){const Ye=ct.has("EXT_color_buffer_half_float")||ct.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[V.id]=new oi(1,1,{generateMipmaps:!0,type:Ye?Ci:wn,minFilter:ys,samples:_t.samples,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:nt.workingColorSpace})}const ge=S.state.transmissionRenderTarget[V.id],Te=V.viewport||G;ge.setSize(Te.z*_.transmissionResolutionScale,Te.w*_.transmissionResolutionScale);const be=_.getRenderTarget(),Ee=_.getActiveCubeFace(),Ie=_.getActiveMipmapLevel();_.setRenderTarget(ge),_.getClearColor(ye),ue=_.getClearAlpha(),ue<1&&_.setClearColor(16777215,.5),_.clear(),$e&&pe.render(H);const Oe=_.toneMapping;_.toneMapping=ii;const De=V.viewport;if(V.viewport!==void 0&&(V.viewport=void 0),S.setupLightsView(V),we===!0&&Me.setGlobalState(_.clippingPlanes,V),Xo(M,H,V),L.updateMultisampleRenderTarget(ge),L.updateRenderTargetMipmap(ge),ct.has("WEBGL_multisampled_render_to_texture")===!1){let Ye=!1;for(let mt=0,Lt=N.length;mt<Lt;mt++){const Nt=N[mt],{object:bt,geometry:Le,material:ht,group:at}=Nt;if(ht.side===Si&&bt.layers.test(V.layers)){const Pn=ht.side;ht.side=nn,ht.needsUpdate=!0,Sg(bt,H,V,Le,ht,at),ht.side=Pn,ht.needsUpdate=!0,Ye=!0}}Ye===!0&&(L.updateMultisampleRenderTarget(ge),L.updateRenderTargetMipmap(ge))}_.setRenderTarget(be,Ee,Ie),_.setClearColor(ye,ue),De!==void 0&&(V.viewport=De),_.toneMapping=Oe}function Xo(M,N,H){const V=N.isScene===!0?N.overrideMaterial:null;for(let B=0,ge=M.length;B<ge;B++){const Te=M[B],{object:be,geometry:Ee,group:Ie}=Te;let Oe=Te.material;Oe.allowOverride===!0&&V!==null&&(Oe=V),be.layers.test(H.layers)&&Sg(be,N,H,Ee,Oe,Ie)}}function Sg(M,N,H,V,B,ge){M.onBeforeRender(_,N,H,V,B,ge),M.modelViewMatrix.multiplyMatrices(H.matrixWorldInverse,M.matrixWorld),M.normalMatrix.getNormalMatrix(M.modelViewMatrix),B.onBeforeRender(_,N,H,V,M,ge),B.transparent===!0&&B.side===Si&&B.forceSinglePass===!1?(B.side=nn,B.needsUpdate=!0,_.renderBufferDirect(H,N,V,B,M,ge),B.side=_i,B.needsUpdate=!0,_.renderBufferDirect(H,N,V,B,M,ge),B.side=Si):_.renderBufferDirect(H,N,V,B,M,ge),M.onAfterRender(_,N,H,V,B,ge)}function Ko(M,N,H){N.isScene!==!0&&(N=yt);const V=b.get(M),B=S.state.lights,ge=S.state.shadowsArray,Te=B.state.version,be=Ae.getParameters(M,B.state,ge,N,H),Ee=Ae.getProgramCacheKey(be);let Ie=V.programs;V.environment=M.isMeshStandardMaterial?N.environment:null,V.fog=N.fog,V.envMap=(M.isMeshStandardMaterial?ee:X).get(M.envMap||V.environment),V.envMapRotation=V.environment!==null&&M.envMap===null?N.environmentRotation:M.envMapRotation,Ie===void 0&&(M.addEventListener("dispose",hi),Ie=new Map,V.programs=Ie);let Oe=Ie.get(Ee);if(Oe!==void 0){if(V.currentProgram===Oe&&V.lightsStateVersion===Te)return Tg(M,be),Oe}else be.uniforms=Ae.getUniforms(M),M.onBeforeCompile(be,_),Oe=Ae.acquireProgram(be,Ee),Ie.set(Ee,Oe),V.uniforms=be.uniforms;const De=V.uniforms;return(!M.isShaderMaterial&&!M.isRawShaderMaterial||M.clipping===!0)&&(De.clippingPlanes=Me.uniform),Tg(M,be),V.needsLights=wM(M),V.lightsStateVersion=Te,V.needsLights&&(De.ambientLightColor.value=B.state.ambient,De.lightProbe.value=B.state.probe,De.directionalLights.value=B.state.directional,De.directionalLightShadows.value=B.state.directionalShadow,De.spotLights.value=B.state.spot,De.spotLightShadows.value=B.state.spotShadow,De.rectAreaLights.value=B.state.rectArea,De.ltc_1.value=B.state.rectAreaLTC1,De.ltc_2.value=B.state.rectAreaLTC2,De.pointLights.value=B.state.point,De.pointLightShadows.value=B.state.pointShadow,De.hemisphereLights.value=B.state.hemi,De.directionalShadowMap.value=B.state.directionalShadowMap,De.directionalShadowMatrix.value=B.state.directionalShadowMatrix,De.spotShadowMap.value=B.state.spotShadowMap,De.spotLightMatrix.value=B.state.spotLightMatrix,De.spotLightMap.value=B.state.spotLightMap,De.pointShadowMap.value=B.state.pointShadowMap,De.pointShadowMatrix.value=B.state.pointShadowMatrix),V.currentProgram=Oe,V.uniformsList=null,Oe}function xg(M){if(M.uniformsList===null){const N=M.currentProgram.getUniforms();M.uniformsList=qo.seqWithValue(N.seq,M.uniforms)}return M.uniformsList}function Tg(M,N){const H=b.get(M);H.outputColorSpace=N.outputColorSpace,H.batching=N.batching,H.batchingColor=N.batchingColor,H.instancing=N.instancing,H.instancingColor=N.instancingColor,H.instancingMorph=N.instancingMorph,H.skinning=N.skinning,H.morphTargets=N.morphTargets,H.morphNormals=N.morphNormals,H.morphColors=N.morphColors,H.morphTargetsCount=N.morphTargetsCount,H.numClippingPlanes=N.numClippingPlanes,H.numIntersection=N.numClipIntersection,H.vertexAlphas=N.vertexAlphas,H.vertexTangents=N.vertexTangents,H.toneMapping=N.toneMapping}function EM(M,N,H,V,B){N.isScene!==!0&&(N=yt),L.resetTextureUnits();const ge=N.fog,Te=V.isMeshStandardMaterial?N.environment:null,be=F===null?_.outputColorSpace:F.isXRRenderTarget===!0?F.texture.colorSpace:er,Ee=(V.isMeshStandardMaterial?ee:X).get(V.envMap||Te),Ie=V.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,Oe=!!H.attributes.tangent&&(!!V.normalMap||V.anisotropy>0),De=!!H.morphAttributes.position,Ye=!!H.morphAttributes.normal,mt=!!H.morphAttributes.color;let Lt=ii;V.toneMapped&&(F===null||F.isXRRenderTarget===!0)&&(Lt=_.toneMapping);const Nt=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,bt=Nt!==void 0?Nt.length:0,Le=b.get(V),ht=S.state.lights;if(we===!0&&(rt===!0||M!==K)){const mn=M===K&&V.id===q;Me.setState(V,M,mn)}let at=!1;V.version===Le.__version?(Le.needsLights&&Le.lightsStateVersion!==ht.state.version||Le.outputColorSpace!==be||B.isBatchedMesh&&Le.batching===!1||!B.isBatchedMesh&&Le.batching===!0||B.isBatchedMesh&&Le.batchingColor===!0&&B.colorTexture===null||B.isBatchedMesh&&Le.batchingColor===!1&&B.colorTexture!==null||B.isInstancedMesh&&Le.instancing===!1||!B.isInstancedMesh&&Le.instancing===!0||B.isSkinnedMesh&&Le.skinning===!1||!B.isSkinnedMesh&&Le.skinning===!0||B.isInstancedMesh&&Le.instancingColor===!0&&B.instanceColor===null||B.isInstancedMesh&&Le.instancingColor===!1&&B.instanceColor!==null||B.isInstancedMesh&&Le.instancingMorph===!0&&B.morphTexture===null||B.isInstancedMesh&&Le.instancingMorph===!1&&B.morphTexture!==null||Le.envMap!==Ee||V.fog===!0&&Le.fog!==ge||Le.numClippingPlanes!==void 0&&(Le.numClippingPlanes!==Me.numPlanes||Le.numIntersection!==Me.numIntersection)||Le.vertexAlphas!==Ie||Le.vertexTangents!==Oe||Le.morphTargets!==De||Le.morphNormals!==Ye||Le.morphColors!==mt||Le.toneMapping!==Lt||Le.morphTargetsCount!==bt)&&(at=!0):(at=!0,Le.__version=V.version);let Pn=Le.currentProgram;at===!0&&(Pn=Ko(V,N,B));let xr=!1,kn=!1,ma=!1;const xt=Pn.getUniforms(),Cn=Le.uniforms;if(Re.useProgram(Pn.program)&&(xr=!0,kn=!0,ma=!0),V.id!==q&&(q=V.id,kn=!0),xr||K!==M){Re.buffers.depth.getReversed()&&M.reversedDepth!==!0&&(M._reversedDepth=!0,M.updateProjectionMatrix()),xt.setValue(I,"projectionMatrix",M.projectionMatrix),xt.setValue(I,"viewMatrix",M.matrixWorldInverse);const En=xt.map.cameraPosition;En!==void 0&&En.setValue(I,it.setFromMatrixPosition(M.matrixWorld)),_t.logarithmicDepthBuffer&&xt.setValue(I,"logDepthBufFC",2/(Math.log(M.far+1)/Math.LN2)),(V.isMeshPhongMaterial||V.isMeshToonMaterial||V.isMeshLambertMaterial||V.isMeshBasicMaterial||V.isMeshStandardMaterial||V.isShaderMaterial)&&xt.setValue(I,"isOrthographic",M.isOrthographicCamera===!0),K!==M&&(K=M,kn=!0,ma=!0)}if(Le.needsLights&&(ht.state.directionalShadowMap.length>0&&xt.setValue(I,"directionalShadowMap",ht.state.directionalShadowMap,L),ht.state.spotShadowMap.length>0&&xt.setValue(I,"spotShadowMap",ht.state.spotShadowMap,L),ht.state.pointShadowMap.length>0&&xt.setValue(I,"pointShadowMap",ht.state.pointShadowMap,L)),B.isSkinnedMesh){xt.setOptional(I,B,"bindMatrix"),xt.setOptional(I,B,"bindMatrixInverse");const mn=B.skeleton;mn&&(mn.boneTexture===null&&mn.computeBoneTexture(),xt.setValue(I,"boneTexture",mn.boneTexture,L))}B.isBatchedMesh&&(xt.setOptional(I,B,"batchingTexture"),xt.setValue(I,"batchingTexture",B._matricesTexture,L),xt.setOptional(I,B,"batchingIdTexture"),xt.setValue(I,"batchingIdTexture",B._indirectTexture,L),xt.setOptional(I,B,"batchingColorTexture"),B._colorsTexture!==null&&xt.setValue(I,"batchingColorTexture",B._colorsTexture,L));const Un=H.morphAttributes;if((Un.position!==void 0||Un.normal!==void 0||Un.color!==void 0)&&Xe.update(B,H,Pn),(kn||Le.receiveShadow!==B.receiveShadow)&&(Le.receiveShadow=B.receiveShadow,xt.setValue(I,"receiveShadow",B.receiveShadow)),V.isMeshGouraudMaterial&&V.envMap!==null&&(Cn.envMap.value=Ee,Cn.flipEnvMap.value=Ee.isCubeTexture&&Ee.isRenderTargetTexture===!1?-1:1),V.isMeshStandardMaterial&&V.envMap===null&&N.environment!==null&&(Cn.envMapIntensity.value=N.environmentIntensity),Cn.dfgLUT!==void 0&&(Cn.dfgLUT.value=nM()),kn&&(xt.setValue(I,"toneMappingExposure",_.toneMappingExposure),Le.needsLights&&MM(Cn,ma),ge&&V.fog===!0&&Ue.refreshFogUniforms(Cn,ge),Ue.refreshMaterialUniforms(Cn,V,Ve,Ge,S.state.transmissionRenderTarget[M.id]),qo.upload(I,xg(Le),Cn,L)),V.isShaderMaterial&&V.uniformsNeedUpdate===!0&&(qo.upload(I,xg(Le),Cn,L),V.uniformsNeedUpdate=!1),V.isSpriteMaterial&&xt.setValue(I,"center",B.center),xt.setValue(I,"modelViewMatrix",B.modelViewMatrix),xt.setValue(I,"normalMatrix",B.normalMatrix),xt.setValue(I,"modelMatrix",B.matrixWorld),V.isShaderMaterial||V.isRawShaderMaterial){const mn=V.uniformsGroups;for(let En=0,vu=mn.length;En<vu;En++){const Ps=mn[En];se.update(Ps,Pn),se.bind(Ps,Pn)}}return Pn}function MM(M,N){M.ambientLightColor.needsUpdate=N,M.lightProbe.needsUpdate=N,M.directionalLights.needsUpdate=N,M.directionalLightShadows.needsUpdate=N,M.pointLights.needsUpdate=N,M.pointLightShadows.needsUpdate=N,M.spotLights.needsUpdate=N,M.spotLightShadows.needsUpdate=N,M.rectAreaLights.needsUpdate=N,M.hemisphereLights.needsUpdate=N}function wM(M){return M.isMeshLambertMaterial||M.isMeshToonMaterial||M.isMeshPhongMaterial||M.isMeshStandardMaterial||M.isShadowMaterial||M.isShaderMaterial&&M.lights===!0}this.getActiveCubeFace=function(){return R},this.getActiveMipmapLevel=function(){return O},this.getRenderTarget=function(){return F},this.setRenderTargetTextures=function(M,N,H){const V=b.get(M);V.__autoAllocateDepthBuffer=M.resolveDepthBuffer===!1,V.__autoAllocateDepthBuffer===!1&&(V.__useRenderToTexture=!1),b.get(M.texture).__webglTexture=N,b.get(M.depthTexture).__webglTexture=V.__autoAllocateDepthBuffer?void 0:H,V.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(M,N){const H=b.get(M);H.__webglFramebuffer=N,H.__useDefaultFramebuffer=N===void 0};const AM=I.createFramebuffer();this.setRenderTarget=function(M,N=0,H=0){F=M,R=N,O=H;let V=null,B=!1,ge=!1;if(M){const be=b.get(M);if(be.__useDefaultFramebuffer!==void 0){Re.bindFramebuffer(I.FRAMEBUFFER,be.__webglFramebuffer),G.copy(M.viewport),W.copy(M.scissor),te=M.scissorTest,Re.viewport(G),Re.scissor(W),Re.setScissorTest(te),q=-1;return}else if(be.__webglFramebuffer===void 0)L.setupRenderTarget(M);else if(be.__hasExternalTextures)L.rebindTextures(M,b.get(M.texture).__webglTexture,b.get(M.depthTexture).__webglTexture);else if(M.depthBuffer){const Oe=M.depthTexture;if(be.__boundDepthTexture!==Oe){if(Oe!==null&&b.has(Oe)&&(M.width!==Oe.image.width||M.height!==Oe.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");L.setupDepthRenderbuffer(M)}}const Ee=M.texture;(Ee.isData3DTexture||Ee.isDataArrayTexture||Ee.isCompressedArrayTexture)&&(ge=!0);const Ie=b.get(M).__webglFramebuffer;M.isWebGLCubeRenderTarget?(Array.isArray(Ie[N])?V=Ie[N][H]:V=Ie[N],B=!0):M.samples>0&&L.useMultisampledRTT(M)===!1?V=b.get(M).__webglMultisampledFramebuffer:Array.isArray(Ie)?V=Ie[H]:V=Ie,G.copy(M.viewport),W.copy(M.scissor),te=M.scissorTest}else G.copy(Y).multiplyScalar(Ve).floor(),W.copy(ie).multiplyScalar(Ve).floor(),te=Ce;if(H!==0&&(V=AM),Re.bindFramebuffer(I.FRAMEBUFFER,V)&&Re.drawBuffers(M,V),Re.viewport(G),Re.scissor(W),Re.setScissorTest(te),B){const be=b.get(M.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_CUBE_MAP_POSITIVE_X+N,be.__webglTexture,H)}else if(ge){const be=N;for(let Ee=0;Ee<M.textures.length;Ee++){const Ie=b.get(M.textures[Ee]);I.framebufferTextureLayer(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0+Ee,Ie.__webglTexture,H,be)}}else if(M!==null&&H!==0){const be=b.get(M.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,be.__webglTexture,H)}q=-1},this.readRenderTargetPixels=function(M,N,H,V,B,ge,Te,be=0){if(!(M&&M.isWebGLRenderTarget)){st("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ee=b.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);try{const Ie=M.textures[be],Oe=Ie.format,De=Ie.type;if(!_t.textureFormatReadable(Oe)){st("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!_t.textureTypeReadable(De)){st("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}N>=0&&N<=M.width-V&&H>=0&&H<=M.height-B&&(M.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+be),I.readPixels(N,H,V,B,oe.convert(Oe),oe.convert(De),ge))}finally{const Ie=F!==null?b.get(F).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,Ie)}}},this.readRenderTargetPixelsAsync=async function(M,N,H,V,B,ge,Te,be=0){if(!(M&&M.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ee=b.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee)if(N>=0&&N<=M.width-V&&H>=0&&H<=M.height-B){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);const Ie=M.textures[be],Oe=Ie.format,De=Ie.type;if(!_t.textureFormatReadable(Oe))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!_t.textureTypeReadable(De))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Ye=I.createBuffer();I.bindBuffer(I.PIXEL_PACK_BUFFER,Ye),I.bufferData(I.PIXEL_PACK_BUFFER,ge.byteLength,I.STREAM_READ),M.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+be),I.readPixels(N,H,V,B,oe.convert(Oe),oe.convert(De),0);const mt=F!==null?b.get(F).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,mt);const Lt=I.fenceSync(I.SYNC_GPU_COMMANDS_COMPLETE,0);return I.flush(),await eS(I,Lt,4),I.bindBuffer(I.PIXEL_PACK_BUFFER,Ye),I.getBufferSubData(I.PIXEL_PACK_BUFFER,0,ge),I.deleteBuffer(Ye),I.deleteSync(Lt),ge}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(M,N=null,H=0){const V=Math.pow(2,-H),B=Math.floor(M.image.width*V),ge=Math.floor(M.image.height*V),Te=N!==null?N.x:0,be=N!==null?N.y:0;L.setTexture2D(M,0),I.copyTexSubImage2D(I.TEXTURE_2D,H,0,0,Te,be,B,ge),Re.unbindTexture()};const RM=I.createFramebuffer(),PM=I.createFramebuffer();this.copyTextureToTexture=function(M,N,H=null,V=null,B=0,ge=null){ge===null&&(B!==0?(Zr("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),ge=B,B=0):ge=0);let Te,be,Ee,Ie,Oe,De,Ye,mt,Lt;const Nt=M.isCompressedTexture?M.mipmaps[ge]:M.image;if(H!==null)Te=H.max.x-H.min.x,be=H.max.y-H.min.y,Ee=H.isBox3?H.max.z-H.min.z:1,Ie=H.min.x,Oe=H.min.y,De=H.isBox3?H.min.z:0;else{const Un=Math.pow(2,-B);Te=Math.floor(Nt.width*Un),be=Math.floor(Nt.height*Un),M.isDataArrayTexture?Ee=Nt.depth:M.isData3DTexture?Ee=Math.floor(Nt.depth*Un):Ee=1,Ie=0,Oe=0,De=0}V!==null?(Ye=V.x,mt=V.y,Lt=V.z):(Ye=0,mt=0,Lt=0);const bt=oe.convert(N.format),Le=oe.convert(N.type);let ht;N.isData3DTexture?(L.setTexture3D(N,0),ht=I.TEXTURE_3D):N.isDataArrayTexture||N.isCompressedArrayTexture?(L.setTexture2DArray(N,0),ht=I.TEXTURE_2D_ARRAY):(L.setTexture2D(N,0),ht=I.TEXTURE_2D),I.pixelStorei(I.UNPACK_FLIP_Y_WEBGL,N.flipY),I.pixelStorei(I.UNPACK_PREMULTIPLY_ALPHA_WEBGL,N.premultiplyAlpha),I.pixelStorei(I.UNPACK_ALIGNMENT,N.unpackAlignment);const at=I.getParameter(I.UNPACK_ROW_LENGTH),Pn=I.getParameter(I.UNPACK_IMAGE_HEIGHT),xr=I.getParameter(I.UNPACK_SKIP_PIXELS),kn=I.getParameter(I.UNPACK_SKIP_ROWS),ma=I.getParameter(I.UNPACK_SKIP_IMAGES);I.pixelStorei(I.UNPACK_ROW_LENGTH,Nt.width),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Nt.height),I.pixelStorei(I.UNPACK_SKIP_PIXELS,Ie),I.pixelStorei(I.UNPACK_SKIP_ROWS,Oe),I.pixelStorei(I.UNPACK_SKIP_IMAGES,De);const xt=M.isDataArrayTexture||M.isData3DTexture,Cn=N.isDataArrayTexture||N.isData3DTexture;if(M.isDepthTexture){const Un=b.get(M),mn=b.get(N),En=b.get(Un.__renderTarget),vu=b.get(mn.__renderTarget);Re.bindFramebuffer(I.READ_FRAMEBUFFER,En.__webglFramebuffer),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,vu.__webglFramebuffer);for(let Ps=0;Ps<Ee;Ps++)xt&&(I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,b.get(M).__webglTexture,B,De+Ps),I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,b.get(N).__webglTexture,ge,Lt+Ps)),I.blitFramebuffer(Ie,Oe,Te,be,Ye,mt,Te,be,I.DEPTH_BUFFER_BIT,I.NEAREST);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else if(B!==0||M.isRenderTargetTexture||b.has(M)){const Un=b.get(M),mn=b.get(N);Re.bindFramebuffer(I.READ_FRAMEBUFFER,RM),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,PM);for(let En=0;En<Ee;En++)xt?I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,Un.__webglTexture,B,De+En):I.framebufferTexture2D(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,Un.__webglTexture,B),Cn?I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,mn.__webglTexture,ge,Lt+En):I.framebufferTexture2D(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,mn.__webglTexture,ge),B!==0?I.blitFramebuffer(Ie,Oe,Te,be,Ye,mt,Te,be,I.COLOR_BUFFER_BIT,I.NEAREST):Cn?I.copyTexSubImage3D(ht,ge,Ye,mt,Lt+En,Ie,Oe,Te,be):I.copyTexSubImage2D(ht,ge,Ye,mt,Ie,Oe,Te,be);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else Cn?M.isDataTexture||M.isData3DTexture?I.texSubImage3D(ht,ge,Ye,mt,Lt,Te,be,Ee,bt,Le,Nt.data):N.isCompressedArrayTexture?I.compressedTexSubImage3D(ht,ge,Ye,mt,Lt,Te,be,Ee,bt,Nt.data):I.texSubImage3D(ht,ge,Ye,mt,Lt,Te,be,Ee,bt,Le,Nt):M.isDataTexture?I.texSubImage2D(I.TEXTURE_2D,ge,Ye,mt,Te,be,bt,Le,Nt.data):M.isCompressedTexture?I.compressedTexSubImage2D(I.TEXTURE_2D,ge,Ye,mt,Nt.width,Nt.height,bt,Nt.data):I.texSubImage2D(I.TEXTURE_2D,ge,Ye,mt,Te,be,bt,Le,Nt);I.pixelStorei(I.UNPACK_ROW_LENGTH,at),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Pn),I.pixelStorei(I.UNPACK_SKIP_PIXELS,xr),I.pixelStorei(I.UNPACK_SKIP_ROWS,kn),I.pixelStorei(I.UNPACK_SKIP_IMAGES,ma),ge===0&&N.generateMipmaps&&I.generateMipmap(ht),Re.unbindTexture()},this.initRenderTarget=function(M){b.get(M).__webglFramebuffer===void 0&&L.setupRenderTarget(M)},this.initTexture=function(M){M.isCubeTexture?L.setTextureCube(M,0):M.isData3DTexture?L.setTexture3D(M,0):M.isDataArrayTexture||M.isCompressedArrayTexture?L.setTexture2DArray(M,0):L.setTexture2D(M,0),Re.unbindTexture()},this.resetState=function(){R=0,O=0,F=null,Re.reset(),xe.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ai}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=nt._getDrawingBufferColorSpace(e),t.unpackColorSpace=nt._getUnpackColorSpace()}}const iM=`
4103
4103
  uniform float uTime;
4104
4104
  uniform float uAudioBass;
4105
4105
  uniform float uAudioMid;
@@ -4468,7 +4468,7 @@ void main() {
4468
4468
  // Softer alpha for more diffuse appearance
4469
4469
  gl_FragColor = vec4(glowColor, glow * 0.4);
4470
4470
  }
4471
- `,As={primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},oM={size:1,segments:128,colors:As,morphStrength:1,noiseScale:.8,noiseSpeed:.15,glowIntensity:.8,idleGlowMultiplier:.4,fresnelPower:2.5,rotationSpeed:.1,audioReactivity:1,audioSmoothing:.03,idleMorphMultiplier:.25,colorContrast:1.5};class hu{constructor(e,t={}){this.orb=null,this.glowMesh=null,this.orbMaterial=null,this.glowMaterial=null,this.animationId=null,this.isActive=!1,this.targetRotation={x:0,y:0},this.currentRotation={x:0,y:0},this.audioValues={bass:0,mid:0,treble:0,level:0},this.smoothedUniforms={bass:0,mid:0,treble:0,level:0},this.canvasPadding=3,this.animate=()=>{this.animationId=requestAnimationFrame(this.animate);const a=this.clock.getElapsedTime();this.clock.getDelta();const c=.02;if(this.smoothedUniforms.bass+=(this.audioValues.bass-this.smoothedUniforms.bass)*c,this.smoothedUniforms.mid+=(this.audioValues.mid-this.smoothedUniforms.mid)*c,this.smoothedUniforms.treble+=(this.audioValues.treble-this.smoothedUniforms.treble)*c,this.smoothedUniforms.level+=(this.audioValues.level-this.smoothedUniforms.level)*c,this.orbMaterial){this.orbMaterial.uniforms.uTime.value=a,this.orbMaterial.uniforms.uAudioBass.value=this.smoothedUniforms.bass,this.orbMaterial.uniforms.uAudioMid.value=this.smoothedUniforms.mid,this.orbMaterial.uniforms.uAudioTreble.value=this.smoothedUniforms.treble,this.orbMaterial.uniforms.uAudioLevel.value=this.smoothedUniforms.level;const l=this.isActive?this.config.morphStrength*1.2:this.config.morphStrength*this.config.idleMorphMultiplier,d=this.orbMaterial.uniforms.uMorphStrength.value;this.orbMaterial.uniforms.uMorphStrength.value+=(l-d)*.02}if(this.glowMaterial){this.glowMaterial.uniforms.uTime.value=a,this.glowMaterial.uniforms.uAudioLevel.value=this.smoothedUniforms.level;const l=this.isActive?this.config.glowIntensity*1.2:this.config.glowIntensity*this.config.idleGlowMultiplier,d=this.glowMaterial.uniforms.uGlowIntensity.value;this.glowMaterial.uniforms.uGlowIntensity.value+=(l-d)*.02}this.currentRotation.x+=(this.targetRotation.x-this.currentRotation.x)*.05,this.currentRotation.y+=(this.targetRotation.y-this.currentRotation.y)*.05,this.orb&&(this.orb.rotation.x=this.currentRotation.x+a*this.config.rotationSpeed*.3,this.orb.rotation.y=this.currentRotation.y+a*this.config.rotationSpeed),this.glowMesh&&(this.glowMesh.rotation.x=this.currentRotation.x+a*this.config.rotationSpeed*.3,this.glowMesh.rotation.y=this.currentRotation.y+a*this.config.rotationSpeed),this.renderer.render(this.scene,this.camera)},this.handleResize=()=>{const a=this.container.clientWidth*this.canvasPadding,c=this.container.clientHeight*this.canvasPadding;this.camera.aspect=a/c,this.camera.updateProjectionMatrix(),this.renderer.setSize(a,c)},this.handleMouseMove=a=>{const c=this.container.getBoundingClientRect(),l=(a.clientX-c.left)/c.width*2-1,d=-((a.clientY-c.top)/c.height)*2+1;this.targetRotation.x=d*.3,this.targetRotation.y=l*.3},this.handleMouseLeave=()=>{this.targetRotation.x=0,this.targetRotation.y=0},this.container=e,this.config={...oM,...t},this.clock=new Nm,this.scene=new Mm;const n=e.clientWidth*this.canvasPadding,s=e.clientHeight*this.canvasPadding,r=n/s;this.camera=new xn(45,r,.1,100),this.camera.position.z=9,this.renderer=new ug({antialias:!0,alpha:!0,powerPreference:"high-performance"}),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(n,s),this.renderer.setClearColor(0,0);const o=this.renderer.domElement;o.style.position="absolute",o.style.left="50%",o.style.top="50%",o.style.transform="translate(-50%, -50%)",o.style.pointerEvents="none",e.appendChild(o),this.createOrb(),window.addEventListener("resize",this.handleResize),e.addEventListener("mousemove",this.handleMouseMove),e.addEventListener("mouseleave",this.handleMouseLeave)}createOrb(){const e={...As,...this.config.colors},t=new Qd(this.config.size,this.config.segments/4);this.orbMaterial=new en({vertexShader:iM,fragmentShader:sM,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 Fe(e.primary)},uColorSecondary:{value:new Fe(e.secondary)},uColorAccent:{value:new Fe(e.accent)},uColorDepth:{value:new Fe(e.depth||As.depth)},uColorHighlight:{value:new Fe(e.highlight||As.highlight)},uFresnelPower:{value:this.config.fresnelPower},uGlowIntensity:{value:this.config.glowIntensity},uColorContrast:{value:this.config.colorContrast}},transparent:!0,side:_i}),this.orb=new Sn(t,this.orbMaterial),this.scene.add(this.orb);const n=new yr(this.config.size,64,64);this.glowMaterial=new en({vertexShader:rM,fragmentShader:aM,uniforms:{uTime:{value:0},uAudioLevel:{value:0},uGlowColor:{value:new Fe(e.glow)},uGlowIntensity:{value:this.config.glowIntensity*.6},uPulseSpeed:{value:2}},transparent:!0,side:tn,blending:Ji,depthWrite:!1}),this.glowMesh=new Sn(n,this.glowMaterial),this.scene.add(this.glowMesh)}updateAudio(e){const t=this.config.audioSmoothing;this.audioValues.bass+=(e.bass-this.audioValues.bass)*t,this.audioValues.mid+=(e.mid-this.audioValues.mid)*t,this.audioValues.treble+=(e.treble-this.audioValues.treble)*t,this.audioValues.level+=(e.level-this.audioValues.level)*t}setSimulatedAudio(e,t,n,s){const r=this.config.audioSmoothing;this.audioValues.bass+=(e-this.audioValues.bass)*r,this.audioValues.mid+=(t-this.audioValues.mid)*r,this.audioValues.treble+=(n-this.audioValues.treble)*r,this.audioValues.level+=(s-this.audioValues.level)*r}setActive(e){this.isActive=e}setColors(e){const t={...As,...this.config.colors,...e};this.orbMaterial&&(this.orbMaterial.uniforms.uColorPrimary.value.set(t.primary),this.orbMaterial.uniforms.uColorSecondary.value.set(t.secondary),this.orbMaterial.uniforms.uColorAccent.value.set(t.accent),this.orbMaterial.uniforms.uColorDepth.value.set(t.depth||As.depth),this.orbMaterial.uniforms.uColorHighlight.value.set(t.highlight||As.highlight)),this.glowMaterial&&this.glowMaterial.uniforms.uGlowColor.value.set(t.glow)}setGlowSettings(e,t){this.config.glowIntensity=e,this.config.idleGlowMultiplier=t}start(){this.animationId===null&&(this.clock.start(),this.animate())}stop(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}getCanvas(){return this.renderer.domElement}destroy(){this.stop(),window.removeEventListener("resize",this.handleResize),this.container.removeEventListener("mousemove",this.handleMouseMove),this.container.removeEventListener("mouseleave",this.handleMouseLeave),this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb)),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh)),this.orbMaterial&&this.orbMaterial.dispose(),this.glowMaterial&&this.glowMaterial.dispose(),this.renderer.dispose(),this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement)}}class fu{constructor(e={}){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.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0,this.smoothingFactor=.04,this.options={fftSize:e.fftSize??2048,smoothingTimeConstant:e.smoothingTimeConstant??.8,minDecibels:e.minDecibels??-90,maxDecibels:e.maxDecibels??-10}}async connectStream(e){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.source&&this.source.disconnect(),this.source=this.audioContext.createMediaStreamSource(e),this.setupMixerAndAnalyser(),this.source.connect(this.mixer)}async connectLocalStream(e){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.localSource&&this.localSource.disconnect(),this.localSource=this.audioContext.createMediaStreamSource(e),this.setupMixerAndAnalyser(),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(e){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.source&&this.source.disconnect();const t=this.audioContext.createMediaElementSource(e);this.analyser||(this.analyser=this.audioContext.createAnalyser()),this.analyser.fftSize=this.options.fftSize,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant,this.analyser.minDecibels=this.options.minDecibels,this.analyser.maxDecibels=this.options.maxDecibels,t.connect(this.analyser),this.analyser.connect(this.audioContext.destination),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize)}getAudioData(){if(!this.analyser)return{bass:0,mid:0,treble:0,level:0,waveform:new Float32Array(0),frequency:new Uint8Array(0)};this.analyser.getByteFrequencyData(this.frequencyData),this.analyser.getFloatTimeDomainData(this.waveformData);const{bass:e,mid:t,treble:n}=this.calculateFrequencyBands(),s=this.calculateOverallLevel();return this.smoothedBass+=(e-this.smoothedBass)*this.smoothingFactor,this.smoothedMid+=(t-this.smoothedMid)*this.smoothingFactor,this.smoothedTreble+=(n-this.smoothedTreble)*this.smoothingFactor,this.smoothedLevel+=(s-this.smoothedLevel)*this.smoothingFactor,{bass:this.smoothedBass,mid:this.smoothedMid,treble:this.smoothedTreble,level:this.smoothedLevel,waveform:this.waveformData,frequency:this.frequencyData}}calculateFrequencyBands(){if(!this.audioContext||this.frequencyData.length===0)return{bass:0,mid:0,treble:0};const e=this.audioContext.sampleRate,t=this.frequencyData.length,n=e/(t*2),s=Math.floor(250/n),r=Math.floor(2e3/n);let o=0,a=0,c=0;for(let h=0;h<t;h++){const f=this.frequencyData[h]/255;h<s?o+=f:h<r?a+=f:c+=f}const l=s>0?o/s:0,d=r-s>0?a/(r-s):0,u=t-r>0?c/(t-r):0;return{bass:Math.pow(l,.8),mid:Math.pow(d,.9),treble:Math.pow(u,1.1)}}calculateOverallLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let n=0;n<this.frequencyData.length;n++)e+=this.frequencyData[n];const t=e/this.frequencyData.length/255;return Math.pow(t,.8)}getPeakLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let t=0;t<this.frequencyData.length;t++)this.frequencyData[t]>e&&(e=this.frequencyData[t]);return e/255}isActive(){return this.audioContext!==null&&this.audioContext.state==="running"}disconnect(){this.source&&(this.source.disconnect(),this.source=null),this.localSource&&(this.localSource.disconnect(),this.localSource=null),this.mixer&&(this.mixer.disconnect(),this.mixer=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0}getAudioContext(){return this.audioContext}getAnalyser(){return this.analyser}}class $o{constructor(e={}){this.audioContext=null,this.config={enabled:!0,volume:.15,...e}}async ensureContext(){if(!this.config.enabled)return null;if(!this.audioContext)try{this.audioContext=new(window.AudioContext||window.webkitAudioContext)}catch{return console.warn("Web Audio API not supported"),null}return this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.audioContext}async prewarm(){await this.ensureContext()}createTone(e,t,n,s,r="sine"){const o=e.createOscillator(),a=e.createGain();o.type=r,o.frequency.setValueAtTime(t,n);const c=.05,l=.1,d=.7,u=.3;return a.gain.setValueAtTime(0,n),a.gain.linearRampToValueAtTime(this.config.volume,n+c),a.gain.linearRampToValueAtTime(this.config.volume*d,n+c+l),a.gain.setValueAtTime(this.config.volume*d,n+s-u),a.gain.linearRampToValueAtTime(0,n+s),o.connect(a),{oscillator:o,gain:a}}async playCallStartSound(){const e=await this.ensureContext();if(!e||typeof e.createGain!="function")return;const t=e.currentTime,n=e.createGain();n.gain.setValueAtTime(1,t),n.connect(e.destination);const{oscillator:s,gain:r}=this.createTone(e,880,t,.12,"sine");r.connect(n),s.start(t),s.stop(t+.12);const{oscillator:o,gain:a}=this.createTone(e,1046,t+.08,.15,"sine");a.connect(n),o.start(t+.08),o.stop(t+.23),setTimeout(()=>{try{s.disconnect()}catch{}try{o.disconnect()}catch{}},300)}async playCallEndSound(){const e=await this.ensureContext();if(!e||typeof e.createGain!="function")return;const t=e.currentTime,n=e.createGain();n.gain.setValueAtTime(1,t),n.connect(e.destination);const{oscillator:s,gain:r}=this.createTone(e,660,t,.2,"sine");r.connect(n),s.start(t),s.stop(t+.2),setTimeout(()=>{try{s.disconnect()}catch{}},250)}setConfig(e){this.config={...this.config,...e}}setEnabled(e){this.config.enabled=e}setVolume(e){this.config.volume=Math.max(0,Math.min(1,e))}getConfig(){return{...this.config}}isEnabled(){return this.config.enabled}destroy(){this.audioContext&&(this.audioContext.close(),this.audioContext=null)}}const di={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"}},ui={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"}};function cM(i,e="dark"){const t=e==="dark"?di:ui;return t[i]||t[Object.keys(t)[0]]}function lM(i="dark"){return Object.keys(i==="dark"?di:ui)}const Sr={default:{dark:{colors:di.default,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.indigo,glowIntensity:1.8,idleGlowMultiplier:1.2}},emerald:{dark:{colors:di.emerald,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.teal,glowIntensity:1.8,idleGlowMultiplier:1.2}},rose:{dark:{colors:di.rose,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.pink,glowIntensity:1.8,idleGlowMultiplier:1.2}},amber:{dark:{colors:di.amber,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.orange,glowIntensity:1.8,idleGlowMultiplier:1.2}},cyan:{dark:{colors:di.cyan,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},purple:{dark:{colors:di.purple,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.violet,glowIntensity:1.8,idleGlowMultiplier:1.2}},blue:{dark:{colors:di.blue,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}}},dM=Object.fromEntries(Object.entries(Sr).map(([i,e])=>[i,e.dark])),uM=Object.fromEntries(Object.entries(Sr).map(([i,e])=>[i,e.light]));function hg(){return typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function pa(i,e="auto"){const t=Sr[i]||Sr.default,n=e==="auto"?hg():e;return t[n]}function hM(){return Object.keys(Sr)}function fg(i,e,t="auto"){const n=pa(e,t);i.orbColors=n.colors,i.glowIntensity=n.glowIntensity,i.idleGlowMultiplier=n.idleGlowMultiplier}function fM(i,e){if(typeof window>"u")return()=>{};const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>{const s=t.matches?"dark":"light";fg(i,e,s)};return n(),t.addEventListener("change",n),()=>{t.removeEventListener("change",n)}}var pM=Object.defineProperty,mM=Object.getOwnPropertyDescriptor,Tt=(i,e,t,n)=>{for(var s=n>1?void 0:n?mM(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&pM(e,t,s),s};$.InlineCall=class extends Ui{constructor(){super(...arguments),this.callManager=new ro,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=xa(),this.animationId=null,this.callStatus="idle",this.microphoneEnabled=!1,this.buttonStartText="Try to call",this.buttonConnectingText="Connecting...",this.size=370,this.containerPadding=45,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=.8,this.noiseSpeed=.15,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=1,this.audioSmoothing=.03,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.15,this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1},this.handleStatusChange=e=>{var n,s,r,o,a;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(o=this.orbRenderer)==null||o.setActive(!1),(a=this.audioAnalyzer)==null||a.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&((e=this.soundManager)==null||e.prewarm(),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp())}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new $o({enabled:this.soundEnabled,volume:this.soundVolume}),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)}disconnectedCallback(){var e;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(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(e){var t,n;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume))}applyTheme(){if(this.theme){const e=pa(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new hu(e,{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 fu,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const t=performance.now()/1e3,n=Math.sin(t*.5)*.15+.15,s=Math.sin(t*.7+1)*.12+.12,r=Math.sin(t*.9+2)*.08+.08,o=(n+s+r)/3;this.orbRenderer.setSimulatedAudio(n,s,r,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer)return;const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Rt`
4471
+ `,As={primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},oM={size:1,segments:128,colors:As,morphStrength:1,noiseScale:.8,noiseSpeed:.15,glowIntensity:.8,idleGlowMultiplier:.4,fresnelPower:2.5,rotationSpeed:.1,audioReactivity:1,audioSmoothing:.03,idleMorphMultiplier:.25,colorContrast:1.5};class hu{constructor(e,t={}){this.orb=null,this.glowMesh=null,this.orbMaterial=null,this.glowMaterial=null,this.animationId=null,this.isActive=!1,this.targetRotation={x:0,y:0},this.currentRotation={x:0,y:0},this.audioValues={bass:0,mid:0,treble:0,level:0},this.smoothedUniforms={bass:0,mid:0,treble:0,level:0},this.canvasPadding=3,this.animate=()=>{this.animationId=requestAnimationFrame(this.animate);const a=this.clock.getElapsedTime();this.clock.getDelta();const c=.02;if(this.smoothedUniforms.bass+=(this.audioValues.bass-this.smoothedUniforms.bass)*c,this.smoothedUniforms.mid+=(this.audioValues.mid-this.smoothedUniforms.mid)*c,this.smoothedUniforms.treble+=(this.audioValues.treble-this.smoothedUniforms.treble)*c,this.smoothedUniforms.level+=(this.audioValues.level-this.smoothedUniforms.level)*c,this.orbMaterial){this.orbMaterial.uniforms.uTime.value=a,this.orbMaterial.uniforms.uAudioBass.value=this.smoothedUniforms.bass,this.orbMaterial.uniforms.uAudioMid.value=this.smoothedUniforms.mid,this.orbMaterial.uniforms.uAudioTreble.value=this.smoothedUniforms.treble,this.orbMaterial.uniforms.uAudioLevel.value=this.smoothedUniforms.level;const l=this.isActive?this.config.morphStrength*1.2:this.config.morphStrength*this.config.idleMorphMultiplier,d=this.orbMaterial.uniforms.uMorphStrength.value;this.orbMaterial.uniforms.uMorphStrength.value+=(l-d)*.02}if(this.glowMaterial){this.glowMaterial.uniforms.uTime.value=a,this.glowMaterial.uniforms.uAudioLevel.value=this.smoothedUniforms.level;const l=this.isActive?this.config.glowIntensity*1.2:this.config.glowIntensity*this.config.idleGlowMultiplier,d=this.glowMaterial.uniforms.uGlowIntensity.value;this.glowMaterial.uniforms.uGlowIntensity.value+=(l-d)*.02}this.currentRotation.x+=(this.targetRotation.x-this.currentRotation.x)*.05,this.currentRotation.y+=(this.targetRotation.y-this.currentRotation.y)*.05,this.orb&&(this.orb.rotation.x=this.currentRotation.x+a*this.config.rotationSpeed*.3,this.orb.rotation.y=this.currentRotation.y+a*this.config.rotationSpeed),this.glowMesh&&(this.glowMesh.rotation.x=this.currentRotation.x+a*this.config.rotationSpeed*.3,this.glowMesh.rotation.y=this.currentRotation.y+a*this.config.rotationSpeed),this.renderer.render(this.scene,this.camera)},this.handleResize=()=>{const a=this.container.clientWidth*this.canvasPadding,c=this.container.clientHeight*this.canvasPadding;this.camera.aspect=a/c,this.camera.updateProjectionMatrix(),this.renderer.setSize(a,c)},this.handleMouseMove=a=>{const c=this.container.getBoundingClientRect(),l=(a.clientX-c.left)/c.width*2-1,d=-((a.clientY-c.top)/c.height)*2+1;this.targetRotation.x=d*.3,this.targetRotation.y=l*.3},this.handleMouseLeave=()=>{this.targetRotation.x=0,this.targetRotation.y=0},this.container=e,this.config={...oM,...t},this.clock=new Nm,this.scene=new Mm;const n=e.clientWidth*this.canvasPadding,s=e.clientHeight*this.canvasPadding,r=n/s;this.camera=new Tn(45,r,.1,100),this.camera.position.z=9,this.renderer=new ug({antialias:!0,alpha:!0,powerPreference:"high-performance"}),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(n,s),this.renderer.setClearColor(0,0);const o=this.renderer.domElement;o.style.position="absolute",o.style.left="50%",o.style.top="50%",o.style.transform="translate(-50%, -50%)",o.style.pointerEvents="none",e.appendChild(o),this.createOrb(),window.addEventListener("resize",this.handleResize),e.addEventListener("mousemove",this.handleMouseMove),e.addEventListener("mouseleave",this.handleMouseLeave)}createOrb(){const e={...As,...this.config.colors},t=new Qd(this.config.size,this.config.segments/4);this.orbMaterial=new tn({vertexShader:iM,fragmentShader:sM,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 Fe(e.primary)},uColorSecondary:{value:new Fe(e.secondary)},uColorAccent:{value:new Fe(e.accent)},uColorDepth:{value:new Fe(e.depth||As.depth)},uColorHighlight:{value:new Fe(e.highlight||As.highlight)},uFresnelPower:{value:this.config.fresnelPower},uGlowIntensity:{value:this.config.glowIntensity},uColorContrast:{value:this.config.colorContrast}},transparent:!0,side:_i}),this.orb=new xn(t,this.orbMaterial),this.scene.add(this.orb);const n=new yr(this.config.size,64,64);this.glowMaterial=new tn({vertexShader:rM,fragmentShader:aM,uniforms:{uTime:{value:0},uAudioLevel:{value:0},uGlowColor:{value:new Fe(e.glow)},uGlowIntensity:{value:this.config.glowIntensity*.6},uPulseSpeed:{value:2}},transparent:!0,side:nn,blending:Ji,depthWrite:!1}),this.glowMesh=new xn(n,this.glowMaterial),this.scene.add(this.glowMesh)}updateAudio(e){const t=this.config.audioSmoothing;this.audioValues.bass+=(e.bass-this.audioValues.bass)*t,this.audioValues.mid+=(e.mid-this.audioValues.mid)*t,this.audioValues.treble+=(e.treble-this.audioValues.treble)*t,this.audioValues.level+=(e.level-this.audioValues.level)*t}setSimulatedAudio(e,t,n,s){const r=this.config.audioSmoothing;this.audioValues.bass+=(e-this.audioValues.bass)*r,this.audioValues.mid+=(t-this.audioValues.mid)*r,this.audioValues.treble+=(n-this.audioValues.treble)*r,this.audioValues.level+=(s-this.audioValues.level)*r}setActive(e){this.isActive=e}setColors(e){const t={...As,...this.config.colors,...e};this.orbMaterial&&(this.orbMaterial.uniforms.uColorPrimary.value.set(t.primary),this.orbMaterial.uniforms.uColorSecondary.value.set(t.secondary),this.orbMaterial.uniforms.uColorAccent.value.set(t.accent),this.orbMaterial.uniforms.uColorDepth.value.set(t.depth||As.depth),this.orbMaterial.uniforms.uColorHighlight.value.set(t.highlight||As.highlight)),this.glowMaterial&&this.glowMaterial.uniforms.uGlowColor.value.set(t.glow)}setGlowSettings(e,t){this.config.glowIntensity=e,this.config.idleGlowMultiplier=t}start(){this.animationId===null&&(this.clock.start(),this.animate())}stop(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}getCanvas(){return this.renderer.domElement}destroy(){this.stop(),window.removeEventListener("resize",this.handleResize),this.container.removeEventListener("mousemove",this.handleMouseMove),this.container.removeEventListener("mouseleave",this.handleMouseLeave),this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb)),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh)),this.orbMaterial&&this.orbMaterial.dispose(),this.glowMaterial&&this.glowMaterial.dispose(),this.renderer.dispose(),this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement)}}class fu{constructor(e={}){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.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0,this.smoothingFactor=.04,this.options={fftSize:e.fftSize??2048,smoothingTimeConstant:e.smoothingTimeConstant??.8,minDecibels:e.minDecibels??-90,maxDecibels:e.maxDecibels??-10}}async connectStream(e){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.source&&this.source.disconnect(),this.source=this.audioContext.createMediaStreamSource(e),this.setupMixerAndAnalyser(),this.source.connect(this.mixer)}async connectLocalStream(e){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.localSource&&this.localSource.disconnect(),this.localSource=this.audioContext.createMediaStreamSource(e),this.setupMixerAndAnalyser(),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(e){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.source&&this.source.disconnect();const t=this.audioContext.createMediaElementSource(e);this.analyser||(this.analyser=this.audioContext.createAnalyser()),this.analyser.fftSize=this.options.fftSize,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant,this.analyser.minDecibels=this.options.minDecibels,this.analyser.maxDecibels=this.options.maxDecibels,t.connect(this.analyser),this.analyser.connect(this.audioContext.destination),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize)}getAudioData(){if(!this.analyser)return{bass:0,mid:0,treble:0,level:0,waveform:new Float32Array(0),frequency:new Uint8Array(0)};this.analyser.getByteFrequencyData(this.frequencyData),this.analyser.getFloatTimeDomainData(this.waveformData);const{bass:e,mid:t,treble:n}=this.calculateFrequencyBands(),s=this.calculateOverallLevel();return this.smoothedBass+=(e-this.smoothedBass)*this.smoothingFactor,this.smoothedMid+=(t-this.smoothedMid)*this.smoothingFactor,this.smoothedTreble+=(n-this.smoothedTreble)*this.smoothingFactor,this.smoothedLevel+=(s-this.smoothedLevel)*this.smoothingFactor,{bass:this.smoothedBass,mid:this.smoothedMid,treble:this.smoothedTreble,level:this.smoothedLevel,waveform:this.waveformData,frequency:this.frequencyData}}calculateFrequencyBands(){if(!this.audioContext||this.frequencyData.length===0)return{bass:0,mid:0,treble:0};const e=this.audioContext.sampleRate,t=this.frequencyData.length,n=e/(t*2),s=Math.floor(250/n),r=Math.floor(2e3/n);let o=0,a=0,c=0;for(let h=0;h<t;h++){const f=this.frequencyData[h]/255;h<s?o+=f:h<r?a+=f:c+=f}const l=s>0?o/s:0,d=r-s>0?a/(r-s):0,u=t-r>0?c/(t-r):0;return{bass:Math.pow(l,.8),mid:Math.pow(d,.9),treble:Math.pow(u,1.1)}}calculateOverallLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let n=0;n<this.frequencyData.length;n++)e+=this.frequencyData[n];const t=e/this.frequencyData.length/255;return Math.pow(t,.8)}getPeakLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let t=0;t<this.frequencyData.length;t++)this.frequencyData[t]>e&&(e=this.frequencyData[t]);return e/255}isActive(){return this.audioContext!==null&&this.audioContext.state==="running"}disconnect(){this.source&&(this.source.disconnect(),this.source=null),this.localSource&&(this.localSource.disconnect(),this.localSource=null),this.mixer&&(this.mixer.disconnect(),this.mixer=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0}getAudioContext(){return this.audioContext}getAnalyser(){return this.analyser}}class $o{constructor(e={}){this.audioContext=null,this.config={enabled:!0,volume:.15,...e}}async ensureContext(){if(!this.config.enabled)return null;if(!this.audioContext)try{this.audioContext=new(window.AudioContext||window.webkitAudioContext)}catch{return console.warn("Web Audio API not supported"),null}return this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.audioContext}async prewarm(){await this.ensureContext()}createTone(e,t,n,s,r="sine"){const o=e.createOscillator(),a=e.createGain();o.type=r,o.frequency.setValueAtTime(t,n);const c=.05,l=.1,d=.7,u=.3;return a.gain.setValueAtTime(0,n),a.gain.linearRampToValueAtTime(this.config.volume,n+c),a.gain.linearRampToValueAtTime(this.config.volume*d,n+c+l),a.gain.setValueAtTime(this.config.volume*d,n+s-u),a.gain.linearRampToValueAtTime(0,n+s),o.connect(a),{oscillator:o,gain:a}}async playCallStartSound(){const e=await this.ensureContext();if(!e||typeof e.createGain!="function")return;const t=e.currentTime,n=e.createGain();n.gain.setValueAtTime(1,t),n.connect(e.destination);const{oscillator:s,gain:r}=this.createTone(e,880,t,.12,"sine");r.connect(n),s.start(t),s.stop(t+.12);const{oscillator:o,gain:a}=this.createTone(e,1046,t+.08,.15,"sine");a.connect(n),o.start(t+.08),o.stop(t+.23),setTimeout(()=>{try{s.disconnect()}catch{}try{o.disconnect()}catch{}},300)}async playCallEndSound(){const e=await this.ensureContext();if(!e||typeof e.createGain!="function")return;const t=e.currentTime,n=e.createGain();n.gain.setValueAtTime(1,t),n.connect(e.destination);const{oscillator:s,gain:r}=this.createTone(e,660,t,.2,"sine");r.connect(n),s.start(t),s.stop(t+.2),setTimeout(()=>{try{s.disconnect()}catch{}},250)}setConfig(e){this.config={...this.config,...e}}setEnabled(e){this.config.enabled=e}setVolume(e){this.config.volume=Math.max(0,Math.min(1,e))}getConfig(){return{...this.config}}isEnabled(){return this.config.enabled}destroy(){this.audioContext&&(this.audioContext.close(),this.audioContext=null)}}const di={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"}},ui={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"}};function cM(i,e="dark"){const t=e==="dark"?di:ui;return t[i]||t[Object.keys(t)[0]]}function lM(i="dark"){return Object.keys(i==="dark"?di:ui)}const Sr={default:{dark:{colors:di.default,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.indigo,glowIntensity:1.8,idleGlowMultiplier:1.2}},emerald:{dark:{colors:di.emerald,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.teal,glowIntensity:1.8,idleGlowMultiplier:1.2}},rose:{dark:{colors:di.rose,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.pink,glowIntensity:1.8,idleGlowMultiplier:1.2}},amber:{dark:{colors:di.amber,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.orange,glowIntensity:1.8,idleGlowMultiplier:1.2}},cyan:{dark:{colors:di.cyan,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},purple:{dark:{colors:di.purple,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.violet,glowIntensity:1.8,idleGlowMultiplier:1.2}},blue:{dark:{colors:di.blue,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ui.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}}},dM=Object.fromEntries(Object.entries(Sr).map(([i,e])=>[i,e.dark])),uM=Object.fromEntries(Object.entries(Sr).map(([i,e])=>[i,e.light]));function hg(){return typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function pa(i,e="auto"){const t=Sr[i]||Sr.default,n=e==="auto"?hg():e;return t[n]}function hM(){return Object.keys(Sr)}function fg(i,e,t="auto"){const n=pa(e,t);i.orbColors=n.colors,i.glowIntensity=n.glowIntensity,i.idleGlowMultiplier=n.idleGlowMultiplier}function fM(i,e){if(typeof window>"u")return()=>{};const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>{const s=t.matches?"dark":"light";fg(i,e,s)};return n(),t.addEventListener("change",n),()=>{t.removeEventListener("change",n)}}var pM=Object.defineProperty,mM=Object.getOwnPropertyDescriptor,Tt=(i,e,t,n)=>{for(var s=n>1?void 0:n?mM(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&pM(e,t,s),s};$.InlineCall=class extends Ui{constructor(){super(...arguments),this.callManager=new ro,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=xa(),this.animationId=null,this.callStatus="idle",this.microphoneEnabled=!1,this.buttonStartText="Try to call",this.buttonConnectingText="Connecting...",this.size=370,this.containerPadding=45,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=.8,this.noiseSpeed=.15,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=1,this.audioSmoothing=.03,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.15,this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1},this.handleStatusChange=e=>{var n,s,r,o,a;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(o=this.orbRenderer)==null||o.setActive(!1),(a=this.audioAnalyzer)==null||a.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&((e=this.soundManager)==null||e.prewarm(),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp())}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new $o({enabled:this.soundEnabled,volume:this.soundVolume}),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)}disconnectedCallback(){var e;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(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(e){var t,n;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume))}applyTheme(){if(this.theme){const e=pa(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new hu(e,{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 fu,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const t=performance.now()/1e3,n=Math.sin(t*.5)*.15+.15,s=Math.sin(t*.7+1)*.12+.12,r=Math.sin(t*.9+2)*.08+.08,o=(n+s+r)/3;this.orbRenderer.setSimulatedAudio(n,s,r,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer)return;const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Rt`
4472
4472
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="hanc-spinner">
4473
4473
  <circle
4474
4474
  cx="8"
@@ -4750,7 +4750,7 @@ void main() {
4750
4750
  display: inline-block;
4751
4751
  contain: layout style;
4752
4752
  }
4753
- `,Tt([pe({type:String,attribute:"agent-id"})],$.InlineCall.prototype,"agentId",2),Tt([pe({type:String,attribute:"voice-service-url"})],$.InlineCall.prototype,"voiceServiceUrl",2),Tt([Fi()],$.InlineCall.prototype,"callStatus",2),Tt([Fi()],$.InlineCall.prototype,"microphoneEnabled",2),Tt([pe({type:String,attribute:"button-start-text"})],$.InlineCall.prototype,"buttonStartText",2),Tt([pe({type:String,attribute:"button-connecting-text"})],$.InlineCall.prototype,"buttonConnectingText",2),Tt([pe({type:Number,attribute:"size"})],$.InlineCall.prototype,"size",2),Tt([pe({type:Number,attribute:"container-padding"})],$.InlineCall.prototype,"containerPadding",2),Tt([pe({type:String,attribute:"theme",reflect:!0})],$.InlineCall.prototype,"theme",2),Tt([pe({type:String,attribute:"theme-mode"})],$.InlineCall.prototype,"themeMode",2),Tt([pe({type:Object,attribute:"orb-colors"})],$.InlineCall.prototype,"orbColors",2),Tt([pe({type:Number,attribute:"glow-intensity"})],$.InlineCall.prototype,"glowIntensity",2),Tt([pe({type:Number,attribute:"idle-glow-multiplier"})],$.InlineCall.prototype,"idleGlowMultiplier",2),Tt([pe({type:Number,attribute:"morph-strength"})],$.InlineCall.prototype,"morphStrength",2),Tt([pe({type:Number,attribute:"noise-scale"})],$.InlineCall.prototype,"noiseScale",2),Tt([pe({type:Number,attribute:"noise-speed"})],$.InlineCall.prototype,"noiseSpeed",2),Tt([pe({type:Number,attribute:"fresnel-power"})],$.InlineCall.prototype,"fresnelPower",2),Tt([pe({type:Number,attribute:"rotation-speed"})],$.InlineCall.prototype,"rotationSpeed",2),Tt([pe({type:Number,attribute:"audio-reactivity"})],$.InlineCall.prototype,"audioReactivity",2),Tt([pe({type:Number,attribute:"audio-smoothing"})],$.InlineCall.prototype,"audioSmoothing",2),Tt([pe({type:Number,attribute:"idle-morph-multiplier"})],$.InlineCall.prototype,"idleMorphMultiplier",2),Tt([pe({type:Number,attribute:"color-contrast"})],$.InlineCall.prototype,"colorContrast",2),Tt([pe({type:Boolean,attribute:"sound-enabled"})],$.InlineCall.prototype,"soundEnabled",2),Tt([pe({type:Number,attribute:"sound-volume"})],$.InlineCall.prototype,"soundVolume",2),$.InlineCall=Tt([_a("hanc-ai-inline-call")],$.InlineCall);var gM=Object.defineProperty,vM=Object.getOwnPropertyDescriptor,Ct=(i,e,t,n)=>{for(var s=n>1?void 0:n?vM(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&gM(e,t,s),s};$.FloatingCall=class extends Ui{constructor(){super(...arguments),this.callManager=new ro,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=xa(),this.animationId=null,this.callStatus="idle",this.microphoneEnabled=!1,this.buttonStartText="Call",this.buttonConnectingText="Connecting...",this.position="bottom-right",this.size=120,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=.8,this.noiseSpeed=.15,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=1,this.audioSmoothing=.03,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.15,this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1},this.handleStatusChange=e=>{var n,s,r,o,a;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(o=this.orbRenderer)==null||o.setActive(!1),(a=this.audioAnalyzer)==null||a.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&((e=this.soundManager)==null||e.prewarm(),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp())}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new $o({enabled:this.soundEnabled,volume:this.soundVolume}),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)}disconnectedCallback(){var e;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(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(e){var t,n;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume))}applyTheme(){if(this.theme){const e=pa(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new hu(e,{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 fu,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const t=performance.now()/1e3,n=Math.sin(t*.5)*.15+.15,s=Math.sin(t*.7+1)*.12+.12,r=Math.sin(t*.9+2)*.08+.08,o=(n+s+r)/3;this.orbRenderer.setSimulatedAudio(n,s,r,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer)return;const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Rt`
4753
+ `,Tt([ce({type:String,attribute:"agent-id"})],$.InlineCall.prototype,"agentId",2),Tt([ce({type:String,attribute:"voice-service-url"})],$.InlineCall.prototype,"voiceServiceUrl",2),Tt([Fi()],$.InlineCall.prototype,"callStatus",2),Tt([Fi()],$.InlineCall.prototype,"microphoneEnabled",2),Tt([ce({type:String,attribute:"button-start-text"})],$.InlineCall.prototype,"buttonStartText",2),Tt([ce({type:String,attribute:"button-connecting-text"})],$.InlineCall.prototype,"buttonConnectingText",2),Tt([ce({type:Number,attribute:"size"})],$.InlineCall.prototype,"size",2),Tt([ce({type:Number,attribute:"container-padding"})],$.InlineCall.prototype,"containerPadding",2),Tt([ce({type:String,attribute:"theme",reflect:!0})],$.InlineCall.prototype,"theme",2),Tt([ce({type:String,attribute:"theme-mode"})],$.InlineCall.prototype,"themeMode",2),Tt([ce({type:Object,attribute:"orb-colors"})],$.InlineCall.prototype,"orbColors",2),Tt([ce({type:Number,attribute:"glow-intensity"})],$.InlineCall.prototype,"glowIntensity",2),Tt([ce({type:Number,attribute:"idle-glow-multiplier"})],$.InlineCall.prototype,"idleGlowMultiplier",2),Tt([ce({type:Number,attribute:"morph-strength"})],$.InlineCall.prototype,"morphStrength",2),Tt([ce({type:Number,attribute:"noise-scale"})],$.InlineCall.prototype,"noiseScale",2),Tt([ce({type:Number,attribute:"noise-speed"})],$.InlineCall.prototype,"noiseSpeed",2),Tt([ce({type:Number,attribute:"fresnel-power"})],$.InlineCall.prototype,"fresnelPower",2),Tt([ce({type:Number,attribute:"rotation-speed"})],$.InlineCall.prototype,"rotationSpeed",2),Tt([ce({type:Number,attribute:"audio-reactivity"})],$.InlineCall.prototype,"audioReactivity",2),Tt([ce({type:Number,attribute:"audio-smoothing"})],$.InlineCall.prototype,"audioSmoothing",2),Tt([ce({type:Number,attribute:"idle-morph-multiplier"})],$.InlineCall.prototype,"idleMorphMultiplier",2),Tt([ce({type:Number,attribute:"color-contrast"})],$.InlineCall.prototype,"colorContrast",2),Tt([ce({type:Boolean,attribute:"sound-enabled"})],$.InlineCall.prototype,"soundEnabled",2),Tt([ce({type:Number,attribute:"sound-volume"})],$.InlineCall.prototype,"soundVolume",2),$.InlineCall=Tt([_a("hanc-ai-inline-call")],$.InlineCall);var gM=Object.defineProperty,vM=Object.getOwnPropertyDescriptor,Ct=(i,e,t,n)=>{for(var s=n>1?void 0:n?vM(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&gM(e,t,s),s};$.FloatingCall=class extends Ui{constructor(){super(...arguments),this.callManager=new ro,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=xa(),this.animationId=null,this.callStatus="idle",this.microphoneEnabled=!1,this.buttonStartText="Call",this.buttonConnectingText="Connecting...",this.position="bottom-right",this.size=120,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=.8,this.noiseSpeed=.15,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=1,this.audioSmoothing=.03,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.15,this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1},this.handleStatusChange=e=>{var n,s,r,o,a;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(o=this.orbRenderer)==null||o.setActive(!1),(a=this.audioAnalyzer)==null||a.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&((e=this.soundManager)==null||e.prewarm(),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp())}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new $o({enabled:this.soundEnabled,volume:this.soundVolume}),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)}disconnectedCallback(){var e;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(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(e){var t,n;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume))}applyTheme(){if(this.theme){const e=pa(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new hu(e,{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 fu,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const t=performance.now()/1e3,n=Math.sin(t*.5)*.15+.15,s=Math.sin(t*.7+1)*.12+.12,r=Math.sin(t*.9+2)*.08+.08,o=(n+s+r)/3;this.orbRenderer.setSimulatedAudio(n,s,r,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer)return;const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Rt`
4754
4754
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="hanc-spinner">
4755
4755
  <circle
4756
4756
  cx="8"
@@ -5017,7 +5017,7 @@ void main() {
5017
5017
  :host {
5018
5018
  display: block;
5019
5019
  }
5020
- `,Ct([pe({type:String,attribute:"agent-id"})],$.FloatingCall.prototype,"agentId",2),Ct([pe({type:String,attribute:"voice-service-url"})],$.FloatingCall.prototype,"voiceServiceUrl",2),Ct([Fi()],$.FloatingCall.prototype,"callStatus",2),Ct([Fi()],$.FloatingCall.prototype,"microphoneEnabled",2),Ct([pe({type:String,attribute:"button-start-text"})],$.FloatingCall.prototype,"buttonStartText",2),Ct([pe({type:String,attribute:"button-connecting-text"})],$.FloatingCall.prototype,"buttonConnectingText",2),Ct([pe({type:String,attribute:"position"})],$.FloatingCall.prototype,"position",2),Ct([pe({type:Number,attribute:"size"})],$.FloatingCall.prototype,"size",2),Ct([pe({type:String,attribute:"theme"})],$.FloatingCall.prototype,"theme",2),Ct([pe({type:String,attribute:"theme-mode"})],$.FloatingCall.prototype,"themeMode",2),Ct([pe({type:Object,attribute:"orb-colors"})],$.FloatingCall.prototype,"orbColors",2),Ct([pe({type:Number,attribute:"glow-intensity"})],$.FloatingCall.prototype,"glowIntensity",2),Ct([pe({type:Number,attribute:"idle-glow-multiplier"})],$.FloatingCall.prototype,"idleGlowMultiplier",2),Ct([pe({type:Number,attribute:"morph-strength"})],$.FloatingCall.prototype,"morphStrength",2),Ct([pe({type:Number,attribute:"noise-scale"})],$.FloatingCall.prototype,"noiseScale",2),Ct([pe({type:Number,attribute:"noise-speed"})],$.FloatingCall.prototype,"noiseSpeed",2),Ct([pe({type:Number,attribute:"fresnel-power"})],$.FloatingCall.prototype,"fresnelPower",2),Ct([pe({type:Number,attribute:"rotation-speed"})],$.FloatingCall.prototype,"rotationSpeed",2),Ct([pe({type:Number,attribute:"audio-reactivity"})],$.FloatingCall.prototype,"audioReactivity",2),Ct([pe({type:Number,attribute:"audio-smoothing"})],$.FloatingCall.prototype,"audioSmoothing",2),Ct([pe({type:Number,attribute:"idle-morph-multiplier"})],$.FloatingCall.prototype,"idleMorphMultiplier",2),Ct([pe({type:Number,attribute:"color-contrast"})],$.FloatingCall.prototype,"colorContrast",2),Ct([pe({type:Boolean,attribute:"sound-enabled"})],$.FloatingCall.prototype,"soundEnabled",2),Ct([pe({type:Number,attribute:"sound-volume"})],$.FloatingCall.prototype,"soundVolume",2),$.FloatingCall=Ct([_a("hanc-ai-floating-call")],$.FloatingCall);var yM=Object.defineProperty,bM=Object.getOwnPropertyDescriptor,Et=(i,e,t,n)=>{for(var s=n>1?void 0:n?bM(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&yM(e,t,s),s};$.PillCall=class extends Ui{constructor(){super(...arguments),this.callManager=new ro,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=xa(),this.animationId=null,this.callStatus="idle",this.microphoneEnabled=!1,this.buttonStartText="Talk to AI Agent",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.orbSize=48,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=.8,this.noiseSpeed=.15,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=1,this.audioSmoothing=.03,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.15,this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1},this.handleStatusChange=e=>{var n,s,r,o,a;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(o=this.orbRenderer)==null||o.setActive(!1),(a=this.audioAnalyzer)==null||a.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&((e=this.soundManager)==null||e.prewarm(),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp())}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new $o({enabled:this.soundEnabled,volume:this.soundVolume}),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)}disconnectedCallback(){var e;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(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(e){var t,n;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume))}applyTheme(){if(this.theme){const e=pa(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new hu(e,{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 fu,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const t=performance.now()/1e3,n=Math.sin(t*.5)*.15+.15,s=Math.sin(t*.7+1)*.12+.12,r=Math.sin(t*.9+2)*.08+.08,o=(n+s+r)/3;this.orbRenderer.setSimulatedAudio(n,s,r,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer)return;const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Rt`
5020
+ `,Ct([ce({type:String,attribute:"agent-id"})],$.FloatingCall.prototype,"agentId",2),Ct([ce({type:String,attribute:"voice-service-url"})],$.FloatingCall.prototype,"voiceServiceUrl",2),Ct([Fi()],$.FloatingCall.prototype,"callStatus",2),Ct([Fi()],$.FloatingCall.prototype,"microphoneEnabled",2),Ct([ce({type:String,attribute:"button-start-text"})],$.FloatingCall.prototype,"buttonStartText",2),Ct([ce({type:String,attribute:"button-connecting-text"})],$.FloatingCall.prototype,"buttonConnectingText",2),Ct([ce({type:String,attribute:"position"})],$.FloatingCall.prototype,"position",2),Ct([ce({type:Number,attribute:"size"})],$.FloatingCall.prototype,"size",2),Ct([ce({type:String,attribute:"theme"})],$.FloatingCall.prototype,"theme",2),Ct([ce({type:String,attribute:"theme-mode"})],$.FloatingCall.prototype,"themeMode",2),Ct([ce({type:Object,attribute:"orb-colors"})],$.FloatingCall.prototype,"orbColors",2),Ct([ce({type:Number,attribute:"glow-intensity"})],$.FloatingCall.prototype,"glowIntensity",2),Ct([ce({type:Number,attribute:"idle-glow-multiplier"})],$.FloatingCall.prototype,"idleGlowMultiplier",2),Ct([ce({type:Number,attribute:"morph-strength"})],$.FloatingCall.prototype,"morphStrength",2),Ct([ce({type:Number,attribute:"noise-scale"})],$.FloatingCall.prototype,"noiseScale",2),Ct([ce({type:Number,attribute:"noise-speed"})],$.FloatingCall.prototype,"noiseSpeed",2),Ct([ce({type:Number,attribute:"fresnel-power"})],$.FloatingCall.prototype,"fresnelPower",2),Ct([ce({type:Number,attribute:"rotation-speed"})],$.FloatingCall.prototype,"rotationSpeed",2),Ct([ce({type:Number,attribute:"audio-reactivity"})],$.FloatingCall.prototype,"audioReactivity",2),Ct([ce({type:Number,attribute:"audio-smoothing"})],$.FloatingCall.prototype,"audioSmoothing",2),Ct([ce({type:Number,attribute:"idle-morph-multiplier"})],$.FloatingCall.prototype,"idleMorphMultiplier",2),Ct([ce({type:Number,attribute:"color-contrast"})],$.FloatingCall.prototype,"colorContrast",2),Ct([ce({type:Boolean,attribute:"sound-enabled"})],$.FloatingCall.prototype,"soundEnabled",2),Ct([ce({type:Number,attribute:"sound-volume"})],$.FloatingCall.prototype,"soundVolume",2),$.FloatingCall=Ct([_a("hanc-ai-floating-call")],$.FloatingCall);var yM=Object.defineProperty,bM=Object.getOwnPropertyDescriptor,Et=(i,e,t,n)=>{for(var s=n>1?void 0:n?bM(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&yM(e,t,s),s};$.PillCall=class extends Ui{constructor(){super(...arguments),this.callManager=new ro,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=xa(),this.animationId=null,this.callStatus="idle",this.microphoneEnabled=!1,this.buttonStartText="Talk to AI Agent",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.orbSize=48,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=.8,this.noiseSpeed=.15,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=1,this.audioSmoothing=.03,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.15,this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1},this.handleStatusChange=e=>{var n,s,r,o,a;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),setTimeout(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(o=this.orbRenderer)==null||o.setActive(!1),(a=this.audioAnalyzer)==null||a.disconnect(),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&((e=this.soundManager)==null||e.prewarm(),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp())}}connectedCallback(){super.connectedCallback(),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new $o({enabled:this.soundEnabled,volume:this.soundVolume}),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)}disconnectedCallback(){var e;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(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}firstUpdated(){this.applyTheme(),this.initializeOrb()}updated(e){var t,n;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume))}applyTheme(){if(this.theme){const e=pa(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new hu(e,{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 fu,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{if(this.callStatus!=="idle"||!this.orbRenderer)return;const t=performance.now()/1e3,n=Math.sin(t*.5)*.15+.15,s=Math.sin(t*.7+1)*.12+.12,r=Math.sin(t*.9+2)*.08+.08,o=(n+s+r)/3;this.orbRenderer.setSimulatedAudio(n,s,r,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer)return;const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Rt`
5021
5021
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="hanc-spinner">
5022
5022
  <circle
5023
5023
  cx="8"
@@ -5206,7 +5206,7 @@ void main() {
5206
5206
  display: inline-block;
5207
5207
  contain: layout style;
5208
5208
  }
5209
- `,Et([pe({type:String,attribute:"agent-id"})],$.PillCall.prototype,"agentId",2),Et([pe({type:String,attribute:"voice-service-url"})],$.PillCall.prototype,"voiceServiceUrl",2),Et([Fi()],$.PillCall.prototype,"callStatus",2),Et([Fi()],$.PillCall.prototype,"microphoneEnabled",2),Et([pe({type:String,attribute:"button-start-text"})],$.PillCall.prototype,"buttonStartText",2),Et([pe({type:String,attribute:"button-connecting-text"})],$.PillCall.prototype,"buttonConnectingText",2),Et([pe({type:String,attribute:"button-end-text"})],$.PillCall.prototype,"buttonEndText",2),Et([pe({type:Number,attribute:"orb-size"})],$.PillCall.prototype,"orbSize",2),Et([pe({type:String,attribute:"theme"})],$.PillCall.prototype,"theme",2),Et([pe({type:String,attribute:"theme-mode"})],$.PillCall.prototype,"themeMode",2),Et([pe({type:Object,attribute:"orb-colors"})],$.PillCall.prototype,"orbColors",2),Et([pe({type:Number,attribute:"glow-intensity"})],$.PillCall.prototype,"glowIntensity",2),Et([pe({type:Number,attribute:"idle-glow-multiplier"})],$.PillCall.prototype,"idleGlowMultiplier",2),Et([pe({type:Number,attribute:"morph-strength"})],$.PillCall.prototype,"morphStrength",2),Et([pe({type:Number,attribute:"noise-scale"})],$.PillCall.prototype,"noiseScale",2),Et([pe({type:Number,attribute:"noise-speed"})],$.PillCall.prototype,"noiseSpeed",2),Et([pe({type:Number,attribute:"fresnel-power"})],$.PillCall.prototype,"fresnelPower",2),Et([pe({type:Number,attribute:"rotation-speed"})],$.PillCall.prototype,"rotationSpeed",2),Et([pe({type:Number,attribute:"audio-reactivity"})],$.PillCall.prototype,"audioReactivity",2),Et([pe({type:Number,attribute:"audio-smoothing"})],$.PillCall.prototype,"audioSmoothing",2),Et([pe({type:Number,attribute:"idle-morph-multiplier"})],$.PillCall.prototype,"idleMorphMultiplier",2),Et([pe({type:Number,attribute:"color-contrast"})],$.PillCall.prototype,"colorContrast",2),Et([pe({type:Boolean,attribute:"sound-enabled"})],$.PillCall.prototype,"soundEnabled",2),Et([pe({type:Number,attribute:"sound-volume"})],$.PillCall.prototype,"soundVolume",2),$.PillCall=Et([_a("hanc-ai-pill-call")],$.PillCall);const _M={core:"#ffffff",coreGlow:"#a855f7",lightning:"#c084fc",shell:"#1e1b2e",shellInner:"#0f0d17",particles:"#e9d5ff",pulseNeutral:"#a855f7",pulseJoy:"#22c55e",pulseThinking:"#3b82f6",pulseInterrupted:"#ef4444"},pu={idle:{shellOpen:0,coreIntensity:.6,lightningCount:2,lightningIntensity:.3,particleSpeed:.3,coreScale:.7},listening:{shellOpen:.15,coreIntensity:.8,lightningCount:4,lightningIntensity:.5,particleSpeed:.5,coreScale:.8},thinking:{shellOpen:.25,coreIntensity:1,lightningCount:6,lightningIntensity:.7,particleSpeed:.7,coreScale:.9},speaking:{shellOpen:.4,coreIntensity:1.2,lightningCount:10,lightningIntensity:1,particleSpeed:1,coreScale:1}};class pg{constructor(e,t={}){this.shellSegments=[],this.coreInner=null,this.coreOuter=null,this.coreGlow=null,this.pulseRings=[],this.particles=null,this.particlePositions=null,this.particleVelocities=null,this.animationId=null,this._currentState="idle",this._currentEmotion="neutral",this.targetConfig={...pu.idle},this.currentConfig={...pu.idle},this.targetAudioLevel=0,this.currentAudioLevel=0,this.audioVelocity=0,this.targetPulseColor=new Fe("#a855f7"),this.currentPulseColor=new Fe("#a855f7"),this.targetRotation={x:0,y:0},this.currentRotation={x:0,y:0},this.time=0,this.animate=()=>{this.animationId=requestAnimationFrame(this.animate);const n=this.clock.getDelta();this.time+=n;const s=.05;this.currentConfig.coreIntensity+=(this.targetConfig.coreIntensity-this.currentConfig.coreIntensity)*s,this.currentConfig.lightningCount+=(this.targetConfig.lightningCount-this.currentConfig.lightningCount)*s,this.currentConfig.lightningIntensity+=(this.targetConfig.lightningIntensity-this.currentConfig.lightningIntensity)*s,this.currentConfig.particleSpeed+=(this.targetConfig.particleSpeed-this.currentConfig.particleSpeed)*s,this.currentConfig.coreScale+=(this.targetConfig.coreScale-this.currentConfig.coreScale)*s;const r=.08,o=.75,a=(this.targetAudioLevel-this.currentAudioLevel)*r;this.audioVelocity+=a,this.audioVelocity*=o,this.currentAudioLevel+=this.audioVelocity,this.currentAudioLevel=Math.max(0,Math.min(1,this.currentAudioLevel));const c=1+this.currentAudioLevel*.4;if(this.coreLight&&(this.coreLight.intensity=3+this.currentConfig.coreIntensity*2*c),this.coreInner){const l=this.coreInner.material;l.uniforms&&(l.uniforms.uTime.value=this.time,l.uniforms.uIntensity.value=this.currentConfig.coreIntensity*c);const d=this.currentConfig.coreScale*.9*c;this.coreInner.scale.setScalar(d)}if(this.coreOuter){const l=this.coreOuter.material;l.uniforms.uTime.value=this.time,l.uniforms.uIntensity.value=this.currentConfig.coreIntensity*c;const d=this.currentConfig.coreScale*c;this.coreOuter.scale.setScalar(d)}if(this.coreGlow){const l=this.coreGlow.material;l.uniforms.uTime.value=this.time,l.uniforms.uIntensity.value=this.currentConfig.coreIntensity*.7*c;const d=1+Math.sin(this.time*1.5)*.03*this.currentConfig.coreIntensity;this.coreGlow.scale.setScalar(d)}this.updateParticles(n),this.currentPulseColor.lerp(this.targetPulseColor,.08);for(const l of this.pulseRings){const d=l.material;d.uniforms.uTime.value=this.time,d.uniforms.uAudioLevel.value=this.currentAudioLevel,d.uniforms.uIntensity.value=this.currentConfig.coreIntensity,d.uniforms.uColor.value.copy(this.currentPulseColor);const u=l.ringConfig;l.rotation.y+=.003*u.speed,l.rotation.x=u.tiltX+Math.sin(this.time*.5+u.phase)*.1,l.rotation.z=u.tiltZ+Math.cos(this.time*.4+u.phase)*.08}this.currentRotation.x+=(this.targetRotation.x-this.currentRotation.x)*.05,this.currentRotation.y+=(this.targetRotation.y-this.currentRotation.y)*.05,this.scene.rotation.x=this.currentRotation.x,this.scene.rotation.y=this.currentRotation.y,this.renderer.render(this.scene,this.camera)},this.handleResize=()=>{const n=this.container.clientWidth*this.config.canvasPadding,s=this.container.clientHeight*this.config.canvasPadding;this.camera.aspect=n/s,this.camera.updateProjectionMatrix(),this.renderer.setSize(n,s)},this.handleMouseMove=n=>{const s=this.container.getBoundingClientRect(),r=(n.clientX-s.left)/s.width*2-1,o=-((n.clientY-s.top)/s.height)*2+1;this.targetRotation.x=o*.3,this.targetRotation.y=r*.3},this.handleMouseLeave=()=>{this.targetRotation.x=0,this.targetRotation.y=0},this.container=e,this.config={size:t.size??1,shellSegments:t.shellSegments??6,colors:t.colors??{},canvasPadding:t.canvasPadding??2},this.colors={..._M,...t.colors},this.clock=new Nm,this.initScene(),this.createShell(),this.createCore(),this.createParticles(),window.addEventListener("resize",this.handleResize),e.addEventListener("mousemove",this.handleMouseMove),e.addEventListener("mouseleave",this.handleMouseLeave)}initScene(){this.scene=new Mm;const e=this.container.clientWidth*this.config.canvasPadding,t=this.container.clientHeight*this.config.canvasPadding;this.camera=new xn(50,e/t,.1,100),this.camera.position.z=3.5,this.renderer=new ug({antialias:!0,alpha:!0,powerPreference:"high-performance"}),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(e,t),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",this.container.appendChild(n)}createShell(){const e=new zS(1710638,.6);this.scene.add(e);const t=new iu(16777215,1);t.position.set(3,4,5),this.scene.add(t);const n=new iu(9133302,.4);n.position.set(-3,2,3),this.scene.add(n);const s=new iu(6514417,.5);s.position.set(0,-2,-4),this.scene.add(s);const r=new FS(new Fe(this.colors.coreGlow),4,6);r.position.set(0,0,0),this.scene.add(r),this.coreLight=r}createCore(){const e=this.config.size*.3,t=new yr(e*.5,64,64),n=new en({uniforms:{uTime:{value:0},uIntensity:{value:1}},vertexShader:`
5209
+ `,Et([ce({type:String,attribute:"agent-id"})],$.PillCall.prototype,"agentId",2),Et([ce({type:String,attribute:"voice-service-url"})],$.PillCall.prototype,"voiceServiceUrl",2),Et([Fi()],$.PillCall.prototype,"callStatus",2),Et([Fi()],$.PillCall.prototype,"microphoneEnabled",2),Et([ce({type:String,attribute:"button-start-text"})],$.PillCall.prototype,"buttonStartText",2),Et([ce({type:String,attribute:"button-connecting-text"})],$.PillCall.prototype,"buttonConnectingText",2),Et([ce({type:String,attribute:"button-end-text"})],$.PillCall.prototype,"buttonEndText",2),Et([ce({type:Number,attribute:"orb-size"})],$.PillCall.prototype,"orbSize",2),Et([ce({type:String,attribute:"theme"})],$.PillCall.prototype,"theme",2),Et([ce({type:String,attribute:"theme-mode"})],$.PillCall.prototype,"themeMode",2),Et([ce({type:Object,attribute:"orb-colors"})],$.PillCall.prototype,"orbColors",2),Et([ce({type:Number,attribute:"glow-intensity"})],$.PillCall.prototype,"glowIntensity",2),Et([ce({type:Number,attribute:"idle-glow-multiplier"})],$.PillCall.prototype,"idleGlowMultiplier",2),Et([ce({type:Number,attribute:"morph-strength"})],$.PillCall.prototype,"morphStrength",2),Et([ce({type:Number,attribute:"noise-scale"})],$.PillCall.prototype,"noiseScale",2),Et([ce({type:Number,attribute:"noise-speed"})],$.PillCall.prototype,"noiseSpeed",2),Et([ce({type:Number,attribute:"fresnel-power"})],$.PillCall.prototype,"fresnelPower",2),Et([ce({type:Number,attribute:"rotation-speed"})],$.PillCall.prototype,"rotationSpeed",2),Et([ce({type:Number,attribute:"audio-reactivity"})],$.PillCall.prototype,"audioReactivity",2),Et([ce({type:Number,attribute:"audio-smoothing"})],$.PillCall.prototype,"audioSmoothing",2),Et([ce({type:Number,attribute:"idle-morph-multiplier"})],$.PillCall.prototype,"idleMorphMultiplier",2),Et([ce({type:Number,attribute:"color-contrast"})],$.PillCall.prototype,"colorContrast",2),Et([ce({type:Boolean,attribute:"sound-enabled"})],$.PillCall.prototype,"soundEnabled",2),Et([ce({type:Number,attribute:"sound-volume"})],$.PillCall.prototype,"soundVolume",2),$.PillCall=Et([_a("hanc-ai-pill-call")],$.PillCall);const _M={core:"#ffffff",coreGlow:"#a855f7",lightning:"#c084fc",shell:"#1e1b2e",shellInner:"#0f0d17",particles:"#e9d5ff",pulseNeutral:"#a855f7",pulseJoy:"#22c55e",pulseThinking:"#3b82f6",pulseInterrupted:"#ef4444",stateIdle:"#a855f7",stateListening:"#facc15",stateThinking:"#f97316",stateSpeaking:"#22c55e"},pu={idle:{shellOpen:0,coreIntensity:.6,lightningCount:2,lightningIntensity:.3,particleSpeed:.3,coreScale:.7},listening:{shellOpen:.15,coreIntensity:.8,lightningCount:4,lightningIntensity:.5,particleSpeed:.5,coreScale:.8},thinking:{shellOpen:.25,coreIntensity:1,lightningCount:6,lightningIntensity:.7,particleSpeed:.7,coreScale:.9},speaking:{shellOpen:.4,coreIntensity:1.2,lightningCount:10,lightningIntensity:1,particleSpeed:1,coreScale:1}};class pg{constructor(e,t={}){this.shellSegments=[],this.coreInner=null,this.coreOuter=null,this.coreGlow=null,this.pulseRings=[],this.particles=null,this.particlePositions=null,this.particleVelocities=null,this.animationId=null,this._currentState="idle",this._currentEmotion="neutral",this.targetConfig={...pu.idle},this.currentConfig={...pu.idle},this.targetAudioLevel=0,this.currentAudioLevel=0,this.audioVelocity=0,this.targetPulseColor=new Fe("#a855f7"),this.currentPulseColor=new Fe("#a855f7"),this.targetRotation={x:0,y:0},this.currentRotation={x:0,y:0},this.time=0,this.animate=()=>{this.animationId=requestAnimationFrame(this.animate);const n=this.clock.getDelta();this.time+=n;const s=.05;this.currentConfig.coreIntensity+=(this.targetConfig.coreIntensity-this.currentConfig.coreIntensity)*s,this.currentConfig.lightningCount+=(this.targetConfig.lightningCount-this.currentConfig.lightningCount)*s,this.currentConfig.lightningIntensity+=(this.targetConfig.lightningIntensity-this.currentConfig.lightningIntensity)*s,this.currentConfig.particleSpeed+=(this.targetConfig.particleSpeed-this.currentConfig.particleSpeed)*s,this.currentConfig.coreScale+=(this.targetConfig.coreScale-this.currentConfig.coreScale)*s;const r=.08,o=.75,a=(this.targetAudioLevel-this.currentAudioLevel)*r;this.audioVelocity+=a,this.audioVelocity*=o,this.currentAudioLevel+=this.audioVelocity,this.currentAudioLevel=Math.max(0,Math.min(1,this.currentAudioLevel));const c=1+this.currentAudioLevel*.4;if(this.coreLight&&(this.coreLight.intensity=3+this.currentConfig.coreIntensity*2*c),this.coreInner){const l=this.coreInner.material;l.uniforms&&(l.uniforms.uTime.value=this.time,l.uniforms.uIntensity.value=this.currentConfig.coreIntensity*c);const d=this.currentConfig.coreScale*.9*c;this.coreInner.scale.setScalar(d)}if(this.coreOuter){const l=this.coreOuter.material;l.uniforms.uTime.value=this.time,l.uniforms.uIntensity.value=this.currentConfig.coreIntensity*c;const d=this.currentConfig.coreScale*c;this.coreOuter.scale.setScalar(d)}if(this.coreGlow){const l=this.coreGlow.material;l.uniforms.uTime.value=this.time,l.uniforms.uIntensity.value=this.currentConfig.coreIntensity*.7*c;const d=1+Math.sin(this.time*1.5)*.03*this.currentConfig.coreIntensity;this.coreGlow.scale.setScalar(d)}this.updateParticles(n),this.currentPulseColor.lerp(this.targetPulseColor,.08);for(const l of this.pulseRings){const d=l.material;d.uniforms.uTime.value=this.time,d.uniforms.uAudioLevel.value=this.currentAudioLevel,d.uniforms.uIntensity.value=this.currentConfig.coreIntensity,d.uniforms.uColor.value.copy(this.currentPulseColor);const u=l.ringConfig;l.rotation.y+=.003*u.speed,l.rotation.x=u.tiltX+Math.sin(this.time*.5+u.phase)*.1,l.rotation.z=u.tiltZ+Math.cos(this.time*.4+u.phase)*.08}this.currentRotation.x+=(this.targetRotation.x-this.currentRotation.x)*.05,this.currentRotation.y+=(this.targetRotation.y-this.currentRotation.y)*.05,this.scene.rotation.x=this.currentRotation.x,this.scene.rotation.y=this.currentRotation.y,this.renderer.render(this.scene,this.camera)},this.handleResize=()=>{const n=this.container.clientWidth*this.config.canvasPadding,s=this.container.clientHeight*this.config.canvasPadding;this.camera.aspect=n/s,this.camera.updateProjectionMatrix(),this.renderer.setSize(n,s)},this.handleMouseMove=n=>{const s=this.container.getBoundingClientRect(),r=(n.clientX-s.left)/s.width*2-1,o=-((n.clientY-s.top)/s.height)*2+1;this.targetRotation.x=o*.3,this.targetRotation.y=r*.3},this.handleMouseLeave=()=>{this.targetRotation.x=0,this.targetRotation.y=0},this.container=e,this.config={size:t.size??1,shellSegments:t.shellSegments??6,colors:t.colors??{},canvasPadding:t.canvasPadding??2},this.colors={..._M,...t.colors},this.clock=new Nm,this.initScene(),this.createShell(),this.createCore(),this.createParticles(),window.addEventListener("resize",this.handleResize),e.addEventListener("mousemove",this.handleMouseMove),e.addEventListener("mouseleave",this.handleMouseLeave)}initScene(){this.scene=new Mm;const e=this.container.clientWidth*this.config.canvasPadding,t=this.container.clientHeight*this.config.canvasPadding;this.camera=new Tn(50,e/t,.1,100),this.camera.position.z=3.5,this.renderer=new ug({antialias:!0,alpha:!0,powerPreference:"high-performance"}),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(e,t),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",this.container.appendChild(n)}createShell(){const e=new zS(1710638,.6);this.scene.add(e);const t=new iu(16777215,1);t.position.set(3,4,5),this.scene.add(t);const n=new iu(9133302,.4);n.position.set(-3,2,3),this.scene.add(n);const s=new iu(6514417,.5);s.position.set(0,-2,-4),this.scene.add(s);const r=new FS(new Fe(this.colors.coreGlow),4,6);r.position.set(0,0,0),this.scene.add(r),this.coreLight=r}createCore(){const e=this.config.size*.3,t=new yr(e*.5,64,64),n=new tn({uniforms:{uTime:{value:0},uIntensity:{value:1}},vertexShader:`
5210
5210
  varying vec3 vNormal;
5211
5211
  varying vec3 vPosition;
5212
5212
  void main() {
@@ -5233,7 +5233,7 @@ void main() {
5233
5233
 
5234
5234
  gl_FragColor = vec4(color, alpha);
5235
5235
  }
5236
- `,transparent:!0,blending:Ji,depthWrite:!1});this.coreInner=new Sn(t,n),this.scene.add(this.coreInner);const s=new yr(e,32,32),r=new en({uniforms:{uTime:{value:0},uIntensity:{value:.8},uColorInner:{value:new Fe(16777215)},uColorOuter:{value:new Fe(this.colors.coreGlow)}},vertexShader:`
5236
+ `,transparent:!0,blending:Ji,depthWrite:!1});this.coreInner=new xn(t,n),this.scene.add(this.coreInner);const s=new yr(e,32,32),r=new tn({uniforms:{uTime:{value:0},uIntensity:{value:.8},uColorInner:{value:new Fe(16777215)},uColorOuter:{value:new Fe(this.colors.coreGlow)}},vertexShader:`
5237
5237
  varying vec3 vNormal;
5238
5238
  varying vec3 vPosition;
5239
5239
  uniform float uTime;
@@ -5320,7 +5320,7 @@ void main() {
5320
5320
  float alpha = 0.9 - fresnel * 0.3;
5321
5321
  gl_FragColor = vec4(color, alpha);
5322
5322
  }
5323
- `,transparent:!0,blending:Ji,depthWrite:!1});this.coreOuter=new Sn(s,r),this.scene.add(this.coreOuter);const o=new yr(e*2.2,64,64),a=new en({uniforms:{uTime:{value:0},uIntensity:{value:.5},uColor:{value:new Fe(this.colors.coreGlow)},uColorSecondary:{value:new Fe("#6366f1")}},vertexShader:`
5323
+ `,transparent:!0,blending:Ji,depthWrite:!1});this.coreOuter=new xn(s,r),this.scene.add(this.coreOuter);const o=new yr(e*2.2,64,64),a=new tn({uniforms:{uTime:{value:0},uIntensity:{value:.5},uColor:{value:new Fe(this.colors.coreGlow)},uColorSecondary:{value:new Fe("#6366f1")}},vertexShader:`
5324
5324
  varying vec3 vNormal;
5325
5325
  varying vec3 vPosition;
5326
5326
  varying vec3 vWorldPos;
@@ -5416,7 +5416,7 @@ void main() {
5416
5416
 
5417
5417
  gl_FragColor = vec4(color * (1.0 + fresnel * 0.3), alpha);
5418
5418
  }
5419
- `,transparent:!0,blending:Ji,depthWrite:!1,side:tn});this.coreGlow=new Sn(o,a),this.scene.add(this.coreGlow),this.createPulseLine()}createPulseLine(){const e=this.config.size*.3,t=6,n=[{radius:e*1.2,tiltX:.3,tiltZ:.1,speed:1,phase:0},{radius:e*1.5,tiltX:-.2,tiltZ:.4,speed:.8,phase:Math.PI*.5},{radius:e*1.3,tiltX:Math.PI*.5,tiltZ:.2,speed:.9,phase:Math.PI},{radius:e*1.4,tiltX:Math.PI*.5,tiltZ:-.4,speed:1.1,phase:Math.PI*1.5},{radius:e*1.35,tiltX:Math.PI*.25,tiltZ:Math.PI*.25,speed:.7,phase:Math.PI*.75},{radius:e*1.25,tiltX:-Math.PI*.3,tiltZ:Math.PI*.35,speed:1,phase:Math.PI*1.25}];for(let s=0;s<t;s++){const r=n[s],o=100,a=[];for(let h=0;h<=o;h++){const f=h/o*Math.PI*2;a.push(new U(Math.cos(f)*r.radius,0,Math.sin(f)*r.radius))}const c=new hn().setFromPoints(a),l=new Float32Array(o+1);for(let h=0;h<=o;h++)l[h]=h/o;c.setAttribute("aIndex",new _n(l,1));const d=new en({uniforms:{uTime:{value:0},uColor:{value:new Fe(this.colors.pulseNeutral)},uIntensity:{value:1},uAudioLevel:{value:0},uSpeed:{value:r.speed},uPhase:{value:r.phase},uRadius:{value:r.radius}},vertexShader:`
5419
+ `,transparent:!0,blending:Ji,depthWrite:!1,side:nn});this.coreGlow=new xn(o,a),this.scene.add(this.coreGlow),this.createPulseLine()}createPulseLine(){const e=this.config.size*.3,t=6,n=[{radius:e*1.2,tiltX:.3,tiltZ:.1,speed:1,phase:0},{radius:e*1.5,tiltX:-.2,tiltZ:.4,speed:.8,phase:Math.PI*.5},{radius:e*1.3,tiltX:Math.PI*.5,tiltZ:.2,speed:.9,phase:Math.PI},{radius:e*1.4,tiltX:Math.PI*.5,tiltZ:-.4,speed:1.1,phase:Math.PI*1.5},{radius:e*1.35,tiltX:Math.PI*.25,tiltZ:Math.PI*.25,speed:.7,phase:Math.PI*.75},{radius:e*1.25,tiltX:-Math.PI*.3,tiltZ:Math.PI*.35,speed:1,phase:Math.PI*1.25}];for(let s=0;s<t;s++){const r=n[s],o=100,a=[];for(let h=0;h<=o;h++){const f=h/o*Math.PI*2;a.push(new U(Math.cos(f)*r.radius,0,Math.sin(f)*r.radius))}const c=new fn().setFromPoints(a),l=new Float32Array(o+1);for(let h=0;h<=o;h++)l[h]=h/o;c.setAttribute("aIndex",new Sn(l,1));const d=new tn({uniforms:{uTime:{value:0},uColor:{value:new Fe(this.colors.pulseNeutral)},uIntensity:{value:1},uAudioLevel:{value:0},uSpeed:{value:r.speed},uPhase:{value:r.phase},uRadius:{value:r.radius}},vertexShader:`
5420
5420
  attribute float aIndex;
5421
5421
  varying float vIndex;
5422
5422
  varying vec3 vPos;
@@ -5486,7 +5486,7 @@ void main() {
5486
5486
 
5487
5487
  gl_FragColor = vec4(color, alpha);
5488
5488
  }
5489
- `,transparent:!0,blending:Ji,depthWrite:!1}),u=new PS(c,d);u.rotation.x=r.tiltX,u.rotation.z=r.tiltZ,u.ringConfig=r,this.pulseRings.push(u),this.scene.add(u)}}createParticles(){this.particlePositions=new Float32Array(690),this.particleVelocities=new Float32Array(690);const t=new Float32Array(230),n=new Float32Array(230);for(let o=0;o<230;o++)this.resetParticleFromCore(o),t[o]=.015+Math.random()*.03,n[o]=Math.random();const s=new hn;s.setAttribute("position",new _n(this.particlePositions,3)),s.setAttribute("size",new _n(t,1)),s.setAttribute("lifetime",new _n(n,1));const r=new en({uniforms:{uColor:{value:new Fe(this.colors.particles)},uTime:{value:0},uMaxRadius:{value:this.config.size*.7}},vertexShader:`
5489
+ `,transparent:!0,blending:Ji,depthWrite:!1}),u=new PS(c,d);u.rotation.x=r.tiltX,u.rotation.z=r.tiltZ,u.ringConfig=r,this.pulseRings.push(u),this.scene.add(u)}}createParticles(){this.particlePositions=new Float32Array(690),this.particleVelocities=new Float32Array(690);const t=new Float32Array(230),n=new Float32Array(230);for(let o=0;o<230;o++)this.resetParticleFromCore(o),t[o]=.015+Math.random()*.03,n[o]=Math.random();const s=new fn;s.setAttribute("position",new Sn(this.particlePositions,3)),s.setAttribute("size",new Sn(t,1)),s.setAttribute("lifetime",new Sn(n,1));const r=new tn({uniforms:{uColor:{value:new Fe(this.colors.particles)},uTime:{value:0},uMaxRadius:{value:this.config.size*.7}},vertexShader:`
5490
5490
  attribute float size;
5491
5491
  attribute float lifetime;
5492
5492
  varying float vLifetime;
@@ -5524,7 +5524,7 @@ void main() {
5524
5524
 
5525
5525
  gl_FragColor = vec4(color, alpha * 0.8);
5526
5526
  }
5527
- `,transparent:!0,blending:Ji,depthWrite:!1});this.particles=new IS(s,r),this.particleMaterial=r,this.scene.add(this.particles)}resetParticleFromCore(e){if(!this.particlePositions||!this.particleVelocities)return;const t=e*3,n=Math.random()*Math.PI*2,s=Math.acos(2*Math.random()-1),r=this.config.size*(.1+Math.random()*.15);this.particlePositions[t]=Math.sin(s)*Math.cos(n)*r,this.particlePositions[t+1]=Math.cos(s)*r,this.particlePositions[t+2]=Math.sin(s)*Math.sin(n)*r;const o=.0027+Math.random()*.008;this.particleVelocities[t]=this.particlePositions[t]/r*o,this.particleVelocities[t+1]=this.particlePositions[t+1]/r*o,this.particleVelocities[t+2]=this.particlePositions[t+2]/r*o,this.particleVelocities[t]+=(Math.random()-.5)*.0013,this.particleVelocities[t+1]+=(Math.random()-.5)*.0013,this.particleVelocities[t+2]+=(Math.random()-.5)*.0013}updateParticles(e){if(!this.particlePositions||!this.particleVelocities||!this.particles)return;const t=this.currentConfig.particleSpeed,n=this.config.size*.7;this.particleMaterial&&(this.particleMaterial.uniforms.uTime.value=this.time);for(let s=0;s<this.particlePositions.length/3;s++){const r=s*3;this.particlePositions[r]+=this.particleVelocities[r]*t,this.particlePositions[r+1]+=this.particleVelocities[r+1]*t,this.particlePositions[r+2]+=this.particleVelocities[r+2]*t,(Math.sqrt(this.particlePositions[r]**2+this.particlePositions[r+1]**2+this.particlePositions[r+2]**2)>=n||Math.random()<.003)&&this.resetParticleFromCore(s)}this.particles.geometry.attributes.position.needsUpdate=!0}setState(e){this._currentState=e,this.targetConfig={...pu[e]}}getState(){return this._currentState}setAudioLevel(e){this.targetAudioLevel=Math.max(0,Math.min(1,e))}setEmotion(e){switch(this._currentEmotion=e,e){case"joy":this.targetPulseColor.set(this.colors.pulseJoy);break;case"thinking":this.targetPulseColor.set(this.colors.pulseThinking);break;case"interrupted":this.targetPulseColor.set(this.colors.pulseInterrupted);break;default:this.targetPulseColor.set(this.colors.pulseNeutral)}}getEmotion(){return this._currentEmotion}setColors(e){this.colors={...this.colors,...e},e.coreGlow&&this.coreOuter&&this.coreOuter.material.uniforms.uColorOuter.value.set(e.coreGlow),e.coreGlow&&this.coreGlow&&this.coreGlow.material.uniforms.uColor.value.set(e.coreGlow),e.particles&&this.particleMaterial&&this.particleMaterial.uniforms.uColor.value.set(e.particles),e.coreGlow&&this.coreLight&&this.coreLight.color.set(e.coreGlow),(e.pulseNeutral||e.pulseJoy||e.pulseThinking||e.pulseInterrupted)&&this.setEmotion(this._currentEmotion)}start(){this.animationId===null&&(this.clock.start(),this.animate())}stop(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}getCanvas(){return this.renderer.domElement}destroy(){this.stop(),window.removeEventListener("resize",this.handleResize),this.container.removeEventListener("mousemove",this.handleMouseMove),this.container.removeEventListener("mouseleave",this.handleMouseLeave),this.shellSegments.forEach(e=>{e.geometry.dispose(),e.material.dispose()}),this.coreInner&&(this.coreInner.geometry.dispose(),this.coreInner.material.dispose()),this.coreOuter&&(this.coreOuter.geometry.dispose(),this.coreOuter.material.dispose()),this.coreGlow&&(this.coreGlow.geometry.dispose(),this.coreGlow.material.dispose());for(const e of this.pulseRings)e.geometry.dispose(),e.material.dispose();this.pulseRings=[],this.particles&&(this.particles.geometry.dispose(),this.particles.material.dispose()),this.renderer.dispose(),this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement)}}var SM=Object.defineProperty,xM=Object.getOwnPropertyDescriptor,Rn=(i,e,t,n)=>{for(var s=n>1?void 0:n?xM(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&SM(e,t,s),s};$.LinaWidget=class extends Ui{constructor(){super(...arguments),this.orbRenderer=null,this.orbContainerRef=xa(),this.audioSimPhase=0,this.animationId=null,this.callManager=null,this.size=300,this.headerLogo="HANC.ai",this.headerTitle="Lina-Voice AI",this.showBranding=!0,this.version="v1.0.3",this.agentId="",this.voiceServiceUrl="",this.btnStartText="Start",this.btnEndText="End",this.colors={},this.currentState="idle",this.callStatus="idle",this._hasMicPermission=null,this.handleCallClick=async()=>{if(this.callStatus==="mic-denied")try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(t=>t.stop()),this._hasMicPermission=!0,this.callStatus="idle"}catch{return}this.callStatus==="active"||this.callStatus==="connecting"?await this.endCall():this.callStatus==="idle"&&await this.startCall()}}connectedCallback(){super.connectedCallback(),this.checkMicrophonePermission()}disconnectedCallback(){super.disconnectedCallback(),this.cleanup()}firstUpdated(){this.initializeOrb()}async checkMicrophonePermission(){try{const e=await navigator.permissions.query({name:"microphone"});this._hasMicPermission=e.state==="granted",e.addEventListener("change",()=>{this._hasMicPermission=e.state==="granted",e.state==="denied"?this.callStatus="mic-denied":this.callStatus==="mic-denied"&&(this.callStatus="idle")})}catch{this._hasMicPermission=null}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new pg(e,{size:1,colors:this.colors}),this.orbRenderer.start(),this.startIdleAnimation())}initializeCallManager(){this.callManager||(this.callManager=new ro,this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.callManager.addEventListener("status-changed",(e=>{const t=e.detail;this.handleCallStatusChange(t)})),this.callManager.addEventListener("audio-track",(e=>{const t=e.detail;if(t){const n=new MediaStream([t]);this.connectAudioStream(n)}})),this.callManager.addEventListener("microphone-disabled",()=>{this.callStatus==="active"&&(this._hasMicPermission=!1)}),this.callManager.addEventListener("error",(e=>{var t,n;console.error("Call error:",(t=e.detail)==null?void 0:t.error),this.callStatus="error",this.currentState="idle",(n=this.orbRenderer)==null||n.setState("idle"),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle")},3e3)})))}handleCallStatusChange(e){var t,n,s,r;switch(e){case"connecting":case"ringing":this.callStatus="connecting",this.currentState="listening",(t=this.orbRenderer)==null||t.setState("listening");break;case"connected":case"agent-connected":this.callStatus="active",this.currentState="speaking",(n=this.orbRenderer)==null||n.setState("speaking"),this.startActiveAnimation();break;case"disconnecting":this.callStatus="ending";break;case"disconnected":this.callStatus="idle",this.currentState="idle",(s=this.orbRenderer)==null||s.setState("idle"),this.startIdleAnimation();break;case"error":this.callStatus="error",this.currentState="idle",(r=this.orbRenderer)==null||r.setState("idle");break}}cleanup(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.callManager)==null||e.hangUp(),(t=this.orbRenderer)==null||t.destroy(),this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{if(!this.orbRenderer)return;const t=performance.now()/1e3,n=Math.sin(t*.4)*.08+Math.sin(t*.7)*.04+.15;this.orbRenderer.setAudioLevel(n),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startActiveAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId),this.audioSimPhase=Math.random()*Math.PI*2;const e=()=>{if(!this.orbRenderer||this.callStatus!=="active"){this.startIdleAnimation();return}this.audioSimPhase+=.03;const t=Math.sin(this.audioSimPhase*.25)*.25+.45,n=Math.sin(this.audioSimPhase*2)*.15,s=Math.sin(this.audioSimPhase*4.5)*.08,r=(Math.random()-.5)*.08,o=Math.random()>.97?Math.random()*.2:0,a=Math.max(0,Math.min(1,t+n+s+r+o));this.orbRenderer.setAudioLevel(a),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}connectAudioStream(e){if(!this.orbRenderer)return;this.animationId!==null&&cancelAnimationFrame(this.animationId);const t=new AudioContext,n=t.createAnalyser();n.fftSize=256,t.createMediaStreamSource(e).connect(n);const r=new Uint8Array(n.frequencyBinCount),o=()=>{if(!this.orbRenderer||this.callStatus!=="active"){t.close(),this.startIdleAnimation();return}n.getByteFrequencyData(r);let a=0;for(let d=0;d<r.length;d++)a+=r[d];const c=a/r.length/255,l=Math.pow(c,.7)*1.2;this.orbRenderer.setAudioLevel(Math.min(1,l)),this.animationId=requestAnimationFrame(o)};this.animationId=requestAnimationFrame(o)}async startCall(){var e,t,n,s;if(this._hasMicPermission!==!0)try{(await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})).getTracks().forEach(o=>o.stop()),this._hasMicPermission=!0}catch{this._hasMicPermission=!1,this.callStatus="mic-denied";return}if(this.agentId&&this.voiceServiceUrl){this.initializeCallManager(),this.callStatus="connecting",this.currentState="listening",(e=this.orbRenderer)==null||e.setState("listening");try{await((t=this.callManager)==null?void 0:t.makeCall({agentId:this.agentId}))}catch(r){console.error("Failed to start call:",r),this.callStatus="error",setTimeout(()=>{var o;this.callStatus==="error"&&(this.callStatus="idle",this.currentState="idle",(o=this.orbRenderer)==null||o.setState("idle"))},3e3)}}else this.callStatus="connecting",this.currentState="listening",(n=this.orbRenderer)==null||n.setState("listening"),await new Promise(r=>setTimeout(r,1500)),this.callStatus="active",this.currentState="speaking",(s=this.orbRenderer)==null||s.setState("speaking"),this.startActiveAnimation(),this.dispatchEvent(new CustomEvent("call-start",{detail:{agentId:"demo",timestamp:Date.now()},bubbles:!0,composed:!0}))}async endCall(){var e;this.callStatus="ending",this.callManager&&await this.callManager.hangUp(),this.callStatus="idle",this.currentState="idle",(e=this.orbRenderer)==null||e.setState("idle"),this.startIdleAnimation(),this.dispatchEvent(new CustomEvent("call-end",{detail:{timestamp:Date.now()},bubbles:!0,composed:!0}))}setState(e){var t;this.currentState=e,(t=this.orbRenderer)==null||t.setState(e)}setAudioLevel(e){var t;(t=this.orbRenderer)==null||t.setAudioLevel(e)}setColors(e){var t;this.colors={...this.colors,...e},(t=this.orbRenderer)==null||t.setColors(e)}setEmotion(e){var t;(t=this.orbRenderer)==null||t.setEmotion(e)}getEmotion(){var e;return(e=this.orbRenderer)==null?void 0:e.getEmotion()}getState(){return this.currentState}getCallStatus(){return this.callStatus}getButtonContent(){switch(this.callStatus){case"connecting":return Rt`
5527
+ `,transparent:!0,blending:Ji,depthWrite:!1});this.particles=new IS(s,r),this.particleMaterial=r,this.scene.add(this.particles)}resetParticleFromCore(e){if(!this.particlePositions||!this.particleVelocities)return;const t=e*3,n=Math.random()*Math.PI*2,s=Math.acos(2*Math.random()-1),r=this.config.size*(.1+Math.random()*.15);this.particlePositions[t]=Math.sin(s)*Math.cos(n)*r,this.particlePositions[t+1]=Math.cos(s)*r,this.particlePositions[t+2]=Math.sin(s)*Math.sin(n)*r;const o=.0027+Math.random()*.008;this.particleVelocities[t]=this.particlePositions[t]/r*o,this.particleVelocities[t+1]=this.particlePositions[t+1]/r*o,this.particleVelocities[t+2]=this.particlePositions[t+2]/r*o,this.particleVelocities[t]+=(Math.random()-.5)*.0013,this.particleVelocities[t+1]+=(Math.random()-.5)*.0013,this.particleVelocities[t+2]+=(Math.random()-.5)*.0013}updateParticles(e){if(!this.particlePositions||!this.particleVelocities||!this.particles)return;const t=this.currentConfig.particleSpeed,n=this.config.size*.7;this.particleMaterial&&(this.particleMaterial.uniforms.uTime.value=this.time);for(let s=0;s<this.particlePositions.length/3;s++){const r=s*3;this.particlePositions[r]+=this.particleVelocities[r]*t,this.particlePositions[r+1]+=this.particleVelocities[r+1]*t,this.particlePositions[r+2]+=this.particleVelocities[r+2]*t,(Math.sqrt(this.particlePositions[r]**2+this.particlePositions[r+1]**2+this.particlePositions[r+2]**2)>=n||Math.random()<.003)&&this.resetParticleFromCore(s)}this.particles.geometry.attributes.position.needsUpdate=!0}setState(e){switch(this._currentState=e,this.targetConfig={...pu[e]},e){case"listening":this.targetPulseColor.set(this.colors.stateListening);break;case"thinking":this.targetPulseColor.set(this.colors.stateThinking);break;case"speaking":this.targetPulseColor.set(this.colors.stateSpeaking);break;default:this.targetPulseColor.set(this.colors.stateIdle)}}getState(){return this._currentState}setAudioLevel(e){this.targetAudioLevel=Math.max(0,Math.min(1,e))}setEmotion(e){switch(this._currentEmotion=e,e){case"joy":this.targetPulseColor.set(this.colors.pulseJoy);break;case"thinking":this.targetPulseColor.set(this.colors.pulseThinking);break;case"interrupted":this.targetPulseColor.set(this.colors.pulseInterrupted);break;default:this.targetPulseColor.set(this.colors.pulseNeutral)}}getEmotion(){return this._currentEmotion}setColors(e){this.colors={...this.colors,...e},e.coreGlow&&this.coreOuter&&this.coreOuter.material.uniforms.uColorOuter.value.set(e.coreGlow),e.coreGlow&&this.coreGlow&&this.coreGlow.material.uniforms.uColor.value.set(e.coreGlow),e.particles&&this.particleMaterial&&this.particleMaterial.uniforms.uColor.value.set(e.particles),e.coreGlow&&this.coreLight&&this.coreLight.color.set(e.coreGlow),(e.pulseNeutral||e.pulseJoy||e.pulseThinking||e.pulseInterrupted)&&this.setEmotion(this._currentEmotion)}start(){this.animationId===null&&(this.clock.start(),this.animate())}stop(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}getCanvas(){return this.renderer.domElement}destroy(){this.stop(),window.removeEventListener("resize",this.handleResize),this.container.removeEventListener("mousemove",this.handleMouseMove),this.container.removeEventListener("mouseleave",this.handleMouseLeave),this.shellSegments.forEach(e=>{e.geometry.dispose(),e.material.dispose()}),this.coreInner&&(this.coreInner.geometry.dispose(),this.coreInner.material.dispose()),this.coreOuter&&(this.coreOuter.geometry.dispose(),this.coreOuter.material.dispose()),this.coreGlow&&(this.coreGlow.geometry.dispose(),this.coreGlow.material.dispose());for(const e of this.pulseRings)e.geometry.dispose(),e.material.dispose();this.pulseRings=[],this.particles&&(this.particles.geometry.dispose(),this.particles.material.dispose()),this.renderer.dispose(),this.renderer.domElement.parentNode&&this.renderer.domElement.parentNode.removeChild(this.renderer.domElement)}}var SM=Object.defineProperty,xM=Object.getOwnPropertyDescriptor,jt=(i,e,t,n)=>{for(var s=n>1?void 0:n?xM(e,t):e,r=i.length-1,o;r>=0;r--)(o=i[r])&&(s=(n?o(e,t,s):o(s))||s);return n&&s&&SM(e,t,s),s};$.LinaWidget=class extends Ui{constructor(){super(...arguments),this.orbRenderer=null,this.orbContainerRef=xa(),this.audioSimPhase=0,this.animationId=null,this.callManager=null,this.size=300,this.headerLogo="HANC.ai",this.headerTitle="Lina-Voice AI",this.showBranding=!0,this.version="v1.0.7",this.agentId="",this.voiceServiceUrl="",this.btnStartText="Start",this.btnEndText="End",this.colors={},this.brandingLogoColor="rgba(255, 255, 255, 0.9)",this.brandingTitleColor="rgba(255, 255, 255, 0.6)",this.brandingDividerColor="rgba(255, 255, 255, 0.3)",this.versionColor="rgba(255, 255, 255, 0.3)",this.buttonBackground="linear-gradient(135deg, rgba(139, 92, 246, 0.95) 0%, rgba(124, 58, 237, 0.95) 100%)",this.buttonTextColor="rgba(255, 255, 255, 0.95)",this.currentState="idle",this.callStatus="idle",this._hasMicPermission=null,this.handleCallClick=async()=>{if(this.callStatus==="mic-denied")try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(t=>t.stop()),this._hasMicPermission=!0,this.callStatus="idle"}catch{return}this.callStatus==="active"||this.callStatus==="connecting"?await this.endCall():this.callStatus==="idle"&&await this.startCall()}}connectedCallback(){super.connectedCallback(),this.checkMicrophonePermission()}disconnectedCallback(){super.disconnectedCallback(),this.cleanup()}firstUpdated(){this.initializeOrb()}async checkMicrophonePermission(){try{const e=await navigator.permissions.query({name:"microphone"});this._hasMicPermission=e.state==="granted",e.addEventListener("change",()=>{this._hasMicPermission=e.state==="granted",e.state==="denied"?this.callStatus="mic-denied":this.callStatus==="mic-denied"&&(this.callStatus="idle")})}catch{this._hasMicPermission=null}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new pg(e,{size:1,colors:this.colors}),this.orbRenderer.start(),this.startIdleAnimation())}initializeCallManager(){this.callManager||(this.callManager=new ro,this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.callManager.addEventListener("status-changed",(e=>{const t=e.detail;this.handleCallStatusChange(t)})),this.callManager.addEventListener("audio-track",(e=>{const t=e.detail;if(t){const n=new MediaStream([t]);this.connectAudioStream(n)}})),this.callManager.addEventListener("microphone-disabled",()=>{this.callStatus==="active"&&(this._hasMicPermission=!1)}),this.callManager.addEventListener("error",(e=>{var t,n;console.error("Call error:",(t=e.detail)==null?void 0:t.error),this.callStatus="error",this.currentState="idle",(n=this.orbRenderer)==null||n.setState("idle"),setTimeout(()=>{this.callStatus==="error"&&(this.callStatus="idle")},3e3)})))}handleCallStatusChange(e){var t,n,s,r;switch(e){case"connecting":case"ringing":this.callStatus="connecting",this.currentState="listening",(t=this.orbRenderer)==null||t.setState("listening");break;case"connected":case"agent-connected":this.callStatus="active",this.currentState="speaking",(n=this.orbRenderer)==null||n.setState("speaking"),this.startActiveAnimation();break;case"disconnecting":this.callStatus="ending";break;case"disconnected":this.callStatus="idle",this.currentState="idle",(s=this.orbRenderer)==null||s.setState("idle"),this.startIdleAnimation();break;case"error":this.callStatus="error",this.currentState="idle",(r=this.orbRenderer)==null||r.setState("idle");break}}cleanup(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.callManager)==null||e.hangUp(),(t=this.orbRenderer)==null||t.destroy(),this.orbRenderer=null}startIdleAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId);const e=()=>{if(!this.orbRenderer)return;const t=performance.now()/1e3,n=Math.sin(t*.4)*.08+Math.sin(t*.7)*.04+.15;this.orbRenderer.setAudioLevel(n),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startActiveAnimation(){this.animationId!==null&&cancelAnimationFrame(this.animationId),this.audioSimPhase=Math.random()*Math.PI*2;const e=()=>{if(!this.orbRenderer||this.callStatus!=="active"){this.startIdleAnimation();return}this.audioSimPhase+=.03;const t=Math.sin(this.audioSimPhase*.25)*.25+.45,n=Math.sin(this.audioSimPhase*2)*.15,s=Math.sin(this.audioSimPhase*4.5)*.08,r=(Math.random()-.5)*.08,o=Math.random()>.97?Math.random()*.2:0,a=Math.max(0,Math.min(1,t+n+s+r+o));this.orbRenderer.setAudioLevel(a),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}connectAudioStream(e){if(!this.orbRenderer)return;this.animationId!==null&&cancelAnimationFrame(this.animationId);const t=new AudioContext,n=t.createAnalyser();n.fftSize=256,t.createMediaStreamSource(e).connect(n);const r=new Uint8Array(n.frequencyBinCount),o=()=>{if(!this.orbRenderer||this.callStatus!=="active"){t.close(),this.startIdleAnimation();return}n.getByteFrequencyData(r);let a=0;for(let d=0;d<r.length;d++)a+=r[d];const c=a/r.length/255,l=Math.pow(c,.7)*1.2;this.orbRenderer.setAudioLevel(Math.min(1,l)),this.animationId=requestAnimationFrame(o)};this.animationId=requestAnimationFrame(o)}async startCall(){var e,t,n,s;if(this._hasMicPermission!==!0)try{(await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})).getTracks().forEach(o=>o.stop()),this._hasMicPermission=!0}catch{this._hasMicPermission=!1,this.callStatus="mic-denied";return}if(this.agentId&&this.voiceServiceUrl){this.initializeCallManager(),this.callStatus="connecting",this.currentState="listening",(e=this.orbRenderer)==null||e.setState("listening");try{await((t=this.callManager)==null?void 0:t.makeCall({agentId:this.agentId}))}catch(r){console.error("Failed to start call:",r),this.callStatus="error",setTimeout(()=>{var o;this.callStatus==="error"&&(this.callStatus="idle",this.currentState="idle",(o=this.orbRenderer)==null||o.setState("idle"))},3e3)}}else this.callStatus="connecting",this.currentState="listening",(n=this.orbRenderer)==null||n.setState("listening"),await new Promise(r=>setTimeout(r,1500)),this.callStatus="active",this.currentState="speaking",(s=this.orbRenderer)==null||s.setState("speaking"),this.startActiveAnimation(),this.dispatchEvent(new CustomEvent("call-start",{detail:{agentId:"demo",timestamp:Date.now()},bubbles:!0,composed:!0}))}async endCall(){var e;this.callStatus="ending",this.callManager&&await this.callManager.hangUp(),this.callStatus="idle",this.currentState="idle",(e=this.orbRenderer)==null||e.setState("idle"),this.startIdleAnimation(),this.dispatchEvent(new CustomEvent("call-end",{detail:{timestamp:Date.now()},bubbles:!0,composed:!0}))}setState(e){var t;this.currentState=e,(t=this.orbRenderer)==null||t.setState(e)}setAudioLevel(e){var t;(t=this.orbRenderer)==null||t.setAudioLevel(e)}setColors(e){var t;this.colors={...this.colors,...e},(t=this.orbRenderer)==null||t.setColors(e)}setEmotion(e){var t;(t=this.orbRenderer)==null||t.setEmotion(e)}getEmotion(){var e;return(e=this.orbRenderer)==null?void 0:e.getEmotion()}getState(){return this.currentState}getCallStatus(){return this.callStatus}getButtonContent(){switch(this.callStatus){case"connecting":return Rt`
5528
5528
  <svg viewBox="0 0 24 24" fill="none">
5529
5529
  <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" stroke-dasharray="50 20" stroke-linecap="round"/>
5530
5530
  </svg>
@@ -5576,11 +5576,11 @@ void main() {
5576
5576
 
5577
5577
  ${this.showBranding?Rt`
5578
5578
  <div class="branding">
5579
- <span class="branding-logo">${this.headerLogo}</span>
5580
- <span class="branding-divider">|</span>
5581
- <span class="branding-title">${this.headerTitle}</span>
5579
+ <span class="branding-logo" style="color: ${this.brandingLogoColor}">${this.headerLogo}</span>
5580
+ <span class="branding-divider" style="color: ${this.brandingDividerColor}">|</span>
5581
+ <span class="branding-title" style="color: ${this.brandingTitleColor}">${this.headerTitle}</span>
5582
5582
  </div>
5583
- <span class="version">${this.version}</span>
5583
+ <span class="version" style="color: ${this.versionColor}">${this.version}</span>
5584
5584
  `:""}
5585
5585
  </div>
5586
5586
  </div>
@@ -5755,4 +5755,4 @@ void main() {
5755
5755
  .call-control-btn.mic-denied svg {
5756
5756
  animation: warning-pulse 2s ease-in-out infinite;
5757
5757
  }
5758
- `,Rn([pe({type:Number})],$.LinaWidget.prototype,"size",2),Rn([pe({type:String,attribute:"header-logo"})],$.LinaWidget.prototype,"headerLogo",2),Rn([pe({type:String,attribute:"header-title"})],$.LinaWidget.prototype,"headerTitle",2),Rn([pe({type:Boolean,attribute:"show-branding"})],$.LinaWidget.prototype,"showBranding",2),Rn([pe({type:String})],$.LinaWidget.prototype,"version",2),Rn([pe({type:String,attribute:"agent-id"})],$.LinaWidget.prototype,"agentId",2),Rn([pe({type:String,attribute:"voice-service-url"})],$.LinaWidget.prototype,"voiceServiceUrl",2),Rn([pe({type:String,attribute:"btn-start-text"})],$.LinaWidget.prototype,"btnStartText",2),Rn([pe({type:String,attribute:"btn-end-text"})],$.LinaWidget.prototype,"btnEndText",2),Rn([pe({type:Object})],$.LinaWidget.prototype,"colors",2),Rn([Fi()],$.LinaWidget.prototype,"currentState",2),Rn([Fi()],$.LinaWidget.prototype,"callStatus",2),$.LinaWidget=Rn([_a("lina-voice-widget")],$.LinaWidget),$.LinaOrbRenderer=pg,$.SoundManager=$o,$.applyTheme=fg,$.darkPresets=di,$.darkThemes=dM,$.detectSystemTheme=hg,$.getColorPreset=cM,$.getPresetNames=lM,$.getTheme=pa,$.getThemeNames=hM,$.lightPresets=ui,$.lightThemes=uM,$.themes=Sr,$.watchSystemTheme=fM,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})}));
5758
+ `,jt([ce({type:Number})],$.LinaWidget.prototype,"size",2),jt([ce({type:String,attribute:"header-logo"})],$.LinaWidget.prototype,"headerLogo",2),jt([ce({type:String,attribute:"header-title"})],$.LinaWidget.prototype,"headerTitle",2),jt([ce({type:Boolean,attribute:"show-branding"})],$.LinaWidget.prototype,"showBranding",2),jt([ce({type:String})],$.LinaWidget.prototype,"version",2),jt([ce({type:String,attribute:"agent-id"})],$.LinaWidget.prototype,"agentId",2),jt([ce({type:String,attribute:"voice-service-url"})],$.LinaWidget.prototype,"voiceServiceUrl",2),jt([ce({type:String,attribute:"btn-start-text"})],$.LinaWidget.prototype,"btnStartText",2),jt([ce({type:String,attribute:"btn-end-text"})],$.LinaWidget.prototype,"btnEndText",2),jt([ce({type:Object})],$.LinaWidget.prototype,"colors",2),jt([ce({type:String,attribute:"branding-logo-color"})],$.LinaWidget.prototype,"brandingLogoColor",2),jt([ce({type:String,attribute:"branding-title-color"})],$.LinaWidget.prototype,"brandingTitleColor",2),jt([ce({type:String,attribute:"branding-divider-color"})],$.LinaWidget.prototype,"brandingDividerColor",2),jt([ce({type:String,attribute:"version-color"})],$.LinaWidget.prototype,"versionColor",2),jt([ce({type:String,attribute:"button-background"})],$.LinaWidget.prototype,"buttonBackground",2),jt([ce({type:String,attribute:"button-text-color"})],$.LinaWidget.prototype,"buttonTextColor",2),jt([Fi()],$.LinaWidget.prototype,"currentState",2),jt([Fi()],$.LinaWidget.prototype,"callStatus",2),$.LinaWidget=jt([_a("lina-voice-widget")],$.LinaWidget),$.LinaOrbRenderer=pg,$.SoundManager=$o,$.applyTheme=fg,$.darkPresets=di,$.darkThemes=dM,$.detectSystemTheme=hg,$.getColorPreset=cM,$.getPresetNames=lM,$.getTheme=pa,$.getThemeNames=hM,$.lightPresets=ui,$.lightThemes=uM,$.themes=Sr,$.watchSystemTheme=fM,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})}));