@livedigital/client 3.24.2 → 3.24.3

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.
package/dist/index.js CHANGED
@@ -24,4 +24,4 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24
24
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25
25
  PERFORMANCE OF THIS SOFTWARE.
26
26
  ***************************************************************************** */
27
- function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}(e,["emitter","type"]),s=null!=r?r:"N/A emitter";"error"===n&&o(this,Hp,"f").error(s,Object.assign({},i)),"warning"===n&&o(this,Hp,"f").warn(s,Object.assign({},i)),"info"===n&&o(this,Hp,"f").info(s,Object.assign({},i)),"ml_inference"===r&&(i.message.toLocaleLowerCase().includes("init lowlighter")&&(o(this,Gp,"f").lowLighter=!0),i.message.toLocaleLowerCase().includes("init colorcorrector")&&(o(this,Gp,"f").colorCorrector=!0),i.message.toLocaleLowerCase().includes("init facedetector")&&(o(this,Gp,"f").faceDetector=!0),i.message.toLocaleLowerCase().includes("init segmentation")&&(o(this,Gp,"f").segmentation=!0),this.isModelsLoaded&&(null===(t=o(this,Yp,"f"))||void 0===t||t.call(this)))}get isModelsLoaded(){return o(this,Gp,"f").colorCorrector&&o(this,Gp,"f").faceDetector&&o(this,Gp,"f").lowLighter&&o(this,Gp,"f").segmentation}get modelsLoadProgress(){return Object.values(o(this,Gp,"f")).filter(Boolean).length/Object.keys(o(this,Gp,"f")).length}get isReady(){return o(this,Jp,"f")}setOnLoadModels(e){a(this,Yp,e,"f"),this.isModelsLoaded&&o(this,Yp,"f").call(this)}onReady(){a(this,Jp,!0,"f"),o(this,Hp,"f").debug("onReady()",{description:"ESDK is ready"}),this.updateEffects(o(this,Qp,"f"))}processTrack(e){var t,r;return s(this,void 0,void 0,(function*(){if(o(this,Kp,"f")===e||"ended"===e.readyState)return(null===(t=o(this,Vp,"f").getStream())||void 0===t?void 0:t.getVideoTracks()[0])||e;this.stopProcessing();try{o(this,Vp,"f").useStream(new MediaStream([e]));const t=null===(r=o(this,Vp,"f").getStream())||void 0===r?void 0:r.getVideoTracks()[0];return t?(a(this,Kp,e,"f"),t):e}catch(t){throw o(this,Hp,"f").error("processTrack()",{error:t,track:e}),new Error("Can not process this track")}}))}stopProcessing(){try{o(this,Vp,"f").clear(),o(this,Vp,"f").stop()}catch(e){o(this,Hp,"f").error("stopProcessing()",{error:e})}finally{a(this,Kp,null,"f")}}updateEffects(e){var t,r,n,i,s,c,d,l,u,p,h,f,m,g,v,y,b,w,_,S,k;if(a(this,Qp,e,"f"),!o(this,Jp,"f"))return void o(this,Hp,"f").warn("updateEffects()",{description:"Esdk not ready"});if(!o(this,Qp,"f")||0===Object.keys(o(this,Qp,"f")).length)return void o(this,Vp,"f").stop();let R=0;if((null===(t=o(this,Qp,"f"))||void 0===t?void 0:t.blur)&&!(null===(r=o(this,Qp,"f"))||void 0===r?void 0:r.backgroundColor)?(o(this,Vp,"f").setBlur(o(this,Qp,"f").blur),R+=1):o(this,Vp,"f").clearBlur(),void 0!==(null===(n=o(this,Qp,"f"))||void 0===n?void 0:n.background)?(o(this,Vp,"f").setBackground(o(this,Qp,"f").background),R+=1):void 0!==(null===(i=o(this,Qp,"f"))||void 0===i?void 0:i.backgroundColor)?(o(this,Vp,"f").setBackgroundColor(null===(s=o(this,Qp,"f"))||void 0===s?void 0:s.backgroundColor),o(this,Vp,"f").setBackground("color"),R+=1):o(this,Vp,"f").clearBackground(),(null===(c=o(this,Qp,"f"))||void 0===c?void 0:c.beautification)?(o(this,Vp,"f").enableBeautification(),o(this,Vp,"f").setBeautificationLevel(o(this,Qp,"f").beautification),R+=1):o(this,Vp,"f").disableBeautification(),(null===(d=o(this,Qp,"f"))||void 0===d?void 0:d.lowLightEffect)?(o(this,Vp,"f").enableLowLightEffect(),o(this,Vp,"f").setLowLightEffectPower(o(this,Qp,"f").lowLightEffect),R+=1):o(this,Vp,"f").disableLowLightEffect(),(null===(l=o(this,Qp,"f"))||void 0===l?void 0:l.colorCorrector)?(o(this,Vp,"f").enableColorCorrector(),o(this,Vp,"f").setColorCorrectorPower(o(this,Qp,"f").colorCorrector),R+=1):o(this,Vp,"f").disableColorCorrector(),(null===(u=o(this,Qp,"f"))||void 0===u?void 0:u.smartZoom)?(o(this,Vp,"f").enableSmartZoom(),o(this,Vp,"f").setFaceArea(o(this,Qp,"f").smartZoom),R+=1):o(this,Vp,"f").disableSmartZoom(),(null===(p=o(this,Qp,"f"))||void 0===p?void 0:p.layout)?(o(this,Vp,"f").setLayout(o(this,Qp,"f").layout),R+=1):o(this,Vp,"f").setLayout("center"),(null===(h=o(this,Qp,"f"))||void 0===h?void 0:h.colorFilter)&&(null===(f=o(this,Qp,"f"))||void 0===f?void 0:f.colorFilter.power)&&(null===(m=o(this,Qp,"f"))||void 0===m?void 0:m.colorFilter.url)?(o(this,Vp,"f").setColorFilterConfig({lut:o(this,Qp,"f").colorFilter.url,power:o(this,Qp,"f").colorFilter.power}),o(this,Vp,"f").enableColorFilter(),R+=1):o(this,Vp,"f").disableColorFilter(),null===(g=o(this,Qp,"f"))||void 0===g?void 0:g.lowerThird){const e=o(this,Vp,"f").createComponent({component:o(this,Qp,"f").lowerThird.type,options:o(this,Qp,"f").lowerThird.options||{}});null===(b=null===(y=null===(v=o(this,Vp,"f").components)||void 0===v?void 0:v.lowerThird)||void 0===y?void 0:y.hideLowerThird)||void 0===b||b.call(y),o(this,Vp,"f").addComponent(e,"lowerThird"),o(this,Vp,"f").components.lowerThird.showLowerThird(),R+=1}else null===(S=null===(_=null===(w=o(this,Vp,"f").components)||void 0===w?void 0:w.lowerThird)||void 0===_?void 0:_.hideLowerThird)||void 0===S||S.call(_);(null===(k=o(this,Qp,"f"))||void 0===k?void 0:k.sharpness)?(o(this,Vp,"f").setSharpnessEffectConfig(o(this,Qp,"f").sharpness),R+=1):o(this,Vp,"f").disableSharpnessEffect(),R>2?o(this,Vp,"f").enableFrameSkipping():o(this,Vp,"f").disableFrameSkipping(),o(this,Vp,"f").run()}}Vp=new WeakMap,Hp=new WeakMap,Gp=new WeakMap,Kp=new WeakMap,Qp=new WeakMap,Jp=new WeakMap,Yp=new WeakMap;class lh{constructor(e){this.isDeviceLoaded=!1,this.tracks=new Map,Zp.set(this,void 0),Xp.set(this,void 0),eh.set(this,void 0),th.set(this,void 0),rh.set(this,void 0),nh.set(this,void 0),ih.set(this,null),sh.set(this,void 0),oh.set(this,!1),ah.set(this,new Map);const{logLevel:t,onLogMessage:r}=e;a(this,Xp,t,"f"),a(this,Zp,new $s({namespace:"Media",logLevel:t,onLogMessage:r,sendAnalytics:e.sendAnalytics}),"f"),a(this,eh,e.engine,"f"),a(this,th,e.internalEventEmitter,"f"),a(this,ih,e.effectsSDKParams||null,"f"),a(this,ih,e.effectsSDKParams||null,"f"),a(this,nh,e.mediaTracksFactory,"f"),a(this,rh,new Up({logLevel:t,onLogMessage:r,sendAnalytics:e.sendAnalytics}),"f")}get mediasoupDevice(){return this.device||(this.device=this.createDevice()),this.device}get isNoiseSuppressorLoaded(){return!!o(this,sh,"f")}get effectsSDKInitialized(){return o(this,oh,"f")}get effectsSDKParams(){return o(this,ih,"f")}getTrack(e){return this.tracks.get(e)}loadDevice(e){return s(this,void 0,void 0,(function*(){this.isDeviceLoaded||(yield this.mediasoupDevice.load({routerRtpCapabilities:e}),this.isDeviceLoaded=!0)}))}createNoiseSuppressor(){return s(this,void 0,void 0,(function*(){try{if(o(this,sh,"f"))return void o(this,Zp,"f").warn("createNoiseSuppressor()",{message:"Noise suppression module already created"});a(this,sh,yield class{static compileModule(e){return s(this,void 0,void 0,(function*(){if(!window.WebAssembly)throw new Error("Webassembly not supported");const t=yield fetch(`${e}/rnnoise-processor.wasm`);return WebAssembly.instantiate(yield t.arrayBuffer())}))}}.compileModule(window.location.origin),"f")}catch(e){o(this,Zp,"f").warn("createNoiseSuppressor()",{message:"Can not load wasm module",error:e})}}))}getTrackCodec(e){const{rtpCapabilities:t,rtpCapabilities:{codecs:r}}=this.mediasoupDevice;if(r)return r.find((t=>t.mimeType.toLowerCase()===`${e.kind}/${e.getPreferredCodec()}`));o(this,Zp,"f").error("getTrackCodec()",{label:e.getLabel,rtpCapabilities:t})}createTracks({constraints:e,mediaStreamTracks:t}){return t.map((t=>{const r={mediaStreamTrack:t,logLevel:o(this,Xp,"f"),engine:o(this,eh,"f"),internalEventEmitter:o(this,th,"f"),constraints:e,mediaStreamTrackManager:o(this,rh,"f")},n="audio"===t.kind?o(this,nh,"f").createAudioTrack(Object.assign(Object.assign({},r),{noiseSuppressor:o(this,sh,"f")})):o(this,nh,"f").createVideoTrack(r);return o(this,Zp,"f").debug("createTrack() track created",{trackId:n.id,kind:n.kind}),n}))}createUserMediaTracks(e){return s(this,void 0,void 0,(function*(){const t=yield o(this,rh,"f").createUserMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createDisplayMediaTracks(e){return s(this,void 0,void 0,(function*(){const t=yield o(this,rh,"f").createDisplayMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}deleteTrack(e){return s(this,void 0,void 0,(function*(){const t={trackId:e.id,label:e.getLabel(),producerId:e.producerId};try{"disableNoiseSuppression"in e&&(yield e.disableNoiseSuppression()),"disableEffects"in e&&(yield e.disableEffects())}catch(e){o(this,Zp,"f").warn("deleteTrack()",Object.assign({error:e},t))}try{this.tracks.delete(e.getLabel()),e.stopMediaStreamTrack(),yield e.closeProducer()}catch(e){o(this,Zp,"f").error("deleteTrack()",{error:e})}finally{o(this,Zp,"f").debug("deleteTrack()",t)}}))}getAllTracks(){return Array.from(this.tracks.values())}clearTracks(){return s(this,void 0,void 0,(function*(){try{this.getAllTracks().map((e=>e.stopMediaStreamTrack()))}catch(e){o(this,Zp,"f").warn("clearTracks()",{error:e})}finally{this.tracks.clear()}}))}setTrack(e){this.tracks.set(e.getLabel(),e)}initEffectsSDK(){if(o(this,oh,"f"))return Promise.resolve(!0);if(!o(this,ih,"f"))throw o(this,Zp,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Error("Effects SDK config not provided");const e=(e,t)=>s(this,void 0,void 0,(function*(){if(!window.tsvb)return o(this,Zp,"f").info("Effects SDK not loaded, skipping initialization",{case:"initEffectsSDK"}),void e(!1);o(this,Zp,"f").info("Effects SDK initializing",{case:"initEffectsSDK"});try{o(this,ah,"f").set(m.Camera,yield this.createEffectsSDKTrackProcessor(m.Camera)),o(this,ah,"f").set(m.CameraPreview,yield this.createEffectsSDKTrackProcessor(m.CameraPreview)),a(this,oh,!0,"f"),o(this,Zp,"f").info("Effects SDK initialized",{case:"initEffectsSDK"}),e(!0)}catch(e){o(this,Zp,"f").error("Failed to initilize Effects SDK",{error:e,case:"initEffectsSDK"}),t(e)}}));return new Promise(((t,r)=>{if(!window.tsvb)return o(this,Zp,"f").info("Effects SDK tsvb-web.js is not ready, waiting",{case:"initEffectsSDK"}),void window.addEventListener("load",(()=>e(t,r)));e(t,r)}))}createEffectsSDKTrackProcessor(e){return s(this,void 0,void 0,(function*(){if(e){const t=o(this,ah,"f").get(e);if(t)return t}if(!o(this,ih,"f"))throw o(this,Zp,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Error("Effects SDK config not provided");const t=new dh({logLevel:o(this,Xp,"f"),customerId:o(this,ih,"f").customerId,sendAnalytics:o(this,eh,"f").sendAnalytics});return yield t.init(),o(this,Zp,"f").info("Track effects processor initialized",{trackLabel:e}),t}))}static getVideoTrackTransformParams(e){const t=e.getSettings();return{width:t.width||Ap.width,height:t.height||Ap.height}}static getScreenVideoTrackParams(e){var t;return{videoTrackOptions:null!==(t=null==e?void 0:e.video)&&void 0!==t?t:{frameRate:{max:20},width:{max:Ap.width},height:{max:Ap.height}},encoderConfig:(null==e?void 0:e.videoEncoderConfig)||{encodings:Np}}}static getCameraVideoTrackParams(e){var t;return{videoTrackOptions:null!==(t=null==e?void 0:e.video)&&void 0!==t?t:{frameRate:{max:24},width:{max:Ap.width},height:{max:Ap.height}},encoderConfig:(null==e?void 0:e.encoderConfig)||{encodings:jp}}}createDevice(){const e=(e=>{const t=null!=e?e:null===navigator||void 0===navigator?void 0:navigator.userAgent;if(!t)return;const r=Wp.getParser(t);return r.satisfies({"yandex browser":">=23.7"})?"Chrome111":r.satisfies({"yandex browser":">=22"})?"Chrome74":void 0})();return o(this,Zp,"f").debug("Creating a media device",{handlerName:null!=e?e:"not specified"}),new Hs.Device({handlerName:e})}}Zp=new WeakMap,Xp=new WeakMap,eh=new WeakMap,th=new WeakMap,rh=new WeakMap,nh=new WeakMap,ih=new WeakMap,sh=new WeakMap,oh=new WeakMap,ah=new WeakMap,function(e){e.Connect="connect",e.Connected="connected",e.ConnectError="connect_error",e.Reconnect="reconnect",e.Reconnecting="reconnecting",e.Reconnected="reconnected",e.ReconnectAttempt="reconnect_attempt",e.NeedToJoinFirst="need_to_join_first",e.Disconnect="disconnect",e.Disconnected="disconnected",e.Error="error",e.State="state",e.BufferingStart="buffering_start",e.BufferingEnd="buffering_end"}(ch||(ch={}));const uh=new Error("request for lock canceled");var ph=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class hh{constructor(e,t=uh){if(this._maxConcurrency=e,this._cancelError=t,this._queue=[],this._waiters=[],e<=0)throw new Error("semaphore must be initialized to a positive value");this._value=e}acquire(){const e=this.isLocked(),t=new Promise(((e,t)=>this._queue.push({resolve:e,reject:t})));return e||this._dispatch(),t}runExclusive(e){return ph(this,void 0,void 0,(function*(){const[t,r]=yield this.acquire();try{return yield e(t)}finally{r()}}))}waitForUnlock(){return ph(this,void 0,void 0,(function*(){if(!this.isLocked())return Promise.resolve();return new Promise((e=>this._waiters.push({resolve:e})))}))}isLocked(){return this._value<=0}release(){if(this._maxConcurrency>1)throw new Error("this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead");if(this._currentReleaser){const e=this._currentReleaser;this._currentReleaser=void 0,e()}}cancel(){this._queue.forEach((e=>e.reject(this._cancelError))),this._queue=[]}_dispatch(){const e=this._queue.shift();if(!e)return;let t=!1;this._currentReleaser=()=>{t||(t=!0,this._value++,this._resolveWaiters(),this._dispatch())},e.resolve([this._value--,this._currentReleaser])}_resolveWaiters(){this._waiters.forEach((e=>e.resolve())),this._waiters=[]}}var fh,mh,gh,vh,yh,bh,wh,_h,Sh,kh,Rh,Ph,Ch,Th,Eh=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class Dh{constructor(e){this._semaphore=new hh(1,e)}acquire(){return Eh(this,void 0,void 0,(function*(){const[,e]=yield this._semaphore.acquire();return e}))}runExclusive(e){return this._semaphore.runExclusive((()=>e()))}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.release()}cancel(){return this._semaphore.cancel()}}class Lh{constructor(e){fh.set(this,void 0),mh.set(this,void 0),this.encoderConfig={},this.label=m.Unknown,gh.set(this,void 0),vh.set(this,void 0),yh.set(this,!1),bh.set(this,void 0),wh.set(this,void 0),_h.set(this,void 0),Sh.set(this,!0),kh.set(this,new Dh);const{mediaStreamTrack:t,logLevel:r,engine:n,internalEventEmitter:i,constraints:s,mediaStreamTrackManager:o}=e;a(this,fh,t,"f"),a(this,gh,n,"f"),a(this,vh,i,"f"),a(this,bh,s,"f"),a(this,wh,o,"f"),a(this,_h,new c,"f"),this.logger=new $s({namespace:"Track",logLevel:r,sendAnalytics:n.sendAnalytics})}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished}}get observer(){return o(this,_h,"f")}get mediaStreamTrack(){return o(this,fh,"f")}get originalTrack(){return o(this,mh,"f")}get id(){return this.mediaStreamTrack.id}get kind(){return this.mediaStreamTrack.kind}get producerId(){var e;return null===(e=this.producer)||void 0===e?void 0:e.id}get isPublished(){return!!this.producer&&!this.producer.closed}get isPaused(){var e,t;return null!==(t=null===(e=this.producer)||void 0===e?void 0:e.paused)&&void 0!==t&&t}get internalEventEmitter(){return o(this,vh,"f")}getLabel(){return this.label}setLabel(e){this.label=e}setEncoderConfig(e){this.encoderConfig=e}getEncoderConfig(){return this.encoderConfig}setProducer(e){this.producer=e}setStopTrackOnPause(e){this.isPublished||a(this,Sh,e,"f")}getProducer(){return this.producer}setOriginalTrack(){a(this,mh,this.mediaStreamTrack,"f")}closeProducer(e=!0){return s(this,void 0,void 0,(function*(){if(this.producer){try{yield o(this,gh,"f").network.closeRemoteProducer(this.producer.id)}catch(e){this.logger.warn("closeProducer()",{label:this.getLabel(),producerId:this.producerId})}this.producer.close(),this.producer=void 0,e&&this.stopMediaStreamTrack()}}))}setPriority(e){return s(this,void 0,void 0,(function*(){this.producer?(yield this.producer.setRtpEncodingParameters({priority:e}),this.logger.debug("setPriority()",{label:this.getLabel(),priority:e})):this.logger.warn("setPriority()",{priority:e,reason:"Not published yet"})}))}stopMediaStreamTrack(){this.mediaStreamTrack.stop(),this.mediaStreamTrack.dispatchEvent(new Event("ended")),this.stopOriginalTrack()}stopOriginalTrack(){o(this,mh,"f")&&(o(this,mh,"f").stop(),a(this,mh,void 0,"f"))}produce({encodings:e,codecOptions:t,preferredCodec:r,transformParams:n,keyFrameRequestDelay:i}){var a;return s(this,void 0,void 0,(function*(){if(!o(this,gh,"f").cahPublish)throw this.logger.error("produce()",{message:"Not enough access to produce"}),new Error("Not enough access to produce");if(this.producer)throw new Error("Track already produced");try{yield o(this,gh,"f").network.socket.request(B);const{rtpCapabilities:{codecs:s}}=o(this,gh,"f").media.mediasoupDevice,c=null==s?void 0:s.find((e=>e.mimeType.toLowerCase()===`${this.kind}/${r}`)),d=0,l=this.prepareProducerEncodings({codec:c,encodings:null!=e?e:[],maxSpatialLayer:(null!=e?e:[]).length-1}),u={trackTransformParams:n,peerId:String(o(this,gh,"f").myPeerId),label:this.getLabel(),maxSpatialLayer:d,encodings:l,codecOptions:t,preferredCodec:r,codec:c,keyFrameRequestDelay:i},p=yield null===(a=o(this,gh,"f").network.sendTransport)||void 0===a?void 0:a.produce({track:this.mediaStreamTrack,encodings:l,codecOptions:t,codec:c,stopTracks:!1,disableTrackOnPause:!0,zeroRtpOnPause:!0,appData:u});if(!p)return;const h=p.rtpSender,f=()=>/Safari/i.test(navigator.userAgent);if(e&&h&&f()){const t=h.getParameters();e.forEach((({maxBitrate:e,scaleResolutionDownBy:r},n)=>{t.encodings[n]&&(t.encodings[n].maxBitrate=e,t.encodings[n].scaleResolutionDownBy=r)})),yield h.setParameters(t)}this.setProducer(p),"video"===this.kind&&(e&&h&&c&&$p(c.mimeType)?yield h.setParameters(Object.assign(Object.assign({},h.getParameters()),{encodings:this.prepareProducerEncodings({encodings:e,codec:c,maxSpatialLayer:d})})):yield p.setMaxSpatialLayer(d),yield o(this,gh,"f").network.socket.request(Re,{producerId:p.id,maxSpatialLayer:d})),"audio"===this.kind&&(yield this.setPriority("high")),this.logger.debug("produce()",{track:this.logCtx,encodings:e,codecOptions:t})}catch(e){throw this.logger.error("produce()",{error:e,track:this.logCtx}),new Error("Publish track failed")}}))}publish(){return s(this,void 0,void 0,(function*(){yield this.produce({}),this.internalEventEmitter.emit(ne.trackProduced,this)}))}unpublish(){return s(this,void 0,void 0,(function*(){try{this.stopMediaStreamTrack(),this.internalEventEmitter.emit(ne.trackUnproduced,this),this.producer&&(yield this.closeProducer()),a(this,yh,!0,"f"),this.logger.debug("unpublish()",{track:this.logCtx})}catch(e){this.logger.error("unpublish()",{error:e})}}))}pauseRemoteProducer(e){return s(this,void 0,void 0,(function*(){return o(this,gh,"f").network.socket.request(ye,{producerId:e})}))}resumeRemoteProducer(e){return s(this,void 0,void 0,(function*(){return o(this,gh,"f").network.socket.request(be,{producerId:e})}))}mute(e){return s(this,void 0,void 0,(function*(){yield o(this,kh,"f").waitForUnlock();const t=yield o(this,kh,"f").acquire();if(this.producer)try{if(this.producer.pause(),this.logger.debug("pause()",{track:this.logCtx}),o(this,Sh,"f"))return null==e||e(),o(this,fh,"f").stop(),this.stopOriginalTrack(),this.internalEventEmitter.emit(ne.trackClosed,this),void(yield this.pauseRemoteProducer(this.producer.id));yield this.pauseRemoteProducer(this.producer.id),this.internalEventEmitter.emit(ne.trackPaused,this)}catch(e){throw this.logger.error("pause()",{error:e,track:this.logCtx}),yield o(this,gh,"f").media.deleteTrack(this),this.internalEventEmitter.emit(ne.trackFailed,this),new Error("Can`t pause track, removing")}finally{t()}else this.logger.warn("pause()",{message:"Track is not published",track:this.logCtx})}))}resume(){return s(this,void 0,void 0,(function*(){yield o(this,kh,"f").waitForUnlock();const e=yield o(this,kh,"f").acquire();if(this.producer)try{if(this.logger.debug("resume()",{track:this.logCtx}),o(this,Sh,"f"))return yield this.reopenMediaStreamTrack(),yield this.resumeProducer(),void this.internalEventEmitter.emit(ne.trackReopened,this);yield this.resumeProducer(),this.internalEventEmitter.emit(ne.trackResumed,this)}catch(e){throw this.logger.error("resume()",{error:e,track:this.logCtx}),new Error("Can`t resume track")}finally{e()}else this.logger.warn("resume()",{message:"Track is not published",track:this.logCtx})}))}getInfo(){return s(this,void 0,void 0,(function*(){const{width:e,height:t,frameRate:r,aspectRatio:n}=o(this,fh,"f").getSettings();return{trackId:o(this,fh,"f").id,readyState:o(this,fh,"f").readyState,kind:this.kind,label:this.label,width:e,height:t,frameRate:r,aspectRatio:n,paused:this.isPaused,trackOutboundStats:yield this.getStats()}}))}getStats(){var e,t,r,n,i;return s(this,void 0,void 0,(function*(){try{return{producerId:null===(e=this.producer)||void 0===e?void 0:e.id,codec:null===(t=this.producer)||void 0===t?void 0:t.rtpParameters.codecs.find((e=>hp(e))),dtlsState:null===(i=null===(n=null===(r=this.producer)||void 0===r?void 0:r.rtpSender)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.state,rtcStats:yield this.getOutboundRTPStreamStats()}}catch(e){return void this.logger.debug("getStats()",{error:e})}}))}replaceTrack(e){var t;return s(this,void 0,void 0,(function*(){try{a(this,fh,e,"f"),this.internalEventEmitter.emit(ne.trackReopened,this),this.observer.safeEmit("track-changed",{track:e}),yield null===(t=this.producer)||void 0===t?void 0:t.replaceTrack({track:e})}catch(e){this.logger.warn("replaceTrack()",{error:e})}}))}resumeProducer(){return s(this,void 0,void 0,(function*(){this.producer?(yield this.resumeRemoteProducer(this.producer.id),this.producer.resume()):this.logger.debug("resumeProducer()",{message:"Track not produced yet",track:this.logCtx})}))}reopenMediaStreamTrack(){var e;return s(this,void 0,void 0,(function*(){const t=yield o(this,wh,"f").createMediaStreamTrack({label:this.label,constraints:o(this,bh,"f")});a(this,fh,t,"f"),yield null===(e=this.producer)||void 0===e?void 0:e.replaceTrack({track:t})}))}prepareProducerEncodings(e){const{encodings:t,codec:r,maxSpatialLayer:n}=e;return t&&t.length>1&&r&&$p(r.mimeType)?[t[n]||t[0]]:t}getOutboundRTPStreamStats(){return new Promise(((e,t)=>{const r=(n=0)=>s(this,void 0,void 0,(function*(){if(!this.producer)throw new Error("Producer is missed");try{const i=yield this.producer.getStats(),s=Array.from(i.values()).find((e=>"outbound-rtp"===e.type));if(!s&&n<5)return void setTimeout((()=>r(n+1)),150);n>=5&&!s&&t(new Error("OutboundRTPStreamStat not exist")),e(s)}catch(e){t(new Error("Can not get RTCStatsReport")),this.logger.debug("getOutboundRTPStreamStats()",{error:e})}}));r()}))}}fh=new WeakMap,mh=new WeakMap,gh=new WeakMap,vh=new WeakMap,yh=new WeakMap,bh=new WeakMap,wh=new WeakMap,_h=new WeakMap,Sh=new WeakMap,kh=new WeakMap;class Mh extends Lh{constructor(e){super(e),this.transformParams={},Rh.set(this,void 0),Ph.set(this,void 0),Ch.set(this,!1),Th.set(this,(()=>{})),a(this,Ph,e,"f")}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished,isEffectsProcessing:this.isEffectsProcessing}}get isEffectsProcessing(){return Boolean(o(this,Rh,"f"))}getEncoderConfig(){return this.encoderConfig}getCodecOptions(){return{videoGoogleStartBitrate:this.getEncoderConfig().videoGoogleStartBitrate||1e3}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||(this.getLabel()===m.ScreenVideo?"vp8":"h264")}getEncodings(){return this.getEncoderConfig().encodings||jp}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return s(this,void 0,void 0,(function*(){const t=this.getProducer();t?(yield t.setMaxSpatialLayer(e),this.logger.debug("setMaxSpatialLayer()",{label:this.getLabel(),spatialLayer:e})):this.logger.warn("setMaxSpatialLayer()",{message:"Not produced yet"})}))}getMaxSpatialLayer(){const e=this.getProducer();if(e)return e.maxSpatialLayer;this.logger.warn("getMaxSpatialLayer()",{message:"Not produced yet"})}enableEffects(){return s(this,void 0,void 0,(function*(){if(!o(this,Ch,"f")){a(this,Ch,!0,"f");try{if(o(this,Rh,"f"))return this.logger.debug("enableEffects()",{description:"Track is already processed"}),void a(this,Ch,!1,"f");if("ended"===this.mediaStreamTrack.readyState)return void this.logger.warn("Track already ended",{case:"enableEffects"});const{media:e}=o(this,Ph,"f").engine;if(!e.effectsSDKInitialized)return void this.logger.warn("Effects SDK not initialized",{case:"enableEffects"});const t=Date.now();a(this,Rh,yield e.createEffectsSDKTrackProcessor(this.getLabel()),"f"),this.setOriginalTrack();const r=yield o(this,Rh,"f").processTrack(this.mediaStreamTrack),n=Date.now();this.logger.info("enableEffects() time",{time:(n-t)/1e3}),yield this.replaceTrack(r),this.logger.info("enableEffects()",{track:this.logCtx})}catch(e){this.logger.warn("enableEffects()",{track:this.logCtx,error:e}),this.disableEffects(),o(this,Th,"f").call(this,e)}finally{a(this,Ch,!1,"f")}}}))}disableEffects(){var e;return s(this,void 0,void 0,(function*(){try{if(!o(this,Rh,"f"))return void this.logger.debug("disableEffects()",{description:"Track is not processed"});this.originalTrack?yield this.replaceTrack(this.originalTrack):this.logger.warn("disableEffects()",{description:"Original track missing"}),null===(e=o(this,Rh,"f"))||void 0===e||e.stopProcessing(),a(this,Rh,void 0,"f"),this.logger.info("disableEffects()",{track:this.logCtx})}catch(e){this.logger.warn("disableEffects()",{track:this.logCtx,error:e})}}))}publish(e={}){var t;return s(this,void 0,void 0,(function*(){yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),transformParams:this.transformParams,codecOptions:this.getCodecOptions(),keyFrameRequestDelay:null!==(t=e.keyFrameRequestDelay)&&void 0!==t?t:0}),this.internalEventEmitter.emit(ne.trackProduced,this)}))}adjustEncodingPresetToCurrentMaxSpatialLayer(e){return s(this,void 0,void 0,(function*(){if(!$p(this.getPreferredCodec()))return;const{rtpSender:t}=this.getProducer()||{};if(!t)return void this.logger.warn("No rtpSender found in producer to change encodings",{maxSpatialLayer:e,trackId:this.id,producerId:this.producerId});const{encodings:r=[]}=this.getEncoderConfig(),n=r[e];if(!n)return void this.logger.warn("Skipping RTPSender params update. No target encoding found",{initialEncodings:r});this.logger.debug("Adjusting encoding parameters to max spatial layer",{targetEncoding:n,maxSpatialLayer:e});const i=t.getParameters();yield t.setParameters(Object.assign(Object.assign({},i),{encodings:[n]}))}))}applyEffects(e){var t;return s(this,void 0,void 0,(function*(){try{!this.isEffectsProcessing&&Object.keys(e).length>0&&(yield this.enableEffects()),null===(t=o(this,Rh,"f"))||void 0===t||t.updateEffects(e)}catch(e){o(this,Th,"f").call(this,e)}}))}resetEffects(){var e;return s(this,void 0,void 0,(function*(){null===(e=o(this,Rh,"f"))||void 0===e||e.updateEffects({})}))}setOnLoadModels(e){var t;null===(t=o(this,Rh,"f"))||void 0===t||t.setOnLoadModels(e)}get modelsLoadProgress(){var e;return(null===(e=o(this,Rh,"f"))||void 0===e?void 0:e.modelsLoadProgress)||0}pause(){return s(this,void 0,void 0,(function*(){yield this.mute((()=>{var e;o(this,Rh,"f")&&(null===(e=o(this,Rh,"f"))||void 0===e||e.stopProcessing(),a(this,Rh,void 0,"f"))}))}))}setOnEffectError(e){a(this,Th,e,"f")}}Rh=new WeakMap,Ph=new WeakMap,Ch=new WeakMap,Th=new WeakMap;const Ih=new class{sleepMs(e){return s(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}},xh=(e,t={})=>s(void 0,void 0,void 0,(function*(){var r;const n=t.maxRetries||2,i=t.minBackoffDelayMs||50;let s,o=0;for(;o<n;){o+=1;try{return yield e()}catch(e){if(s=e,t.logger&&t.logger.info("Action retry failed",{currentAttempt:o,actionName:t.actionName,error:e}),t.abortOnError&&t.abortOnError(e))throw s;if(o<n){const e=Math.pow(2,o-1)*i;yield Ih.sleepMs(Math.min(e,null!==(r=t.maxBackoffDelayMs)&&void 0!==r?r:e))}}}throw s}));class Oh extends b{constructor(e,t){super(e,null!=t?t:"need_join_first")}}var Ah,jh,Nh,Bh,Fh,Uh,qh,Wh,zh,$h;class Vh{constructor(){Ah.set(this,[]),jh.set(this,new Map),Nh.set(this,new Set),Bh.set(this,!1)}subscribeToSocket(e){o(this,Nh,"f").has(e)||(e.onAny(((e,...t)=>{this.push(e,t)})),o(this,Nh,"f").add(e))}subscribeToDataChannel(e){e.on("message",((...e)=>{this.push("message",e)}))}on(e,t){var r;o(this,jh,"f").has(e)?null===(r=o(this,jh,"f").get(e))||void 0===r||r.push(t):o(this,jh,"f").set(e,[t])}removeListener(e){o(this,jh,"f").delete(e)}removeAllListeners(e,t){t&&o(this,Nh,"f").has(t)&&(t.offAny(),o(this,Nh,"f").delete(t)),e.forEach((e=>{o(this,jh,"f").delete(e)}))}push(e,t){o(this,Ah,"f").push({event:e,args:t}),this.process()}process(){if(!o(this,Bh,"f"))for(;o(this,Ah,"f").length>0;){const e=o(this,Ah,"f").shift();this.emit(e.event,e.args)}}emit(e,t){(o(this,jh,"f").get(e)||[]).forEach((e=>{e(...t)}))}pause(){a(this,Bh,!0,"f")}resume(){a(this,Bh,!1,"f"),this.process()}}Ah=new WeakMap,jh=new WeakMap,Nh=new WeakMap,Bh=new WeakMap;class Hh{constructor(e){var t,r;this.initialized=!1,Fh.set(this,!1),this.isChannelJoining=!1,this.rejoinRequested=!1,this.isReleasing=!1,Uh.set(this,!1),qh.set(this,new Map),Wh.set(this,void 0);const{clientEventEmitter:n,internalEventEmitter:i,network:c,media:d,dependenciesFactory:l,logLevel:u,effectsSDKParams:p}=e;this.logLevel=u||mt,a(this,Wh,null===(t=e.sendAnalytics)||void 0===t||t,"f"),this.system=l.createSystem({logLevel:this.logLevel,clientEventEmitter:n,onLogMessage:e.onLogMessage,sendAnalytics:o(this,Wh,"f")}),this.media=l.createMedia({logLevel:this.logLevel,engine:this,internalEventEmitter:i,mediaTracksFactory:d.mediaTracksFactory,onLogMessage:e.onLogMessage,effectsSDKParams:p,sendAnalytics:o(this,Wh,"f")}),this.network=l.createNetwork({logLevel:this.logLevel,loadbalancer:c.loadbalancer,onLogMessage:e.onLogMessage,sendAnalytics:o(this,Wh,"f")}),this.logger=new $s({logLevel:this.logLevel,namespace:"Engine",onLogMessage:e.onLogMessage,sendAnalytics:o(this,Wh,"f")}),this.peersRepository=new Map,this.clientEventEmitter=n,this.internalEventEmitter=i,this.eventsQueue=new Vh,this.channelEventsHandler=l.createChannelEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.mediaSoupEventsHandler=l.createMediaSoupEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.channelAudioObserverEventHandler=l.createAudioObserverEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.channelStateSynchronizer=l.createChannelStateSynchronizer({engine:this,logLevel:this.logLevel,onLogMessage:e.onLogMessage,sendAnalytics:o(this,Wh,"f")}),this.webRtcIssueDetector=e.disableWid?void 0:l.createIssueDetector({engine:this,onIssues:e.onIssues,onNetworkScoresUpdated:e.onNetworkScoresUpdated,ignoreSSRCList:[1234],logger:new $s({logLevel:this.logLevel,namespace:"WID",sendAnalytics:o(this,Wh,"f")})}),this.channelStateSyncEventHandler=l.createChannelStateSyncEventHandler({engine:this,clientEventEmitter:n,webRTCIssueEmitter:null===(r=this.webRtcIssueDetector)||void 0===r?void 0:r.eventEmitter,onLogMessage:e.onLogMessage,sendAnalytics:o(this,Wh,"f")}),this.handleChannelAudioObserverEvent=e=>{this.channelAudioObserverEventHandler.handle(e)},this.handleDataChannelEvent=e=>{this.channelEventsHandler.handleDataChannelEvent(e)},this.handleChannelStateSyncEvent=e=>s(this,void 0,void 0,(function*(){yield this.channelStateSyncEventHandler.handle(e)})),this.watchNetworkState(),this.watchDocumentUnload()}get sendAnalytics(){return o(this,Wh,"f")}get isChannelJoined(){return o(this,Fh,"f")}initialize(){var e,t,r;return s(this,void 0,void 0,(function*(){try{const{rtpCapabilities:n}=yield this.network.socket.request("router.getRtpCapabilities");yield this.media.createNoiseSuppressor(),yield this.media.loadDevice(n),this.logger.info("Supported capabilities",{codecs:zp(this.media.mediasoupDevice)}),null===(e=this.webRtcIssueDetector)||void 0===e||e.watchNewPeerConnections(),yield Promise.all([this.network.createSendTransport(this.media.mediasoupDevice),this.network.createRecvTransport(this.media.mediasoupDevice)]),this.initialized=!0,this.logger.debug("initialize()",{sendTransportId:null===(t=this.network.sendTransport)||void 0===t?void 0:t.id,recvTransportId:null===(r=this.network.receiveTransport)||void 0===r?void 0:r.id})}catch(e){this.logger.error("initialize()",{error:e});const t=e instanceof v&&"device not supported"===e.message,r=e instanceof Error&&"RTCPeerConnection is not defined"===e.message;if(t||r)throw new w("Device not supported",w.UNSUPPORTED_DEVICE_CODE);throw new Error("Error initialize engine")}}))}release(){var e,t,r,n,i,o,c;return s(this,void 0,void 0,(function*(){if(!this.isReleasing){this.isReleasing=!0;try{this.initialized=!1,a(this,Fh,!1,"f"),this.app=void 0,this.channel=void 0,this.network.peerId=void 0,null===(e=this.webRtcIssueDetector)||void 0===e||e.stopWatchingNewPeerConnections(),this.peersRepository.forEach((e=>e.reset())),this.peersRepository.clear(),yield this.network.closeSendTransport(),yield this.network.closeReceiveTransport(),yield this.media.clearTracks(),null===(t=this.audioObserver)||void 0===t||t.removeListener("message",this.handleChannelAudioObserverEvent),null===(r=this.audioObserver)||void 0===r||r.close(),null===(n=this.generalDataConsumer)||void 0===n||n.removeListener("message",this.handleDataChannelEvent),this.eventsQueue.removeListener("message"),null===(i=this.generalDataConsumer)||void 0===i||i.close(),null===(o=this.channelStateSyncDataConsumer)||void 0===o||o.removeListener("message",this.handleChannelStateSyncEvent),null===(c=this.channelStateSyncDataConsumer)||void 0===c||c.close(),this.channelEventsHandler.reset(),this.mediaSoupEventsHandler.reset(),this.removeClientEventEmitterListeners(),yield this.network.reset(),this.network.socket.disconnect(),zs.clear(),this.logger.debug("release()",{socketId:this.myPeerId})}catch(e){throw this.logger.error("release()",{error:e}),new Error("Error release engine")}finally{this.isReleasing=!1}}}))}removeClientEventEmitterListeners(){Array.from(Object.values(ne)).forEach((e=>this.internalEventEmitter.removeAllListeners(e)))}get activeSpeaker(){return this.activeSpeakerPeer}get peers(){return Array.from(this.peersRepository.values())}get hostPeers(){return this.peers.filter((e=>"host"===e.role))}get audiencePeers(){return this.peers.filter((e=>"audience"===e.role))}get myPeerId(){return this.network.peerId}get isSocketConnectionActive(){try{return this.checkSocketConnectionActivity(),!0}catch(e){return!1}}getPeerById(e){return this.peersRepository.get(e)}checkSocketConnectionActivity(){var e;if(!this.channel||this.isChannelJoining)throw new Error("Connect to the channel first");if(!(null===(e=this.network.socket.connection)||void 0===e?void 0:e.active))throw new Error("Socket is inactive");if(!this.network.socket.connection.connected)throw new Error("Socket disconnected")}confirmActivity(){return s(this,void 0,void 0,(function*(){this.checkSocketConnectionActivity(),yield this.network.socket.request(C)}))}join(e){return s(this,void 0,void 0,(function*(){try{this.logger.debug("join()",{params:e}),this.isChannelJoining=!0,this.watchClientEvents(),yield this.connectToSocketServerWithRetry(e),yield this.performJoin({appData:e.appData})}catch(e){throw this.logger.error("join()",{error:e}),e}finally{this.isChannelJoining=!1,this.rejoinRequested=!1}}))}loadPeers(e){return s(this,void 0,void 0,(function*(){const{peers:t}=yield this.network.getChannelPeers(e);t.filter((e=>!this.peersRepository.has(e.id))).forEach((e=>this.setPeer(e)))}))}setPeer(e){const t=this.peersRepository.get(e.id);if(t)return t;const r=new Op(Object.assign(Object.assign({},e),{engine:this}));return this.peersRepository.set(r.id,r),this.clientEventEmitter.safeEmit(U,r),r}removePeer(e){const t=this.peersRepository.get(e);t&&(t.tracks.forEach((e=>e.close())),t.reset(),this.peersRepository.delete(e),this.clientEventEmitter.safeEmit(q,e))}registerTrack(e){const t=e.consumerId;if(t)return o(this,qh,"f").set(t,e),()=>{o(this,qh,"f").delete(t)}}getTrackByConsumerId(e){return o(this,qh,"f").get(e)}updateAppData(e){return s(this,void 0,void 0,(function*(){const{myPeer:t}=this;if(!t)throw new Error("Need join to channel first");try{Mp(e),yield this.network.updatePeerAppData({peerId:t.id,appData:e})}catch(e){throw this.logger.error("updateAppData()",{error:e}),new Error("Can not update peer appData")}}))}createCameraVideoTrack(e){return s(this,void 0,void 0,(function*(){const t=lh.getCameraVideoTrackParams(e);try{const[r]=yield this.media.createUserMediaTracks({audio:!1,video:t.videoTrackOptions});return r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof Mh&&(r.setLabel((null==e?void 0:e.isPreview)?m.CameraPreview:m.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(lh.getVideoTrackTransformParams(r.mediaStreamTrack))),this.media.setTrack(r),this.logger.debug("createCameraVideoTrack()",{trackParams:t}),r}catch(e){throw this.logger.error("createCameraVideoTrack()",{error:e,trackParams:t}),new Error(`Can not create camera track: ${e.message}`)}}))}createMicrophoneAudioTrack(e){return s(this,void 0,void 0,(function*(){try{const[t]=yield this.media.createUserMediaTracks({video:!1,audio:null==e?void 0:e.audio});if(t.setLabel((null==e?void 0:e.isPreview)?m.MicrophonePreview:m.Microphone),t.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),(null==e?void 0:e.encoderConfig)&&t.setEncoderConfig(e.encoderConfig),"audio"===t.kind&&(null==e?void 0:e.noiseSuppression))try{yield t.enableNoiseSuppression()}catch(e){this.logger.warn("Failed to start noise suppression, featured original track",{label:t.getLabel()})}return this.media.setTrack(t),this.logger.debug("createMicrophoneAudioTrack()",{options:e}),t}catch(t){throw this.logger.error("createMicrophoneAudioTrack()",{error:t,options:e}),new Error(`Can not create microphone track: ${t.message}`)}}))}createScreenMediaTracks(e){return s(this,void 0,void 0,(function*(){const t=lh.getScreenVideoTrackParams(e);try{const r=yield this.media.createDisplayMediaTracks({audio:null==e?void 0:e.audio,video:null==e?void 0:e.video});return r.forEach((r=>{if(r.mediaStreamTrack.addEventListener("ended",(()=>{r.unpublish()}),{once:!0}),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof Mh){r.setLabel(m.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=lh.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),this.media.setTrack(r),void this.logger.debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,label:r.logCtx})}r.setLabel(m.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(r),this.logger.debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig})})),r}catch(e){throw this.logger.error("createScreenMediaTrack()",{error:e,trackParams:t}),new Error(`Can not create screen media tracks: ${e.message}`)}}))}deleteTrack(e){return this.media.deleteTrack(e)}get channelId(){return this.channel}get appId(){return this.app}get canUseNoiseSuppression(){return this.media.isNoiseSuppressorLoaded}setActiveSpeakerPeer(e){this.activeSpeaker!==e&&(this.activeSpeakerPeer=e,this.clientEventEmitter.safeEmit(J,{peer:e}))}getNodeActiveStreamsStat(){var e;const t=this.network.socket.getServerUrl(),r=this.hostPeers.filter((e=>{var t;return e.id!==(null===(t=this.myPeer)||void 0===t?void 0:t.id)})).reduce(((e,t)=>e+t.getActiveTracksCount()),0);return{node:t,inboundActiveStreams:r,outboundActiveStreams:(null===(e=this.myPeer)||void 0===e?void 0:e.getActivePublishersCount())||0}}connectToSocketServerWithRetry(e){return s(this,void 0,void 0,(function*(){return xh((()=>s(this,void 0,void 0,(function*(){return this.connectToSocketServer(e)}))),{maxRetries:15,minBackoffDelayMs:150,maxBackoffDelayMs:5e3,actionName:"connectToSocketServer",logger:new $s({namespace:"RetrySocketConnect",logLevel:this.logLevel,sendAnalytics:o(this,Wh,"f")}),abortOnError:e=>{var t;return"unauthorized"===(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.errorCode)}})}))}connectToSocketServer(e){return s(this,void 0,void 0,(function*(){const{webSocketUrl:t}=yield this.getAvailableNode({channelId:e.channelId,role:e.role});this.network.socket.connect(t,e.token);try{yield this.waitForSocketConnection()}catch(r){throw this.logger.error("Failed to connect to socket server",{error:r,role:e.role,channelId:e.channelId,webSocketUrl:t}),this.network.socket.disconnect(),r}}))}getAvailableNode(e){return s(this,void 0,void 0,(function*(){try{return{webSocketUrl:(yield this.network.loadBalancerClient.getNode(e)).webSocketUrl}}catch(e){throw this.logger.error("getAvailableNode()",{error:"No available nodes"}),e}}))}waitForSocketConnection(){return new Promise(((e,t)=>{const r=n=>s(this,void 0,void 0,(function*(){const{error:i,state:s}=n,o=()=>this.network.socket.observer.removeListener(ch.State,r),a=[ch.Disconnected,ch.Reconnecting].includes(s);return i?(o(),void t(i)):this.isChannelJoining&&a?(o(),void t(new Error(`Not expected socket state for new connection: ${s}`))):void(this.isChannelJoining&&[ch.Connected,ch.Reconnected].includes(s)&&(o(),e()))}));this.network.socket.observer.on(ch.State,r)}))}performJoin(e){return s(this,void 0,void 0,(function*(){try{const{appId:t,channelId:r,peerId:n}=yield this.sendJoinChannelRequestWithRetry(e);this.network.peerId=n,this.app=t,this.channel=r,yield this.initialize(),this.channelEventsHandler.subscribeToEvents(),this.mediaSoupEventsHandler.subscribeToEvents(),a(this,Fh,!0,"f"),this.logger.debug("Successfully joined channel",{channelId:r}),yield Promise.all([this.createAudioObserver(),this.createGeneralDataConsumer(),this.createChannelStateSyncDataConsumer()]),zs.setPeerId(n),zs.setChannelId(r),zs.setAppId(t)}catch(e){throw this.logger.error("performJoin()",{error:e}),e}}))}sendJoinChannelRequestWithRetry(e){return s(this,void 0,void 0,(function*(){return xh((()=>s(this,void 0,void 0,(function*(){return this.sendJoinChannelRequest(e)}))),{maxRetries:3,minBackoffDelayMs:300,actionName:"sendJoinChannelRequest",logger:new $s({namespace:"RetryJoin",logLevel:this.logLevel,sendAnalytics:o(this,Wh,"f")})})}))}sendJoinChannelRequest(e){return s(this,void 0,void 0,(function*(){return this.network.socket.request(S,e)}))}get cahPublish(){var e;return"host"===(null===(e=this.peers.find((e=>e.isMe)))||void 0===e?void 0:e.role)}get myPeer(){return this.peers.find((e=>e.isMe))}watchClientEvents(){this.internalEventEmitter.on(ne.trackProduced,(e=>s(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(ne.trackUnproduced,(e=>s(this,void 0,void 0,(function*(){var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close(),yield this.media.deleteTrack(e)})))),this.internalEventEmitter.on(ne.trackPaused,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.pause()})),this.internalEventEmitter.on(ne.trackResumed,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.resume()})),this.internalEventEmitter.on(ne.trackClosed,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close()})),this.internalEventEmitter.on(ne.trackReopened,(e=>s(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(ne.trackFailed,(e=>s(this,void 0,void 0,(function*(){this.clientEventEmitter.safeEmit(Q,{label:e.getLabel()})}))))}createSelfPeerTrack(e){var t;return s(this,void 0,void 0,(function*(){const r=this.peersRepository.get(this.myPeerId);if(!r)return;yield null===(t=r.tracks.get(e.getLabel()))||void 0===t?void 0:t.close();const n=new Lp({mediaStreamTrack:e.mediaStreamTrack,label:e.getLabel(),engine:this,muted:!1,paused:e.isPaused,peerEventEmitter:r.observer});r.tracks.set(n.label,n)}))}createAudioObserver(){var e;return s(this,void 0,void 0,(function*(){if(!o(this,Fh,"f"))throw new Oh("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getAudioObserverProducer(),r=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId});r.on("message",this.handleChannelAudioObserverEvent),this.audioObserver=r,this.logger.debug("Successfully create audio observer",t)}catch(e){this.logger.error("Failed to create audio observer",t)}}))}createGeneralDataConsumer(){var e;return s(this,void 0,void 0,(function*(){if(!o(this,Fh,"f"))throw new Oh("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getGeneralDataProducer();this.generalDataConsumer=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId,ordered:!0}),this.eventsQueue.subscribeToDataChannel(this.generalDataConsumer),this.eventsQueue.on("message",this.handleDataChannelEvent),this.logger.debug("Successfully created general data consumer",Object.assign(Object.assign({},t),{producerId:e}))}catch(e){this.logger.error("Failed to create general data consumer",Object.assign(Object.assign({},t),{error:e}))}}))}createChannelStateSyncDataConsumer(){var e;return s(this,void 0,void 0,(function*(){if(!o(this,Fh,"f"))throw new Oh("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getChannelStateSyncDataProducer();this.channelStateSyncDataConsumer=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId}),this.channelStateSyncDataConsumer.on("message",this.handleChannelStateSyncEvent),this.logger.debug("Successfully created ChannelStateSyncDataConsumer",t)}catch(e){this.logger.error("Failed to create ChannelStateSyncDataConsumer",Object.assign(Object.assign({},t),{error:e}))}}))}triggerRejoinEventIfAppropriate(e){this.rejoinRequested&&!this.isChannelJoining||(this.logger.debug("Triggering channel rejoin required event",{reason:e}),this.rejoinRequested=!0,this.clientEventEmitter.emit(V))}watchNetworkState(){this.network.observer.on(qe,(e=>s(this,void 0,void 0,(function*(){var t;if(this.isReleasing)return;const{code:r,error:n,state:i}=e,s="unauthorized"===(null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.errorCode)&&this.isChannelJoined,c=r===ch.NeedToJoinFirst&&this.isChannelJoined;if(s&&this.clientEventEmitter.safeEmit(te),"server.disconnect"!==r||o(this,Uh,"f")){if(c||s){const e=s?"unauthorized error":"invalid channel state";this.triggerRejoinEventIfAppropriate(e)}i===ch.Disconnected&&this.isChannelJoined&&!o(this,Uh,"f")&&this.logger.info("connection lost",{channel:"socket"}),i===ch.Reconnected&&this.isChannelJoined&&this.logger.info("connection restored",{channel:"socket"}),i===ch.BufferingStart&&(a(this,Uh,!0,"f"),this.clientEventEmitter.safeEmit(Z)),[ch.BufferingEnd,ch.Reconnected].includes(i)&&this.network.isNetworkActive&&(a(this,Uh,!1,"f"),this.clientEventEmitter.safeEmit(X))}else this.clientEventEmitter.safeEmit(ee)})))),this.network.observer.on(We,(({state:e,direction:t})=>s(this,void 0,void 0,(function*(){if(!this.isReleasing&&(["disconnected","failed"].includes(e)&&this.isChannelJoined&&!o(this,Uh,"f")&&(a(this,Uh,!0,"f"),this.logger.info("connection lost",{channel:"webrtc-transport",direction:t}),this.clientEventEmitter.safeEmit(Z)),"reconnected"===e&&this.isChannelJoined&&this.logger.info("connection restored",{channel:"webrtc-transport",direction:t}),"reconnected"===e&&this.isChannelJoined&&o(this,Uh,"f"))){if(![this.network.receiveTransport,this.network.sendTransport].every((e=>"connected"===(null==e?void 0:e.connectionState)||"new"===(null==e?void 0:e.connectionState))))return;a(this,Uh,!1,"f"),this.clientEventEmitter.safeEmit(X)}}))))}watchDocumentUnload(){try{window.addEventListener("unload",(()=>{var e,t;null===(e=this.network.sendTransport)||void 0===e||e.close(),null===(t=this.network.receiveTransport)||void 0===t||t.close()}))}catch(e){this.logger.error("Failed to add watchDocumentUnload listener",{channelId:this.channelId})}}}Fh=new WeakMap,Uh=new WeakMap,qh=new WeakMap,Wh=new WeakMap;class Gh{constructor(e){var t;this.preferRelay=!1,zh.set(this,{send:void 0,recv:void 0}),$h.set(this,void 0);const{socketClient:r,loadBalancerApiClient:n,onLogMessage:i}=e;this.socket=r,this.loadBalancerClient=n,a(this,$h,null!==(t=e.eventEmitter)&&void 0!==t?t:new c,"f"),this.logger=new $s({namespace:"Network",logLevel:e.logLevel,onLogMessage:i,sendAnalytics:e.sendAnalytics}),this.socket.observer.on(ch.State,(e=>{o(this,$h,"f").safeEmit(qe,e)}))}get isNetworkActive(){var e,t,r,n,i;return!!(null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&["connected","new"].includes(null!==(r=null===(t=this.receiveTransport)||void 0===t?void 0:t.connectionState)&&void 0!==r?r:"")&&["connected","new"].includes(null!==(i=null===(n=this.sendTransport)||void 0===n?void 0:n.connectionState)&&void 0!==i?i:"")}get observer(){return o(this,$h,"f")}removeEventListeners(){const{sendTransport:e,receiveTransport:t}=this;if(e){["connect","produce","connectionstatechange"].forEach((t=>e.removeAllListeners(t)))}if(t){["connect","produce","connectionstatechange"].forEach((e=>t.removeAllListeners(e)))}}reset(){return s(this,void 0,void 0,(function*(){this.stopRestartIceAtempts(),this.removeEventListeners()}))}closeRemoteProducer(e){return s(this,void 0,void 0,(function*(){yield this.socket.request(ve,{peerId:this.peerId,producerId:e})}))}closeSendTransport(){var e;return s(this,void 0,void 0,(function*(){this.sendTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&(yield this.closeTransport(this.sendTransport)),this.sendTransport.close(),this.sendTransport=void 0):this.logger.warn("closeSendTransport()",{message:"No available send transport"})}))}closeReceiveTransport(){var e;return s(this,void 0,void 0,(function*(){this.receiveTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&(yield this.closeTransport(this.receiveTransport)),this.receiveTransport.close(),this.receiveTransport=void 0):this.logger.warn("closeReceiveTransport()",{message:"No available receive transport"})}))}closeTransport(e){return s(this,void 0,void 0,(function*(){try{e.close(),this.logger.debug("closeTransport()",{transportId:e.id,direction:e.direction})}catch(t){this.logger.error("closeTransport()",{error:t,transportId:e.id,direction:e.direction})}}))}createSendTransport(e){return s(this,void 0,void 0,(function*(){if(this.sendTransport)return void this.logger.warn("createSendTransport()",{message:"Send transport already exists"});const t=yield this.socket.request(Ae,{sctpCapabilities:e.sctpCapabilities,localDirection:"send"}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));this.logger.debug("createSendTransport()",{transportId:r.id,direction:r.direction}),this.sendTransport=r,this.subscribeCommonTransportEvents(r)}))}createRecvTransport(e){return s(this,void 0,void 0,(function*(){if(this.receiveTransport)return void this.logger.warn("createReceiveTransport()",{message:"Receive transport already exists"});const t=yield this.socket.request(Ae,{localDirection:"receive"}),r=e.createRecvTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));this.logger.debug("createReceiveTransport()",{transportId:r.id,direction:r.direction}),this.receiveTransport=r,this.subscribeCommonTransportEvents(r)}))}getIceParameters(e){return s(this,void 0,void 0,(function*(){const t=yield this.socket.request(Fe,{transportId:e.id}),{error:r}=t;if(r)throw new Error(r);const{iceParameters:n}=t;return this.logger.debug("getIceParameters()",{iceParameters:n}),n}))}restartIce(e){return s(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),this.logger.info("restartIce completed",{iceParameters:t})}catch(e){this.logger.error("restartIce error",{error:e})}}))}createConsumer({producerId:e,rtpCapabilities:t,appId:r,channelId:n,producerPeerId:i}){return s(this,void 0,void 0,(function*(){const s=this.receiveTransport;if(!s)throw this.logger.error("createConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");this.logger.debug("createConsumer()",{producerId:e});const o=yield this.socket.request(Ce,{producerId:e,transportId:s.id,rtpCapabilities:t,appData:{peerId:this.peerId,appId:r,channelId:n},producerPeerId:i}),a=yield s.consume(o),{producerPaused:c}=o;return this.logger.debug("Consumer created",{consumerId:a.id,label:a.appData.label,isProducerPaused:c}),{consumer:a,isProducerPaused:c}}))}createDataConsumer({producerId:e,appId:t,channelId:r,ordered:n}){return s(this,void 0,void 0,(function*(){const i=this.receiveTransport;if(!i)throw this.logger.error("createDataConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");this.logger.debug("createDataConsumer()",{producerId:e});const s=yield this.socket.request(Te,{ordered:n,dataProducerId:e,transportId:i.id,appData:{peerId:this.peerId,producerId:e,appId:t,channelId:r}}),o=yield i.consumeData(s);return this.logger.debug("Data consumer created",{consumerId:o.id}),o}))}closeRemoteConsumer(e){return s(this,void 0,void 0,(function*(){return this.socket.request(Ee,{peerId:this.peerId,consumerId:e})}))}resumeRemoteConsumer(e){return s(this,void 0,void 0,(function*(){return this.socket.request(Le,{consumerId:e})}))}pauseRemoteProducer(e){return s(this,void 0,void 0,(function*(){return this.socket.request(ye,{producerId:e})}))}pauseRemoteConsumer(e){return s(this,void 0,void 0,(function*(){return this.socket.request(De,{consumerId:e})}))}updatePeerAppData({peerId:e,appData:t}){return s(this,void 0,void 0,(function*(){return this.socket.request(P,{peerId:e,appData:t})}))}getAudioObserverProducer(){return s(this,void 0,void 0,(function*(){return this.socket.request(L)}))}getGeneralDataProducer(){return s(this,void 0,void 0,(function*(){return this.socket.request(M)}))}getChannelStateSyncDataProducer(){return s(this,void 0,void 0,(function*(){return this.socket.request(I)}))}getTransportsStateInfo(){return s(this,void 0,void 0,(function*(){const[e,t]=yield Promise.all([this.getParsedTransportStats(this.receiveTransport),this.getParsedTransportStats(this.sendTransport)]);return{receive:e,send:t}}))}setPreferRelay(e){this.preferRelay=e}getPreferRelay(){return this.preferRelay}getChannelPeers(e){return s(this,void 0,void 0,(function*(){return this.socket.request(k,{role:e})}))}getParsedTransportStats(e){return s(this,void 0,void 0,(function*(){if(e)try{const t=Array.from((yield e.getStats()).values()),r=t.find((e=>"local-candidate"===e.type)),n=t.find((e=>"remote-candidate"===e.type)),i=t.find((e=>"transport"===e.type));return{dtlsState:null==i?void 0:i.dtlsState,iceState:null==i?void 0:i.iceState,dtlsRole:null==i?void 0:i.dtlsRole,iceRole:null==i?void 0:i.iceRole,selectedCandidatePairChanges:null==i?void 0:i.selectedCandidatePairChanges,tlsVersion:null==i?void 0:i.tlsVersion,localCandidateState:{ip:null==r?void 0:r.ip,address:null==r?void 0:r.address,port:null==r?void 0:r.port,protocol:null==r?void 0:r.protocol,candidateType:null==r?void 0:r.candidateType},remoteCandidateState:{ip:null==n?void 0:n.ip,address:null==n?void 0:n.address,port:null==n?void 0:n.port,protocol:null==n?void 0:n.protocol,candidateType:null==n?void 0:n.candidateType}}}catch(e){return void this.logger.warn("getParsedTransportStats()",{error:e})}else this.logger.debug("getParsedTransportStats()",{message:"Transport is missing"})}))}logTransportDetails(e){var t,r;return s(this,void 0,void 0,(function*(){let n;try{n=yield e.getStats()}catch(t){return void this.logger.error("Failed to log detailed WebRTC transport stats",{error:ut(t),transportId:e.id,reason:"failed to parse getStats"})}try{const i=[...n],[,s]=null!==(t=i.find((([,e])=>"transport"===(null==e?void 0:e.type))))&&void 0!==t?t:[],[,o]=null!==(r=i.find((([,e])=>"candidate-pair"===e.type&&"succeeded"===e.state&&e.nominated)))&&void 0!==r?r:[],a=n.get(String((null==o?void 0:o.localCandidateId)||"-")),c=n.get(String((null==o?void 0:o.remoteCandidateId)||"-")),d={hasNominatedPair:!!o,transportId:e.id,iceRole:null==s?void 0:s.iceRole,iceState:null==s?void 0:s.iceState,dtlsRole:null==s?void 0:s.dtlsRole,dtlsState:null==s?void 0:s.dtlsState,local:{address:null==a?void 0:a.address,candidateType:null==a?void 0:a.candidateType,foundation:null==a?void 0:a.foundation,networkType:null==a?void 0:a.networkType,isRemote:null==a?void 0:a.isRemote,port:null==a?void 0:a.port,protocol:null==a?void 0:a.protocol,relatedAddress:null==a?void 0:a.relatedAddress,relatedPort:null==a?void 0:a.relatedPort,transportId:null==a?void 0:a.transportId,relayProtocol:null==a?void 0:a.relayProtocol,url:null==a?void 0:a.url},remote:{address:null==c?void 0:c.address,candidateType:null==c?void 0:c.candidateType,foundation:null==c?void 0:c.foundation,isRemote:null==c?void 0:c.isRemote,port:null==c?void 0:c.port,protocol:null==c?void 0:c.protocol,transportId:null==c?void 0:c.transportId}};(null==o?void 0:o.totalRoundTripTime)&&(null==o?void 0:o.responsesReceived)&&(d.pairRoundTripTime=Math.round(o.totalRoundTripTime/o.responsesReceived*1e3)),this.logger.info("Detailed WebRTC transport stats",d)}catch(t){this.logger.error("Failed to log detailed WebRTC transport stats",{error:ut(t),transportId:e.id,reason:"-"})}}))}stopRestartIceAtempts(){clearInterval(o(this,zh,"f").send),clearInterval(o(this,zh,"f").recv)}subscribeCommonTransportEvents(e){e.on("connect",(({dtlsParameters:t},r,n)=>s(this,void 0,void 0,(function*(){try{yield this.socket.request(je,{transportId:e.id,dtlsParameters:t}),r(),this.logger.debug(`${e.direction}Transport.connect()`,{transportId:e.id,dtlsRole:t.role}),setTimeout((()=>this.logTransportDetails(e)),1500)}catch(t){this.logger.error(`${e.direction}Transport.on('connect')`,{error:t}),n(t)}})))),e.on("produce",((t,r,n)=>s(this,void 0,void 0,(function*(){try{const{id:n}=yield this.socket.request(Ne,{transportId:e.id,kind:t.kind,rtpParameters:t.rtpParameters,appData:t.appData});r({id:n}),this.logger.debug(`${e.direction}Transport.produce()`,{producerId:n,transportId:e.id,kind:t.kind})}catch(r){this.logger.error(`${e.direction}Transport.produce()`,{error:r,transportId:e.id,kind:t.kind}),n(r)}})))),e.on("connectionstatechange",(t=>{if(this.logger.info(`${e.direction}Transport.state`,{state:t}),["closed","connected"].includes(t))return o(this,$h,"f").safeEmit(We,{state:t,direction:e.direction}),o(this,zh,"f")[e.direction]&&(this.logger.debug("Stop receiveTransport.restartIce() retries",{recvTransportId:e.id}),clearInterval(o(this,zh,"f")[e.direction]),o(this,zh,"f")[e.direction]=void 0,"connected"===t&&o(this,$h,"f").safeEmit(We,{state:"reconnected",direction:e.direction})),void("connected"===t&&setTimeout((()=>this.logTransportDetails(e)),1500));if(o(this,$h,"f").safeEmit(We,{state:t,direction:e.direction}),["disconnected","failed"].includes(t)){if(o(this,zh,"f")[e.direction])return;"failed"===t&&(this.logger.debug(`${e.direction}Transport.restartIce()`,{recvTransportId:e.id}),this.restartIce(e)),o(this,zh,"f")[e.direction]=setInterval((()=>{this.restartIce(e),this.logger.debug(`${e.direction}Transport.restartIce() attempt`,{recvTransportId:e.id})}),5e3)}})),e.on("icegatheringstatechange",(t=>{this.logger.info("icegatheringstatechange",{state:t,transportId:e.id,transportDirection:e.direction})}))}}zh=new WeakMap,$h=new WeakMap;class Kh{constructor(e){this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[];const{clientEventEmitter:t,logLevel:r,onLogMessage:n}=e;this.clientEventEmitter=t,this.logger=new $s({namespace:"System",logLevel:r,onLogMessage:n,sendAnalytics:e.sendAnalytics}),this.deviceChangeHandler=this.deviceChangeHandler.bind(this),this.listenDevices()}setIsEnableVideoDevicesLock(e){this.isEnableVideoDevicesLock=e}setIsEnableAudioDevicesLock(e){this.isEnableAudioDevicesLock=e}setAvailableVideoDevices(e){this.availableVideoDevices=e}setAvailableAudioDevices(e){this.availableAudioDevices=e}requestMediaDevicesAccess(e={video:!0,audio:!0}){return s(this,void 0,void 0,(function*(){try{return(yield navigator.mediaDevices.getUserMedia(e)).getTracks()}catch(t){if(this.logger.error("getUserMedia()",{error:t,constraints:e}),"NotAllowedError"===t.name)throw new Error(g.NotAllowedError);if("NotReadableError"===t.name)throw new Error(g.DeviceIsBusy);if("NotFoundError"===t.name)throw new Error(g.NotFoundError);throw new Error(g.RequestDevicesUnknownError)}}))}hasAvailableMediaDevicesList(){return s(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices();if(0===e.length)return!0;return e.every((e=>e.deviceId&&e.label))}))}refreshAvailableMediaDevicesList(){return s(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices(),t=[],r=[];e.forEach((e=>{""!==e.deviceId&&("videoinput"===e.kind&&t.push(e),"audioinput"===e.kind&&r.push(e))})),this.setAvailableVideoDevices(t),this.setAvailableAudioDevices(r);const n=({label:e,kind:t})=>({label:e,kind:t});return this.logger.debug("Devices list updated",{videoDevices:t.map(n),audioDevices:r.map(n)}),e}))}detectDevices(e){return s(this,void 0,void 0,(function*(){if(this.isDevicesDetected&&!e)return;(yield this.hasAvailableMediaDevicesList())||(yield this.tryToAccessDevices()),this.isDevicesDetected=!0;const t=yield this.refreshAvailableMediaDevicesList(),r=t.some((e=>"audioinput"===e.kind)),n=t.some((e=>"videoinput"===e.kind));if(!r&&!n)throw new Error(g.NoDevices)}))}deviceChangeHandler(){return s(this,void 0,void 0,(function*(){this.isDevicesDetected&&(yield this.refreshAvailableMediaDevicesList(),this.clientEventEmitter.safeEmit(H,{audio:this.availableAudioDevices,video:this.availableVideoDevices}))}))}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}assertHasAccessToMediaDevices(e={video:!0,audio:!0}){return s(this,void 0,void 0,(function*(){(yield this.requestMediaDevicesAccess(e)).forEach((e=>e.stop()))}))}tryToAccessDevices(){return s(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess()).forEach((e=>e.stop()))}catch(t){if(e=t.message,![g.NotFoundError,g.NotAllowedError,g.DeviceIsBusy].includes(e))throw t;t.message!==g.DeviceIsBusy&&(yield this.assertHasAccessToMediaDevices({audio:!0}),yield this.assertHasAccessToMediaDevices({video:!0}))}var e}))}}class Qh{constructor(e){const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new $s({logLevel:t.logLevel,namespace:"ChannelEvents",onLogMessage:r,sendAnalytics:t.sendAnalytics})}handleDataChannelEvent(e){try{const{event:t,data:r}=JSON.parse(e);this.doHandleDataChannelEvent(t,r)}catch(t){this.logger.error("Failed to handle data channel event",{error:t,payload:e})}}doHandleDataChannelEvent(e,t){e===P&&this.handlePeerAppDataUpdate(t)}subscribeToEvents(){const{connection:e}=this.engine.network.socket;if(!e)throw this.logger.error("subscribeToEvents()",{error:"Socket connection not initialized"}),new Error("Socket connection not initialized");this.engine.eventsQueue.subscribeToSocket(e),this.engine.eventsQueue.on(_,(e=>{this.engine.clientEventEmitter.safeEmit(F,e),this.logger.debug("New channel event",{event:e})})),this.engine.eventsQueue.on(S,(e=>{const t=this.engine.setPeer(e);this.logger.debug("Peer joined to the channel",{peer:Ip(t)})})),this.engine.eventsQueue.on(R,(e=>{this.engine.removePeer(e),this.logger.debug("Peer left the channel",{peerId:e})})),this.engine.eventsQueue.on(E,(e=>{this.engine.clientEventEmitter.safeEmit(W,e),this.logger.info("Notify the channel that activity confirmation is required",e)})),this.engine.eventsQueue.on(D,(e=>{this.engine.clientEventEmitter.safeEmit($,e),this.logger.info("Notify the channel that it has disconnected due to the activity confirmation expiring",e)})),this.engine.eventsQueue.on(T,(e=>{this.engine.clientEventEmitter.safeEmit(z,e),this.logger.info("Notify the channel that the activity has been acquired.",e)})),this.engine.eventsQueue.on(x,(e=>{const{producePermissions:t,groups:r,changedProducePermissions:n}=e;this.engine.peers.filter((e=>e.groups.some((e=>r.includes(e))))).forEach((e=>{const r=Array.from(new Set([...e.producePermissions,...n])).filter((e=>!n.includes(e)||t.includes(e)));e.handleProducePermissionsChange(r)})),this.logger.info("Peers changed produce permissions",{groups:r,producePermissions:t})})),this.engine.eventsQueue.on(A,(e=>{const{peerId:t,producePermissions:r}=e,n=this.engine.peersRepository.get(t);n&&n.handleProducePermissionsChange(r)})),this.engine.eventsQueue.on(O,(e=>{const{producePermissions:t,groups:r}=e;this.engine.peers.filter((e=>e.groups.some((e=>r.includes(e))))).forEach((e=>{const r=e.producePermissions.filter((e=>!t.includes(e)));e.handleProducePermissionsChange(r)})),this.logger.info("Peers deleted produce permissions",{groups:r,producePermissions:t})}))}removeEventListeners(){if(!this.engine.eventsQueue)return;const e=[_,S,R,E,D,T,P,x],{connection:t}=this.engine.network.socket;this.engine.eventsQueue.removeAllListeners(e,t)}handlePeerAppDataUpdate({peerId:e,appData:t}){const r=this.engine.peers.find((({id:t})=>t===e));r&&r.observer.emit(P,t)}reset(){this.removeEventListeners()}}class Jh{constructor(e){this.queue=new Dp;const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new $s({logLevel:t.logLevel,namespace:"MediasoupEvents",onLogMessage:r,sendAnalytics:t.sendAnalytics})}subscribeToEvents(){const{connection:e}=this.engine.network.socket;if(!e)throw this.logger.error("subscribeToEvents()",{error:"Socket connection not initialized"}),new Error("Socket connection not initialized");this.engine.eventsQueue.subscribeToSocket(e),this.engine.eventsQueue.on(ve,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&t.observer.safeEmit(ve,e)})),this.engine.eventsQueue.on(ge,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&t.observer.safeEmit(ge,e)})),this.engine.eventsQueue.on(Ee,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&r.observer.safeEmit(Ee,e)})),this.engine.eventsQueue.on(Le,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(Le,e)})),this.engine.eventsQueue.on(De,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(De,e)})),this.engine.eventsQueue.on(Ie,(({peerId:e,spatialLayer:t,temporalLayer:r,consumerId:n})=>{const i=this.engine.peers.find((t=>t.id===e));i&&!i.isMe&&i.observer.safeEmit(Ie,{consumerId:n,spatialLayer:t,temporalLayer:r})})),this.engine.eventsQueue.on(Me,(e=>{const{consumerPeerId:t}=e,r=this.engine.peers.find((e=>e.id===t));if(!r||r.isMe)return;r.observer.safeEmit(Me,e);const n=this.engine.peers.find((e=>e.isMe));n&&n.observer.safeEmit(Me,e)})),this.engine.eventsQueue.on(ke,(e=>{const t=this.engine.peers.find((e=>e.isMe));t&&t.observer.safeEmit(ke,e)})),this.engine.eventsQueue.on(Pe,(({producerId:e,spatialLayer:t})=>s(this,void 0,void 0,(function*(){yield this.queue.push((()=>s(this,void 0,void 0,(function*(){yield this.handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t})}))),Pe)})))),this.engine.eventsQueue.on(Re,(({peerId:e,producerId:t,spatialLayer:r})=>s(this,void 0,void 0,(function*(){const n=this.engine.peers.find((t=>t.id===e));n&&!n.isMe&&n.observer.safeEmit(Re,{peerId:e,producerId:t,spatialLayer:r})})))),this.engine.eventsQueue.on(Be,(({reason:e,transportId:t,direction:r,timeout:n})=>s(this,void 0,void 0,(function*(){const i=[this.engine.network.receiveTransport,this.engine.network.sendTransport].find((e=>(null==e?void 0:e.id)===t));i&&"connected"!==i.connectionState&&(this.logger.warn(Be,{reason:e,transportId:t,direction:r,timeout:n}),this.engine.clientEventEmitter.emit(G,{direction:r,reason:e}))})))),this.engine.eventsQueue.on(we,(({peerId:e,producerId:t})=>{const r=this.engine.peers.find((t=>t.id===e)),n=null==r?void 0:r.producers.get(t);r&&n&&(n.paused=!0,r.observer.safeEmit(oe,{producerId:n.id,kind:n.kind,label:n.label,paused:n.paused}))})),this.engine.eventsQueue.on(_e,(({peerId:e,producerId:t})=>{const r=this.engine.peers.find((t=>t.id===e)),n=null==r?void 0:r.producers.get(t);r&&n&&(n.paused=!1,r.observer.safeEmit(ae,{producerId:n.id,kind:n.kind,label:n.label,paused:n.paused}))})),this.engine.eventsQueue.on(Se,(({label:e})=>s(this,void 0,void 0,(function*(){const t=this.engine.media.getTrack(e);t&&(t.stopMediaStreamTrack(),this.engine.internalEventEmitter.safeEmit(ne.trackClosed,t),this.engine.clientEventEmitter.emit(K,{label:e}),yield this.engine.media.deleteTrack(t))}))))}removeEventListeners(){if(!this.engine.eventsQueue)return;const e=[ve,ge,Ee,Le,De,Ie,Me,ke,Pe,Re,Be,we,_e,Se],{connection:t}=this.engine.network.socket;this.engine.eventsQueue.removeAllListeners(e,t)}reset(){this.removeEventListeners()}handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t}){return s(this,void 0,void 0,(function*(){const r=this.engine.media.getAllTracks().find((t=>{var r;return(null===(r=t.getProducer())||void 0===r?void 0:r.id)===e}));if(!r)return void this.logger.warn("producerRequestMaxSpatialLayer()",{message:"Producer not found"});if(!(r instanceof Mh))return void this.logger.warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const n=t||0,i=r.getMaxSpatialLayer();i!==n?(r.getEncodings().length>1&&(yield r.setMaxSpatialLayer(n)),yield this.engine.network.socket.request(Re,{producerId:e,maxSpatialLayer:n}),yield r.adjustEncodingPresetToCurrentMaxSpatialLayer(n)):this.logger.debug("producerRequestMaxSpatialLayer()",{message:"Skip set max spatial layer",requestedSpatialLayer:n,currentMaxSpatialLayer:i})}))}}const Yh=Object.create(null);Yh.open="0",Yh.close="1",Yh.ping="2",Yh.pong="3",Yh.message="4",Yh.upgrade="5",Yh.noop="6";const Zh=Object.create(null);Object.keys(Yh).forEach((e=>{Zh[Yh[e]]=e}));const Xh={type:"error",data:"parser error"},ef="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),tf="function"==typeof ArrayBuffer,rf=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,nf=({type:e,data:t},r,n)=>ef&&t instanceof Blob?r?n(t):sf(t,n):tf&&(t instanceof ArrayBuffer||rf(t))?r?n(t):sf(new Blob([t]),n):n(Yh[e]+(t||"")),sf=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function of(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let af;const cf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",df="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<cf.length;e++)df[cf.charCodeAt(e)]=e;const lf="function"==typeof ArrayBuffer,uf=(e,t)=>{if("string"!=typeof e)return{type:"message",data:hf(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:pf(e.substring(1),t)};return Zh[r]?e.length>1?{type:Zh[r],data:e.substring(1)}:{type:Zh[r]}:Xh},pf=(e,t)=>{if(lf){const r=(e=>{let t,r,n,i,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=df[e.charCodeAt(t)],n=df[e.charCodeAt(t+1)],i=df[e.charCodeAt(t+2)],s=df[e.charCodeAt(t+3)],l[c++]=r<<2|n>>4,l[c++]=(15&n)<<4|i>>2,l[c++]=(3&i)<<6|63&s;return d})(e);return hf(r,t)}return{base64:!0,data:e}},hf=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,ff=String.fromCharCode(30);function mf(){return new TransformStream({transform(e,t){!function(e,t){ef&&e.data instanceof Blob?e.data.arrayBuffer().then(of).then(t):tf&&(e.data instanceof ArrayBuffer||rf(e.data))?t(of(e.data)):nf(e,!1,(e=>{af||(af=new TextEncoder),t(af.encode(e))}))}(e,(r=>{const n=r.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(r)}))}})}let gf;function vf(e){return e.reduce(((e,t)=>e+t.length),0)}function yf(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function bf(e){if(e)return function(e){for(var t in bf.prototype)e[t]=bf.prototype[t];return e}(e)}bf.prototype.on=bf.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},bf.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},bf.prototype.off=bf.prototype.removeListener=bf.prototype.removeAllListeners=bf.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},bf.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},bf.prototype.emitReserved=bf.prototype.emit,bf.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},bf.prototype.hasListeners=function(e){return!!this.listeners(e).length};const wf="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function _f(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Sf=wf.setTimeout,kf=wf.clearTimeout;function Rf(e,t){t.useNativeTimers?(e.setTimeoutFn=Sf.bind(wf),e.clearTimeoutFn=kf.bind(wf)):(e.setTimeoutFn=wf.setTimeout.bind(wf),e.clearTimeoutFn=wf.clearTimeout.bind(wf))}class Pf extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class Cf extends bf{constructor(e){super(),this.writable=!1,Rf(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new Pf(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=uf(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const Tf="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),Ef={};let Df,Lf=0,Mf=0;function If(e){let t="";do{t=Tf[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function xf(){const e=If(+new Date);return e!==Df?(Lf=0,Df=e):e+"."+If(Lf++)}for(;Mf<64;Mf++)Ef[Tf[Mf]]=Mf;let Of=!1;try{Of="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(eg){}const Af=Of;function jf(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Af))return new XMLHttpRequest}catch(e){}if(!t)try{return new(wf[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function Nf(){}const Bf=null!=new jf({xdomain:!1}).responseType;class Ff extends bf{constructor(e,t){super(),Rf(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=_f(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const r=this.xhr=new jf(t);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=Ff.requestsCount++,Ff.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Nf,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Ff.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(Ff.requestsCount=0,Ff.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Uf);else if("function"==typeof addEventListener){addEventListener("onpagehide"in wf?"pagehide":"unload",Uf,!1)}function Uf(){for(let e in Ff.requests)Ff.requests.hasOwnProperty(e)&&Ff.requests[e].abort()}const qf="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Wf=wf.WebSocket||wf.MozWebSocket,zf="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const $f={websocket:class extends Cf{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=zf?{}:_f(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=zf?new Wf(e,t,r):t?new Wf(e,t):new Wf(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;nf(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}n&&qf((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=xf()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Wf}},webtransport:class extends Cf{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((e=>{this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=function(e,t){gf||(gf=new TextDecoder);const r=[];let n=0,i=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===n){if(vf(r)<1)break;const e=yf(r,1);s=128==(128&e[0]),i=127&e[0],n=i<126?3:126===i?1:2}else if(1===n){if(vf(r)<2)break;const e=yf(r,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(vf(r)<8)break;const e=yf(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(Xh);break}i=s*Math.pow(2,32)+t.getUint32(4),n=3}else{if(vf(r)<i)break;const e=yf(r,i);a.enqueue(uf(s?e:gf.decode(e),t)),n=0}if(0===i||i>e){a.enqueue(Xh);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=mf();n.readable.pipeTo(e.writable),this.writer=n.writable.getWriter();const i=()=>{r.read().then((({done:e,value:t})=>{e||(this.onPacket(t),i())})).catch((e=>{}))};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;this.writer.write(r).then((()=>{n&&qf((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends Cf{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=Bf&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(ff),n=[];for(let e=0;e<r.length;e++){const i=uf(r[e],t);if(n.push(i),"error"===i.type)break}return n})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach(((e,s)=>{nf(e,!1,(e=>{n[s]=e,++i===r&&t(n.join(ff))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=xf()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Ff(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},Vf=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hf=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Gf(e){const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=Vf.exec(e||""),s={},o=14;for(;o--;)s[Hf[o]]=i[o]||"";return-1!=r&&-1!=n&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(r[t]=n)})),r}(0,s.query),s}class Kf extends bf{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Gf(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Gf(t.host).host),Rf(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new $f[e](r)}open(){let e;if(this.opts.rememberUpgrade&&Kf.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){let t=this.createTransport(e),r=!1;Kf.priorWebsocketSuccess=!1;const n=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",(e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Kf.priorWebsocketSuccess="websocket"===t.name,this.transport.pause((()=>{r||"closed"!==this.readyState&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}})))};function i(){r||(r=!0,d(),t.close(),t=null)}const s=e=>{const r=new Error("probe error: "+e);r.transport=t.name,i(),this.emitReserved("upgradeError",r)};function o(){s("transport closed")}function a(){s("socket closed")}function c(e){t&&e.name!==t.name&&i()}const d=()=>{t.removeListener("open",n),t.removeListener("error",s),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",n),t.once("error",s),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((()=>{r||t.open()}),200):t.open()}onOpen(){if(this.readyState="open",Kf.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let r=0;r<this.writeBuffer.length;r++){const n=this.writeBuffer[r].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}var t;return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?r():e()})):this.upgrading?r():e()),this}onError(e){Kf.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}Kf.protocol=4;const Qf="function"==typeof ArrayBuffer,Jf=Object.prototype.toString,Yf="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Jf.call(Blob),Zf="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Jf.call(File);function Xf(e){return Qf&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Yf&&e instanceof Blob||Zf&&e instanceof File}function em(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(em(e[t]))return!0;return!1}if(Xf(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return em(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&em(e[t]))return!0;return!1}function tm(e){const t=[],r=e.data,n=e;return n.data=rm(r,t),n.attachments=t.length,{packet:n,buffers:t}}function rm(e,t){if(!e)return e;if(Xf(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=rm(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=rm(e[n],t));return r}return e}function nm(e,t){return e.data=im(e.data,t),delete e.attachments,e}function im(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=im(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=im(e[r],t));return e}const sm=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var om;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(om||(om={}));function am(e){return"[object Object]"===Object.prototype.toString.call(e)}class cm extends bf{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===om.BINARY_EVENT;r||t.type===om.BINARY_ACK?(t.type=r?om.EVENT:om.ACK,this.reconstructor=new dm(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Xf(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===om[r.type])throw new Error("unknown packet type "+r.type);if(r.type===om.BINARY_EVENT||r.type===om.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!cm.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case om.CONNECT:return am(t);case om.DISCONNECT:return void 0===t;case om.CONNECT_ERROR:return"string"==typeof t||am(t);case om.EVENT:case om.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===sm.indexOf(t[0]));case om.ACK:case om.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class dm{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=nm(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var lm=Object.freeze({__proto__:null,protocol:5,get PacketType(){return om},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==om.EVENT&&e.type!==om.ACK||!em(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===om.EVENT?om.BINARY_EVENT:om.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==om.BINARY_EVENT&&e.type!==om.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=tm(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}},Decoder:cm});function um(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const pm=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class hm extends bf{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[um(e,"open",this.onopen.bind(this)),um(e,"packet",this.onpacket.bind(this)),um(e,"error",this.onerror.bind(this)),um(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(pm.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:om.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const i=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,i)=>{t.push(((e,t)=>r?e?i(e):n(t):n(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...n)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()})),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:om.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case om.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case om.EVENT:case om.BINARY_EVENT:this.onevent(e);break;case om.ACK:case om.BINARY_ACK:this.onack(e);break;case om.DISCONNECT:this.ondisconnect();break;case om.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...n){r||(r=!0,t.packet({type:om.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:om.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function fm(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}fm.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},fm.prototype.reset=function(){this.attempts=0},fm.prototype.setMin=function(e){this.ms=e},fm.prototype.setMax=function(e){this.max=e},fm.prototype.setJitter=function(e){this.jitter=e};class mm extends bf{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Rf(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new fm({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||lm;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Kf(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=um(t,"open",(function(){r.onopen(),e&&e()})),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=um(t,"error",i);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn((()=>{n(),i(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}return this.subs.push(n),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(um(e,"ping",this.onping.bind(this)),um(e,"data",this.ondata.bind(this)),um(e,"error",this.onerror.bind(this)),um(e,"close",this.onclose.bind(this)),um(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){qf((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new hm(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const gm={};function vm(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),n=Gf(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,s=r.path,o=gm[i]&&s in gm[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new mm(n,t):(gm[i]||(gm[i]=new mm(n,t)),a=gm[i]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}var ym,bm,wm,_m;Object.assign(vm,{Manager:mm,Socket:hm,io:vm,connect:vm});class Sm{constructor(e){this.reconnectingAttempt=0,this.isConnected=!1,this._observer=new c,this.knownDisconnectReasonsCodes={"io server disconnect":"server.disconnect","io client disconnect":"client.disconnect","ping timeout":"ping.timeout","transport close":"transport.close","transport error":"transport.error"},ym.set(this,100),bm.set(this,!1),wm.set(this,8e3),this.logger=new $s({namespace:"Socket",logLevel:e.logLevel,onLogMessage:e.onLogMessage,sendAnalytics:e.sendAnalytics})}get observer(){return this._observer}get id(){var e;return null===(e=this.connection)||void 0===e?void 0:e.id}connect(e,t){const r=vm(e,{multiplex:!0,randomizationFactor:.2,reconnectionDelay:1e3,reconnection:!0,transports:["polling","websocket"],upgrade:!0,rememberUpgrade:!1,auth:{token:t,apiVersion:4}});this.connection=r,this.serverUrl=e,r.on(ch.Connect,(()=>{const e=this.reconnectingAttempt?ch.Reconnected:ch.Connected;this.isConnected=!0,this.setReconnectingAttempt(0),this.logger.debug(`connection.on('${ch.Connect}')`,{connectionId:r.id,recovered:r.recovered}),this.observer.safeEmit(ch.State,{state:e})})),r.on(ch.ConnectError,(e=>{this.connectionError=e,this.logger.error(`connection.on('${ch.ConnectError}')`,{error:e}),this.observer.safeEmit(ch.State,{state:ch.Error,error:e}),this.reconnectingAttempt>o(this,ym,"f")&&(r.disconnect(),this.observer.safeEmit(ch.State,{state:ch.Disconnected,code:"server.disconnect"}))})),r.on(ch.Disconnect,(e=>{this.isConnected=!1,this.setReconnectingAttempt(0),this.disconnectReason=e,this.logger.info(`connection.on('${ch.Disconnect}')`,{reason:e});const t=this.getDisconnectReasonCode(e);"server.disconnect"===t&&r.disconnect(),this.observer.safeEmit(ch.State,{state:ch.Disconnected,code:t})})),r.io.on(ch.ReconnectAttempt,(e=>{this.setReconnectingAttempt(e),this.logger.info(`connection.on('${ch.ReconnectAttempt}')`,{attempt:e}),this.observer.safeEmit(ch.State,{state:ch.Reconnecting})})),r.io.on(ch.Reconnect,(()=>{this.logger.debug(`connection.on('${ch.Reconnect}')`,{connectionId:r.id}),this.observer.safeEmit(ch.State,{state:ch.Reconnect})}))}disconnect(){this.connection&&(this.connection.offAny(),this.connection.volatile.offAny(),this.connection.disconnect(),this.connection.io.removeAllListeners(),this.setReconnectingAttempt(0))}request(e,t={}){return new Promise(((r,n)=>{this.connection?this.connection.timeout(o(this,wm,"f")).emit(e,t,((t,i)=>{if(t){const r=Ue.includes(e);return"operation has timed out"===(null==t?void 0:t.message)&&!o(this,bm,"f")&&r&&(a(this,bm,!0,"f"),this.observer.safeEmit(ch.State,{state:ch.BufferingStart})),void n(t)}i&&i.error?("Need join to channel first"===i.error&&this.observer.safeEmit(ch.State,{code:ch.NeedToJoinFirst}),n(i.error)):(o(this,bm,"f")&&(a(this,bm,!1,"f"),this.observer.safeEmit(ch.State,{state:ch.BufferingEnd})),r(i))})):n(new Error("Socket request: Socket connection is not initialized"))}))}getServerUrl(){return this.serverUrl}getDisconnectReasonCode(e){const t=String(e).toLowerCase();return this.knownDisconnectReasonsCodes[t]||t}setReconnectingAttempt(e){this.reconnectingAttempt=e}}ym=new WeakMap,bm=new WeakMap,wm=new WeakMap;class km{constructor(e){const{baseURL:t,timeout:r,customNode:n}=e;this.api=Kr.create({baseURL:t||"https://lb.livedigital.space/v1",timeout:r||5e3,withCredentials:!1,paramsSerializer:e=>us.stringify(e)}),this.customNode=n}getNode(e){return s(this,void 0,void 0,(function*(){if(this.customNode)return this.customNode;const{data:t}=yield this.api.get("/nodes/best",{params:e});return t}))}}class Rm extends b{constructor(e,t){super(e,null!=t?t:"invalid_payload")}}!function(e){e.DominantSpeaker="dominant-speaker",e.PeersVolumes="peers-volumes",e.Silence="silence"}(_m||(_m={}));class Pm{constructor(e){const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new $s({logLevel:t.logLevel,namespace:"ChannelAudioObserverEventHandler",onLogMessage:r,sendAnalytics:t.sendAnalytics})}handle(e){try{const t=JSON.parse(e);switch(Pm.validateEventPayload(t),t.event){case _m.DominantSpeaker:this.handleDominantSpeaker(t);break;case _m.PeersVolumes:this.handlePeerVolumes(t);break;case _m.Silence:this.handleSilence()}}catch(t){this.logger.warn("Failed to handle audio observer event",{error:ut(t),eventData:e})}}handleDominantSpeaker(e){const{peerId:t}=e.data,r=this.engine.getPeerById(t);this.engine.setActiveSpeakerPeer(r)}handlePeerVolumes(e){e.volumes.forEach((e=>{var t;const{peerId:r,trackLabel:n,value:i}=e,s=null===(t=this.engine.getPeerById(r))||void 0===t?void 0:t.tracks.get(n);s&&s.setVolume(i)}))}handleSilence(){this.engine.peers.flatMap((e=>Array.from(e.tracks.values()))).forEach((e=>e.setVolume(0))),this.engine.setActiveSpeakerPeer(void 0)}static validateEventPayload(e){switch(e.event){case _m.Silence:break;case _m.DominantSpeaker:{e.data||Pm.throwInvalidPayload();const{peerId:t,producerId:r,trackLabel:n}=e.data;"string"==typeof t&&"string"==typeof r&&n===m.Microphone||Pm.throwInvalidPayload();break}case _m.PeersVolumes:Array.isArray(e.volumes)||Pm.throwInvalidPayload(),e.volumes.forEach((e=>{const{peerId:t,producerId:r,value:n,trackLabel:i}=e;"string"==typeof t&&"string"==typeof r&&"number"==typeof n&&i===m.Microphone||Pm.throwInvalidPayload()}));break;default:Pm.throwInvalidPayload()}}static throwInvalidPayload(){throw new Rm("Invalid channel audio observer event handler payload")}}function Cm(e,t){var r,n;if(0===t.length)return e;for(r=0,n=t.length;r<n;r++)e=(e<<5)-e+t.charCodeAt(r),e|=0;return e<0?-2*e:e}function Tm(e,t,r,n){var i=Cm(Cm(Cm(e,r),function(e){return Object.prototype.toString.call(e)}(t)),typeof t);if(null===t)return Cm(i,"null");if(void 0===t)return Cm(i,"undefined");if("object"==typeof t||"function"==typeof t){if(-1!==n.indexOf(t))return Cm(i,"[Circular]"+r);n.push(t);var s=function(e,t,r){return Object.keys(t).sort().reduce((function(e,n){return Tm(e,t[n],n,r)}),e)}(i,t,n);if(!("valueOf"in t)||"function"!=typeof t.valueOf)return s;try{return Cm(s,String(t.valueOf()))}catch(e){return Cm(s,"[valueOf exception]"+(e.stack||e.message))}}return Cm(i,t.toString())}var Em=function(e){return function(e,t){for(;e.length<t;)e="0"+e;return e}(Tm(0,e,"",[]).toString(16),8)},Dm=Uint8Array,Lm=Uint16Array,Mm=Int32Array,Im=new Dm([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),xm=new Dm([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Om=new Dm([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Am=function(e,t){for(var r=new Lm(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var i=new Mm(r[30]);for(n=1;n<30;++n)for(var s=r[n];s<r[n+1];++s)i[s]=s-r[n]<<5|n;return{b:r,r:i}},jm=Am(Im,2),Nm=jm.b,Bm=jm.r;Nm[28]=258,Bm[258]=28;for(var Fm=Am(xm,0).b,Um=new Lm(32768),qm=0;qm<32768;++qm){var Wm=(43690&qm)>>1|(21845&qm)<<1;Wm=(61680&(Wm=(52428&Wm)>>2|(13107&Wm)<<2))>>4|(3855&Wm)<<4,Um[qm]=((65280&Wm)>>8|(255&Wm)<<8)>>1}var zm=function(e,t,r){for(var n=e.length,i=0,s=new Lm(t);i<n;++i)e[i]&&++s[e[i]-1];var o,a=new Lm(t);for(i=1;i<t;++i)a[i]=a[i-1]+s[i-1]<<1;if(r){o=new Lm(1<<t);var c=15-t;for(i=0;i<n;++i)if(e[i])for(var d=i<<4|e[i],l=t-e[i],u=a[e[i]-1]++<<l,p=u|(1<<l)-1;u<=p;++u)o[Um[u]>>c]=d}else for(o=new Lm(n),i=0;i<n;++i)e[i]&&(o[i]=Um[a[e[i]-1]++]>>15-e[i]);return o},$m=new Dm(288);for(qm=0;qm<144;++qm)$m[qm]=8;for(qm=144;qm<256;++qm)$m[qm]=9;for(qm=256;qm<280;++qm)$m[qm]=7;for(qm=280;qm<288;++qm)$m[qm]=8;var Vm=new Dm(32);for(qm=0;qm<32;++qm)Vm[qm]=5;var Hm=zm($m,9,1),Gm=zm(Vm,5,1),Km=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Qm=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},Jm=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Ym=function(e){return(e+7)/8|0},Zm=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new Dm(e.subarray(t,r))},Xm=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],eg=function(e,t,r){var n=new Error(t||Xm[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,eg),!r)throw n;return n},tg=function(e,t,r,n){var i=e.length,s=n?n.length:0;if(!i||t.f&&!t.l)return r||new Dm(0);var o=!r,a=o||2!=t.i,c=t.i;o&&(r=new Dm(3*i));var d=function(e){var t=r.length;if(e>t){var n=new Dm(Math.max(2*t,e));n.set(r),r=n}},l=t.f||0,u=t.p||0,p=t.b||0,h=t.l,f=t.d,m=t.m,g=t.n,v=8*i;do{if(!h){l=Qm(e,u,1);var y=Qm(e,u+1,3);if(u+=3,!y){var b=e[(L=Ym(u)+4)-4]|e[L-3]<<8,w=L+b;if(w>i){c&&eg(0);break}a&&d(p+b),r.set(e.subarray(L,w),p),t.b=p+=b,t.p=u=8*w,t.f=l;continue}if(1==y)h=Hm,f=Gm,m=9,g=5;else if(2==y){var _=Qm(e,u,31)+257,S=Qm(e,u+10,15)+4,k=_+Qm(e,u+5,31)+1;u+=14;for(var R=new Dm(k),P=new Dm(19),C=0;C<S;++C)P[Om[C]]=Qm(e,u+3*C,7);u+=3*S;var T=Km(P),E=(1<<T)-1,D=zm(P,T,1);for(C=0;C<k;){var L,M=D[Qm(e,u,E)];if(u+=15&M,(L=M>>4)<16)R[C++]=L;else{var I=0,x=0;for(16==L?(x=3+Qm(e,u,3),u+=2,I=R[C-1]):17==L?(x=3+Qm(e,u,7),u+=3):18==L&&(x=11+Qm(e,u,127),u+=7);x--;)R[C++]=I}}var O=R.subarray(0,_),A=R.subarray(_);m=Km(O),g=Km(A),h=zm(O,m,1),f=zm(A,g,1)}else eg(1);if(u>v){c&&eg(0);break}}a&&d(p+131072);for(var j=(1<<m)-1,N=(1<<g)-1,B=u;;B=u){var F=(I=h[Jm(e,u)&j])>>4;if((u+=15&I)>v){c&&eg(0);break}if(I||eg(2),F<256)r[p++]=F;else{if(256==F){B=u,h=null;break}var U=F-254;if(F>264){var q=Im[C=F-257];U=Qm(e,u,(1<<q)-1)+Nm[C],u+=q}var W=f[Jm(e,u)&N],z=W>>4;W||eg(3),u+=15&W;A=Fm[z];if(z>3){q=xm[z];A+=Jm(e,u)&(1<<q)-1,u+=q}if(u>v){c&&eg(0);break}a&&d(p+131072);var $=p+U;if(p<A){var V=s-A,H=Math.min(A,$);for(V+p<0&&eg(3);p<H;++p)r[p]=n[V+p]}for(;p<$;++p)r[p]=r[p-A]}}t.l=h,t.p=B,t.b=p,t.f=l,h&&(l=1,t.m=m,t.d=f,t.n=g)}while(!l);return p!=r.length&&o?Zm(r,0,p):r.subarray(0,p)},rg=new Dm(0);function ng(e,t){var r=function(e){31==e[0]&&139==e[1]&&8==e[2]||eg(6,"invalid gzip data");var t=e[3],r=10;4&t&&(r+=2+(e[10]|e[11]<<8));for(var n=(t>>3&1)+(t>>4&1);n>0;n-=!e[r++]);return r+(2&t)}(e);return r+8>e.length&&eg(6,"invalid gzip data"),tg(e.subarray(r,-8),{i:2},t&&t.out||new Dm(function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}(e)),t&&t.dictionary)}function ig(e,t){return tg(e.subarray(function(e,t){return(8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31)&&eg(6,"invalid zlib data"),(e[1]>>5&1)==+!t&&eg(6,"invalid zlib data: "+(32&e[1]?"need":"unexpected")+" dictionary"),2+(e[1]>>3&4)}(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function sg(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?ng(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return tg(e,{i:2},t&&t.out,t&&t.dictionary)}(e,t):ig(e,t)}var og="undefined"!=typeof TextDecoder&&new TextDecoder;try{og.decode(rg,{stream:!0}),1}catch(cg){}var ag,cg,dg;function lg(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}if(og)return og.decode(e);var i=function(e){for(var t="",r=0;;){var n=e[r++],i=(n>127)+(n>223)+(n>239);if(r+i>e.length)return{s:t,r:Zm(e,r-1)};i?3==i?(n=((15&n)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|n>>10,56320|1023&n)):t+=1&i?String.fromCharCode((31&n)<<6|63&e[r++]):String.fromCharCode((15&n)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(n)}}(e),s=i.s;return(r=i.r).length&&eg(8),s}function ug(){}function pg(){pg.init.call(this)}function hg(e){return void 0===e._maxListeners?pg.defaultMaxListeners:e._maxListeners}function fg(e,t,r){if(t)e.call(r);else for(var n=e.length,i=Sg(e,n),s=0;s<n;++s)i[s].call(r)}function mg(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=Sg(e,i),o=0;o<i;++o)s[o].call(r,n)}function gg(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=Sg(e,s),a=0;a<s;++a)o[a].call(r,n,i)}function vg(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=Sg(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}function yg(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=Sg(e,i),o=0;o<i;++o)s[o].apply(r,n)}function bg(e,t,r,n){var i,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]):(s=e._events=new ug,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=hg(e))&&i>0&&o.length>i){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[t]=r,++e._eventsCount;return e}function wg(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function _g(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Sg(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}ug.prototype=Object.create(null),pg.EventEmitter=pg,pg.usingDomains=!1,pg.prototype.domain=void 0,pg.prototype._events=void 0,pg.prototype._maxListeners=void 0,pg.defaultMaxListeners=10,pg.init=function(){this.domain=null,pg.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new ug,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},pg.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},pg.prototype.getMaxListeners=function(){return hg(this)},pg.prototype.emit=function(e){var t,r,n,i,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(n=arguments.length){case 1:fg(r,l,this);break;case 2:mg(r,l,this,arguments[1]);break;case 3:gg(r,l,this,arguments[1],arguments[2]);break;case 4:vg(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),s=1;s<n;s++)i[s-1]=arguments[s];yg(r,l,this,i)}return!0},pg.prototype.addListener=function(e,t){return bg(this,e,t,!1)},pg.prototype.on=pg.prototype.addListener,pg.prototype.prependListener=function(e,t){return bg(this,e,t,!0)},pg.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,wg(this,e,t)),this},pg.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,wg(this,e,t)),this},pg.prototype.removeListener=function(e,t){var r,n,i,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new ug:(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new ug,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}(r,i);n.removeListener&&this.emit("removeListener",e,o||t)}return this},pg.prototype.off=function(e,t){return this.removeListener(e,t)},pg.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new ug,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new ug:delete r[e]),this;if(0===arguments.length){for(var n,i=Object.keys(r),s=0;s<i.length;++s)"removeListener"!==(n=i[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new ug,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},pg.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},pg.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):_g.call(e,t)},pg.prototype.listenerCount=_g,pg.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class kg extends pg{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(ag||(ag={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(cg||(cg={})),function(e){e.OutboundNetworkQuality="outbound-network-quality",e.InboundNetworkQuality="inbound-network-quality",e.OutboundNetworkMediaLatency="outbound-network-media-latency",e.InboundNetworkMediaLatency="inbound-network-media-latency",e.NetworkMediaSyncFailure="network-media-sync-failure",e.OutboundNetworkThroughput="outbound-network-throughput",e.InboundNetworkThroughput="inbound-network-throughput",e.EncoderCPUThrottling="encoder-cpu-throttling",e.DecoderCPUThrottling="decoder-cpu-throttling",e.ServerIssue="server-issue",e.UnknownVideoDecoderIssue="unknown-video-decoder",e.LowInboundMOS="low-inbound-mean-opinion-score",e.LowOutboundMOS="low-outbound-mean-opinion-score",e.FrozenVideoTrack="frozen-video-track"}(dg||(dg={}));class Rg extends pg{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(e){super(),this.compositeStatsParser=e.compositeStatsParser,this.getStatsInterval=e.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;const e=()=>setTimeout((()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally((()=>{this.reportTimer=e()}))}),this.getStatsInterval);this.isStopped=!1,this.reportTimer=e()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){const e=Date.now(),t=await this.compositeStatsParser.parse(),r=Date.now()-e;this.emit(Rg.STATS_REPORTS_PARSED,{timeTaken:r}),t.forEach((e=>{this.emit(Rg.STATS_REPORT_READY_EVENT,e)}))}}const Pg=(()=>{const e=new Map;return t=>{const{taskId:r,delayMs:n,maxJitterMs:i,callback:s}=t,o=Math.ceil(Math.random()*(i||0)),a=e.get(r);a&&clearTimeout(a);const c=setTimeout((()=>{s(),e.delete(r)}),n+o);e.set(r,c)}})();class Cg{#e={};calculate(e){const{connection:{id:t}}=e,{mos:r,stats:n}=this.calculateOutboundScore(e)||{},{mos:i,stats:s}=this.calculateInboundScore(e)||{};return this.#e[t]=e,Pg({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:r,inbound:i,connectionId:t,statsSamples:{inboundStatsSample:s,outboundStatsSample:n}}}calculateOutboundScore(e){const t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:i}=e.connection,s=r.connection.packetsSent,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=i-s,u=o.packetsLost-o.lastPacketsLost,p=l&&u?Math.round(100*u/(l+u)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateInboundScore(e){const t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:i}=e.connection,s=r.connection.packetsReceived,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=i-s,u=o.packetsLost-o.lastPacketsLost,p=l&&u?Math.round(100*u/(l+u)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateMOS({avgJitter:e,rtt:t,packetsLoss:r}){const n=t+2*e+10;let i=n<160?93.2-n/40:93.2-n/120-10;return i-=2.5*r,1+.035*i+7e-6*i*(i-60)*(100-i)}}class Tg{#e;#t;constructor(e={}){this.#e=new Map,this.#t=e.statsCleanupTtlMs??35e3}detect(e){const t=this.performDetection(e);return this.performPrevStatsCleanup({connectionId:e.connection.id}),t}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;this.#e.has(t)&&Pg({taskId:t,delayMs:this.#t,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof r&&r()}})}setLastProcessedStats(e,t){this.#e.set(e,t)}getLastProcessedStats(e){return this.#e.get(e)}deleteLastProcessedStats(e){this.#e.delete(e)}}class Eg extends Tg{#r;constructor(e={}){super(e),this.#r=e.availableOutgoingBitrateThreshold??1e5}performDetection(e){const t=[],{availableOutgoingBitrate:r}=e.connection;if(void 0===r)return t;const n=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),i=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!n&&!i)return t;const s={availableOutgoingBitrate:r,videoStreamsTotalBitrate:i,audioStreamsTotalTargetBitrate:n};return n>r||i>0&&r<this.#r?(t.push({statsSample:s,type:cg.Network,reason:dg.OutboundNetworkThroughput}),t):t}}class Dg extends Tg{#n;constructor(e={}){super(e),this.#n=e.framesDroppedThreshold??.5}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.inbound.filter((e=>e.framesDropped>0)),r=[],n=this.getLastProcessedStats(e.connection.id)?.video.inbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesDropped===t.framesDropped)return;const i=e.framesReceived-t.framesReceived,s=e.framesDecoded-t.framesDecoded,o=e.framesDropped-t.framesDropped,a=o/i;if(0===i||0===s)return;const c={deltaFramesDropped:o,deltaFramesReceived:i,deltaFramesDecoded:s,framesDroppedPct:Math.round(100*a)};a>=this.#n&&r.push({statsSample:c,type:cg.CPU,reason:dg.DecoderCPUThrottling,ssrc:e.ssrc})})),r):r}}class Lg extends Tg{#i;constructor(e={}){super(e),this.#i=e.missedFramesThreshold??.15}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.outbound.filter((e=>e.framesEncoded>0)),r=[],n=this.getLastProcessedStats(e.connection.id)?.video.outbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesEncoded===t.framesEncoded)return;const i=e.framesEncoded-t.framesEncoded,s=e.framesSent-t.framesSent,o=1-s/i;if(0===i)return;if(i===s)return;const a={deltaFramesSent:s,deltaFramesEncoded:i,missedFramesPct:Math.round(100*o)};o>=this.#i&&r.push({statsSample:a,type:cg.Network,reason:dg.OutboundNetworkThroughput,ssrc:e.ssrc})})),r):r}}class Mg extends Tg{#s;#o;#a;#c;constructor(e={}){super(),this.#s=e.highPacketLossThresholdPct??5,this.#o=e.highJitterThreshold??200,this.#a=e.highJitterBufferDelayThresholdMs??500,this.#c=e.highRttThresholdMs??250}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=[],r=[...e.audio?.inbound,...e.video?.inbound];if(!r.length)return t;const n=this.getLastProcessedStats(e.connection.id);if(!n)return t;const i=[...n.video?.inbound,...n.audio?.inbound],{packetsReceived:s}=e.connection,o=n.connection.packetsReceived,a=r.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc)),n=r?.jitterBufferDelay||0,s=r?.jitterBufferEmittedCount||0,o=t.jitterBufferDelay-n,a=t.jitterBufferEmittedCount-s,c=o&&a?1e3*o/a:0;return{sumJitter:e.sumJitter+t.jitter,sumJitterBufferDelayMs:e.sumJitterBufferDelayMs+c,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d,sumJitterBufferDelayMs:l}=a,u=d/r.length,p=l/r.length,h=s-o,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.#s,v=u>=this.#o,y=c>=this.#c,b=p>this.#a,w=y&&!v&&!g,_=g&&v,S=v&&b,k={rtt:c,packetLossPct:m,avgJitter:u,avgJitterBufferDelay:p};return(v||g)&&t.push({statsSample:k,type:cg.Network,reason:dg.InboundNetworkQuality,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:k,type:cg.Server,reason:dg.ServerIssue,iceCandidate:e.connection.remote.id}),_&&t.push({statsSample:k,type:cg.Network,reason:dg.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),S&&t.push({statsSample:k,type:cg.Network,reason:dg.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class Ig extends Tg{#d;constructor(e={}){super(),this.#d=e.correctedSamplesThresholdPct??5}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.audio.inbound,r=[],n=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;const i=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,s=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(i===s)return;const o=e.track.totalSamplesReceived-t.track.totalSamplesReceived,a=i-s,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>this.#d&&r.push({statsSample:d,type:cg.Network,reason:dg.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class xg extends Tg{#s;#o;constructor(e={}){super(),this.#s=e.highPacketLossThresholdPct??5,this.#o=e.highJitterThreshold??200}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=[],r=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!r.length)return t;const n=this.getLastProcessedStats(e.connection.id);if(!n)return t;const i=[...n.remote?.audio.inbound||[],...n.remote?.video.inbound||[]],{packetsSent:s}=e.connection,o=n.connection.packetsSent,a=r.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d}=a,l=d/r.length,u=s-o,p=a.packetsLost-a.lastPacketsLost,h=u&&p?Math.round(100*p/(u+p)):0,f=h>this.#s,m=l>=this.#o,g=!f&&m||m||f,v={rtt:c,avgJitter:l,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:cg.Network,reason:dg.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:cg.Network,reason:dg.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class Og extends Tg{performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.outbound.filter((e=>"none"!==e.qualityLimitationReason)),r=[],n=this.getLastProcessedStats(e.connection.id)?.video.outbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;const i={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&r.push({statsSample:i,type:cg.CPU,reason:dg.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:i,type:cg.Network,reason:dg.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class Ag extends Tg{UNKNOWN_DECODER="unknown";#l={};performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#l[t],"function"==typeof r&&r()}})}processData(e){const t=[],{id:r}=e.connection,n=this.getLastProcessedStats(r)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:i,ssrc:s}=e,o=n?.find((e=>e.ssrc===s));if(o)if(i===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(r,s)){this.setLastDecoderWithIssue(r,s,this.UNKNOWN_DECODER);const n={mimeType:e.mimeType,decoderImplementation:i};t.push({ssrc:s,statsSample:n,type:cg.Stream,reason:dg.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,s,void 0)})),t}setLastDecoderWithIssue(e,t,r){const n=this.#l[e]??{};void 0===r?delete n[t]:n[t]=r,this.#l[e]=n}hadLastDecoderWithIssue(e,t){const r=this.#l[e];return(r&&r[t])===this.UNKNOWN_DECODER}}class jg extends Tg{#u=new Map;#p;#n;constructor(e={}){super(),this.#p=e.timeoutMs??1e4,this.#n=e.framesDroppedThreshold??.5}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const{connection:{id:t}}=e,r=this.getLastProcessedStats(t),n=[];if(!r)return n;const{video:{inbound:i}}=e,{video:{inbound:s}}=r,o=e=>new Map(e.map((e=>[e.track.trackIdentifier,e]))),a=o(i),c=o(s),d=new Set(this.#u.keys());return Array.from(a.entries()).forEach((([e,t])=>{d.delete(e);const r=c.get(e);if(!r)return;const i=t.framesReceived-r.framesReceived,s=t.framesDropped-r.framesDropped,o=t.framesDecoded-r.framesDecoded;if(0===i)return;if(s/i>=this.#n)return;if(o>0)return void this.removeMarkIssue(e);if(!this.markIssue(e))return;const a={framesReceived:t.framesReceived,framesDropped:t.framesDropped,framesDecoded:t.framesDecoded,deltaFramesReceived:i,deltaFramesDropped:s,deltaFramesDecoded:o};n.push({statsSample:a,type:cg.Stream,reason:dg.FrozenVideoTrack,trackIdentifier:e})})),d.forEach((e=>{this.removeMarkIssue(e)})),n}markIssue(e){const t=Date.now(),r=this.#u.get(e);return r?!(t-r<this.#p):(this.#u.set(e,t),!1)}removeMarkIssue(e){this.#u.delete(e)}}const Ng=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,Bg=(e,t,r)=>8*((e,t,r)=>{if(!t)return 0;const n=e[r],i=t[r];if(null==n||null==i)return 0;const s=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===s?0:(Number(n)-Number(i))/s*1e3})(e,t,r);class Fg{connections=[];statsParser;constructor(e){this.statsParser=e.statsParser}listConnections(){return[...this.connections]}addPeerConnection(e){this.connections.push({id:e.id??String(Date.now()+Math.random().toString(32)),pc:e.pc})}removePeerConnection(e){const t=this.connections.findIndex((({pc:t})=>t===e.pc));t>=0&&this.removeConnectionsByIndexes([t])}async parse(){const e=[],t=this.connections.map((async(t,r)=>{if(!Ng(t.pc))return this.statsParser.parse(t);e.unshift(r)}));return e.length&&this.removeConnectionsByIndexes(e),(await Promise.all(t)).filter((e=>void 0!==e))}removeConnectionsByIndexes(e){e.forEach((e=>{this.connections.splice(e,1)}))}}class Ug{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);ignoreSSRCList;logger;constructor(e){this.ignoreSSRCList=e.ignoreSSRCList??[],this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!Ng(e.pc))return this.getConnectionStats(e);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:e})}async getConnectionStats(e){const{pc:t,id:r}=e;try{const n=Date.now(),i=t.getReceivers().filter((e=>e.track?.enabled)),s=t.getSenders().filter((e=>e.track?.enabled)),o=await Promise.all(i.map((e=>e.getStats()))),a=await Promise.all(s.map((e=>e.getStats())));return{id:r,stats:this.mapReportsStats([...o,...a],e),timeTaken:Date.now()-n}}catch(e){return void this.logger.error("Failed to get stats for PC",{id:r,pc:t,error:e})}}mapReportsStats(e,t){const r={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};e.forEach((e=>{e.forEach((t=>{this.allowedReportTypes.has(t.type)&&this.updateMappedStatsWithReportItemData(t,r,e)}))}));const{id:n}=t,i=this.prevStats.get(n);return i&&this.propagateStatsWithRateValues(r,i.stats),this.prevStats.set(n,{stats:r,ts:Date.now()}),Pg({taskId:n,delayMs:35e3,callback:()=>this.prevStats.delete(n)}),r}updateMappedStatsWithReportItemData(e,t,r){const n=e.type;if("candidate-pair"===n&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,r));const i=this.getMediaType(e);if(!i)return;const s=e.ssrc;if(!s||!this.ignoreSSRCList.includes(s))if("outbound-rtp"!==n)if("inbound-rtp"!==n)"remote-outbound-rtp"!==n?"remote-inbound-rtp"===n&&(this.mapConnectionStatsIfNecessary(t,e,r),t.remote[i].inbound.push({...e})):t.remote[i].outbound.push({...e});else{const n=r.get(e.trackId)||r.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,r);const s={...e,track:{...n}};t[i].inbound.push(s)}else{const n=r.get(e.trackId)||r.get(e.mediaSourceId)||{},s={...e,track:{...n}};t[i].outbound.push(s)}}getMediaType(e){const t=e.mediaType||e.kind;if(!["audio","video"].includes(t)){const{id:t}=e;if(!t)return;return String(t).includes("Video")?"video":String(t).includes("Audio")?"audio":void 0}return t}propagateStatsWithRateValues(e,t){e.audio.inbound.forEach((e=>{const r=t.audio.inbound.find((({id:t})=>t===e.id));e.bitrate=Bg(e,r,"bytesReceived"),e.packetRate=Bg(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=Bg(e,r,"bytesSent"),e.packetRate=Bg(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=Bg(e,r,"bytesReceived"),e.packetRate=Bg(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=Bg(e,r,"bytesSent"),e.packetRate=Bg(e,r,"packetsSent")}))}mapConnectionStatsIfNecessary(e,t,r){if(e.connection.id||!t.transportId)return;const n=r.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=r.get(n.selectedCandidatePairId);e.connection=this.prepareConnectionStats(t,r)}}prepareConnectionStats(e,t){if(!e||!t)return{};const r={...e};if(r.remoteCandidateId){const e=t.get(r.remoteCandidateId);r.remote={...e}}if(r.localCandidateId){const e=t.get(r.localCandidateId);r.local={...e}}return r}}class qg{eventEmitter;#h=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;autoAddPeerConnections;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new kg,e.onIssues&&this.eventEmitter.on(ag.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(ag.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new Og,new Dg,new Lg,new Mg,new xg,new Ig,new Eg,new Ag,new jg],this.networkScoresCalculator=e.networkScoresCalculator??new Cg,this.compositeStatsParser=e.compositeStatsParser??new Fg({statsParser:new Ug({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new Rg({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.autoAddPeerConnections=e.autoAddPeerConnections??!0,this.autoAddPeerConnections&&this.wrapRTCPeerConnection(),this.statsReporter.on(Rg.STATS_REPORT_READY_EVENT,(e=>{this.detectIssues({data:e.stats}),this.calculateNetworkScores(e.stats)})),this.statsReporter.on(Rg.STATS_REPORTS_PARSED,(e=>{const t={timeTaken:e.timeTaken,ts:Date.now()};this.eventEmitter.emit(ag.StatsParsingFinished,t)}))}watchNewPeerConnections(){if(!this.autoAddPeerConnections)throw new Error("Auto add peer connections was disabled in the constructor.");this.#h?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#h=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#h?(this.logger.info("Stop watching peer connections"),this.#h=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e){this.#h||!this.autoAddPeerConnections?(this.#h||!1!==this.autoAddPeerConnections||(this.logger.info("Starting stats reporting for new peer connection"),this.#h=!0,this.statsReporter.startReporting()),this.logger.debug("Handling new peer connection",e),this.compositeStatsParser.addPeerConnection({pc:e})):this.logger.debug("Skip handling new peer connection. Detector is not running",e)}emitIssues(e){this.eventEmitter.emit(ag.Issue,e)}detectIssues({data:e}){const t=this.detectors.reduce(((t,r)=>[...t,...r.detect(e)]),[]);t.length>0&&this.emitIssues(t)}calculateNetworkScores(e){const t=this.networkScoresCalculator.calculate(e);this.eventEmitter.emit(ag.NetworkScoresUpdated,t)}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");const e=window.RTCPeerConnection,t=e=>this.handleNewPeerConnection(e);function r(r){const n=new e(r);return t(n),n}r.prototype=e.prototype,window.RTCPeerConnection=r}}class Wg{constructor(e){this.missingPeers=e.missingPeers,this.missingConsumers=e.missingConsumers,this.missingProducers=e.missingProducers,this.consumersWithInconsistentState=e.consumersWithInconsistentState,this.producersWithInconsistentState=e.producersWithInconsistentState,this.peersWithInconsistentAppData=e.peersWithInconsistentAppData}hasInconsistencyCases(){return this.missingPeers.length>0||this.missingConsumers.length>0||this.missingProducers.length>0||this.consumersWithInconsistentState.length>0||this.producersWithInconsistentState.length>0||this.peersWithInconsistentAppData.length>0}}class zg{constructor(e){this.missingPeers=[],this.missingConsumers=[],this.missingProducers=[],this.consumersWithInconsistentState=[],this.producersWithInconsistentState=[],this.peersWithInconsistentAppData=[],this.localState=e.localState,this.remoteState=e.remoteState,this.ignoreIds=e.ignoreIds}check(){this.resetPreviousCheckResults(),this.remoteState.peers.forEach((e=>{if(this.ignoreIds.includes(e.id))return;const t=this.findLocalPeerById(e.id);if(!t)return void this.missingPeers.push(e.id);t.appDataHash!==e.appDataHash&&this.peersWithInconsistentAppData.push(e.id),e.producers.forEach((e=>{if(this.ignoreIds.includes(e.id))return;const r=this.findLocalConsumerByProducerId(t,e.id);r&&(r.paused,e.paused);const n=this.findLocalProducerById(t,e.id);if(n||this.missingProducers.push(e.id),r||n||this.missingConsumers.push(e.id),!n)return;n.paused!==e.paused&&this.producersWithInconsistentState.push(e.id)}))}));return new Wg({missingPeers:this.missingPeers,missingConsumers:this.missingConsumers,missingProducers:this.missingProducers,consumersWithInconsistentState:this.consumersWithInconsistentState,producersWithInconsistentState:this.producersWithInconsistentState,peersWithInconsistentAppData:this.peersWithInconsistentAppData})}getMissingPeers(){return this.missingPeers}getMissingConsumers(){return this.missingConsumers}getMissingProducers(){return this.missingProducers}getConsumersWithInconsistentState(){return this.consumersWithInconsistentState}getProducersWithInconsistentState(){return this.producersWithInconsistentState}getPeersWithInconsistentAppData(){return this.peersWithInconsistentAppData}findLocalPeerById(e){return this.localState.peers.find((t=>t.id===e))}findLocalConsumerByProducerId(e,t){var r;return null===(r=e.consumers)||void 0===r?void 0:r.find((e=>e.producerId===t))}findLocalProducerById(e,t){return e.producers.find((e=>e.id===t))}resetPreviousCheckResults(){this.missingPeers=[],this.missingConsumers=[],this.missingProducers=[],this.consumersWithInconsistentState=[],this.producersWithInconsistentState=[],this.peersWithInconsistentAppData=[]}}var $g;!function(e){e.MissingPeer="missing-peer",e.MissingConsumers="missing-consumers",e.MissingProducer="missing-producer",e.IncorrectProducerState="incorrect-producer-state",e.IncorrectConsumerState="incorrect-consumer-state"}($g||($g={}));var Vg,Hg,Gg,Kg,Qg,Jg,Yg,Zg,Xg;class ev{constructor(e){Vg.set(this,[]),Hg.set(this,[]),Gg.set(this,[]),Kg.set(this,[]),Qg.set(this,[]),Jg.set(this,[]),Yg.set(this,!1),this.networkScores={inbound:4.3,outbound:4.3};const{engine:t,onLogMessage:r,clientEventEmitter:n,webRTCIssueEmitter:i}=e;this.engine=t,this.clientEventEmitter=n,this.webRTCIssueEmitter=i,this.logger=new $s({logLevel:t.logLevel,namespace:"ChannelStateSyncEventHandler",onLogMessage:r,sendAnalytics:e.sendAnalytics}),this.listenNetworkScoresUpdatedEvents()}handle(e){return s(this,void 0,void 0,(function*(){try{const{event:t,data:r}=yield this.parseChannelStateSyncEventPayload(e);"channel-state"!==t||o(this,Yg,"f")||this.handleChannelStateEvent(r)}catch(e){this.logger.error("handleChannelStateSyncEvent()",{error:ut(e)})}}))}handleChannelStateEvent(e){return s(this,void 0,void 0,(function*(){a(this,Yg,!0,"f");try{yield this.collectProbableInconsistencyCases(e);const t=this.getConfirmedInconsistencyResult();t&&t.hasInconsistencyCases()&&this.handleConfirmedInconsistencyResult(t)}finally{a(this,Yg,!1,"f")}}))}getLastInconsistencyCheckResult(){return o(this,Jg,"f")[o(this,Jg,"f").length-1]}handleConfirmedInconsistencyResult(e){e.missingPeers.forEach((e=>{o(this,Vg,"f").push(e),this.clientEventEmitter.safeEmit(Y,{peerId:e,type:$g.MissingPeer})})),e.missingProducers.forEach((e=>{o(this,Gg,"f").push(e),this.clientEventEmitter.safeEmit(Y,{producerId:e,type:$g.MissingProducer})})),e.producersWithInconsistentState.forEach((e=>{o(this,Qg,"f").push(e),this.clientEventEmitter.safeEmit(Y,{producerId:e,type:$g.IncorrectProducerState})})),e.missingConsumers.length>0&&(o(this,Hg,"f").push(...e.missingConsumers),this.clientEventEmitter.safeEmit(Y,{type:$g.MissingConsumers})),e.consumersWithInconsistentState.length>0&&(o(this,Kg,"f").push(...e.consumersWithInconsistentState),this.clientEventEmitter.safeEmit(Y,{type:$g.IncorrectConsumerState}))}getConfirmedInconsistencyResult(){const e=this.getLastInconsistencyCheckResult();if(!e)return;return new Wg({missingPeers:this.getConfirmedMissingPeers(e.missingPeers),missingConsumers:this.getConfirmedMissingConsumers(e.missingConsumers),missingProducers:this.getConfirmedMissingProducers(e.missingProducers),consumersWithInconsistentState:this.getConfirmedConsumersWithInconsistencState(e.consumersWithInconsistentState),producersWithInconsistentState:this.getConfirmedProducersWithInconsistencState(e.producersWithInconsistentState),peersWithInconsistentAppData:this.getConfirmedPeersWithInconsistentAppData(e.missingPeers)})}collectProbableInconsistencyCases(e){return s(this,void 0,void 0,(function*(){const t=new zg({remoteState:e,localState:this.getLocalState(),ignoreIds:this.getAllConfirmedInconsistentEntityIds()}).check();if(this.rotateLastProbableInconsistencyCheckResults(t),!t.hasInconsistencyCases())return;if(this.isBadNetworkScore())return void this.resetLastProbableInconsistencyCheckResults();(yield this.getIsConnectionActive())||this.resetLastProbableInconsistencyCheckResults()}))}resetLastProbableInconsistencyCheckResults(){a(this,Jg,[],"f")}rotateLastProbableInconsistencyCheckResults(e){4===o(this,Jg,"f").length&&o(this,Jg,"f").shift(),o(this,Jg,"f").push(e)}isReachedMaxCheckRetries(e,t,r=4){let n=0;return o(this,Jg,"f").forEach((r=>{r[e].includes(t)&&(n+=1)})),n>=r}getConfirmedMissingPeers(e){return e.filter((e=>this.isReachedMaxCheckRetries("missingPeers",e)))}getConfirmedMissingConsumers(e){return e.filter((e=>this.isReachedMaxCheckRetries("missingConsumers",e,1)))}getConfirmedMissingProducers(e){return e.filter((e=>this.isReachedMaxCheckRetries("missingProducers",e)))}getConfirmedConsumersWithInconsistencState(e){return e.filter((e=>this.isReachedMaxCheckRetries("consumersWithInconsistentState",e,1)))}getConfirmedProducersWithInconsistencState(e){return e.filter((e=>this.isReachedMaxCheckRetries("producersWithInconsistentState",e)))}getConfirmedPeersWithInconsistentAppData(e){return e.filter((e=>this.isReachedMaxCheckRetries("peersWithInconsistentAppData",e)))}parseChannelStateSyncEventPayload(e){return s(this,void 0,void 0,(function*(){const t=sg("arrayBuffer"in e?new Uint8Array(yield e.arrayBuffer()):new Uint8Array(e));return JSON.parse(lg(t))}))}getAllConfirmedInconsistentEntityIds(){return[...o(this,Vg,"f"),...o(this,Hg,"f"),...o(this,Gg,"f"),...o(this,Kg,"f"),...o(this,Qg,"f")]}getLocalState(){const{hostPeers:e}=this.engine;return{peers:e.map((e=>({id:e.id,appDataHash:Em(e.appData),producers:e.getProducers().map((e=>({id:e.id,paused:e.paused}))),consumers:e.getConsumersState()})))}}getIsConnectionActive(){var e;return s(this,void 0,void 0,(function*(){try{return this.engine.checkSocketConnectionActivity(),yield null===(e=this.engine.network.socket.connection)||void 0===e?void 0:e.timeout(1e3).emitWithAck("peer.ping",{}),!0}catch(e){return!1}}))}listenNetworkScoresUpdatedEvents(){this.webRTCIssueEmitter&&this.webRTCIssueEmitter.on(ag.NetworkScoresUpdated,(e=>{e.inbound&&(this.networkScores.inbound=e.inbound),e.outbound&&(this.networkScores.outbound=e.outbound)}))}isBadNetworkScore(){const{inbound:e,outbound:t}=this.networkScores;return e<=2.6||t<=2.6}}Vg=new WeakMap,Hg=new WeakMap,Gg=new WeakMap,Kg=new WeakMap,Qg=new WeakMap,Jg=new WeakMap,Yg=new WeakMap;class tv{constructor({engine:e,onLogMessage:t,logLevel:r,sendAnalytics:n}){Zg.set(this,void 0),Xg.set(this,void 0),a(this,Zg,e,"f"),a(this,Xg,new $s({logLevel:r,namespace:"ChannelStateSyncEventHandler",onLogMessage:t,sendAnalytics:n}),"f"),this.watchNetworkState(),this.debouncedRestoreState=ft(this.restoreState.bind(this),3e3),this.debouncedSyncPeerState=ft(this.syncPeerState.bind(this),1e3)}watchNetworkState(){o(this,Zg,"f").clientEventEmitter.on(X,(()=>s(this,void 0,void 0,(function*(){yield this.debouncedRestoreState()})))),o(this,Zg,"f").clientEventEmitter.on(Y,(({type:e})=>s(this,void 0,void 0,(function*(){[$g.IncorrectConsumerState,$g.MissingConsumers].includes(e)&&(yield this.debouncedSyncPeerState(e))}))))}syncPeerState(e){return s(this,void 0,void 0,(function*(){try{if(!o(this,Zg,"f").isSocketConnectionActive)return void o(this,Xg,"f").info("Connection inactive, skipping re-syncing local peers state",{case:"restoreLocalState",type:e});o(this,Zg,"f").eventsQueue.pause(),o(this,Xg,"f").info("Re-syncing local peers state",{case:"restoreLocalState",type:e});const{peers:t}=yield o(this,Zg,"f").network.getChannelPeers("host");this.restoreLocalPeersState(t)}catch(t){o(this,Xg,"f").info("Failed to re-sync local peers state",{case:"restoreLocalState",type:e,error:ut(t)})}finally{o(this,Zg,"f").eventsQueue.resume()}}))}restoreState(){return s(this,void 0,void 0,(function*(){try{if(!o(this,Zg,"f").isSocketConnectionActive)return void o(this,Xg,"f").info("Connection inactive, skipping restore local state",{case:"restoreLocalState"});o(this,Xg,"f").info("Restoring local state",{case:"restoreLocalState"});const e=o(this,Zg,"f").hostPeers.map((e=>e.shortData)),{peers:t}=yield o(this,Zg,"f").network.getChannelPeers("host");yield this.restoreRemoteProducersState(t),this.removeUnnecessaryPeers(e,t),this.setMissingPeers(e,t),this.restoreLocalPeersState(t)}catch(e){o(this,Xg,"f").info("Failed to restore local state",{case:"restoreLocalState",error:ut(e)})}}))}restoreRemoteProducersState(e){return s(this,void 0,void 0,(function*(){const t=o(this,Zg,"f").peers.find((e=>e.id===o(this,Zg,"f").myPeerId)),r=e.find((e=>e.id===o(this,Zg,"f").myPeerId));if(!t||!r)return;const n=o(this,Zg,"f").media.getAllTracks(),i=r.producers.filter((e=>!n.map((e=>e.producerId)).some((t=>e.id===t))));yield Promise.all(i.map((e=>s(this,void 0,void 0,(function*(){yield o(this,Zg,"f").network.closeRemoteProducer(e.id),t.producers.delete(e.id),o(this,Xg,"f").info("Unnecessary local producer closed",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})})))));const a=r.producers.filter((e=>!!n.find((t=>t.isPaused&&t.isPaused!==e.paused))));yield Promise.all(a.map((e=>s(this,void 0,void 0,(function*(){yield o(this,Zg,"f").network.pauseRemoteProducer(e.id),o(this,Xg,"f").info("Remote producer state repaired",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})})))))}))}removeUnnecessaryPeers(e,t){e.filter((e=>!t.find((t=>t.id===e.id)))).forEach((e=>{o(this,Zg,"f").removePeer(e.id),o(this,Xg,"f").info("Unnecessary peer removed",{case:"restoreLocalState",removedPeerId:e.id})}))}setMissingPeers(e,t){t.forEach((t=>{e.find((e=>e.id===t.id))||(o(this,Zg,"f").setPeer(t),o(this,Xg,"f").info("Missing peer added to storage",{case:"restoreLocalState",peerId:t.id}))}))}restoreLocalPeersState(e){const t=new Map(e.map((e=>[e.id,e])));o(this,Zg,"f").hostPeers.forEach((e=>{const r=t.get(e.id);r?(this.removeUnnecessaryProducers(e,r),this.restoreAppData(e,r),this.restoreTracksState(e,r)):o(this,Xg,"f").warn("Found new local peer, skip restoring state",{case:"restoreLocalState",newPeerId:e.id})})),o(this,Xg,"f").info("Peers state restored",{case:"restoreLocalState"})}removeUnnecessaryProducers(e,t){e.getProducers().filter((e=>!t.producers.find((t=>t.id===e.id)))).forEach((t=>{e.observer.safeEmit(ve,t),o(this,Xg,"f").info("Unnecessary producer removed",{case:"restoreLocalState",removedProducerId:t.id,removedProducerPeerId:t.peerId})}))}restoreTracksState(e,t){t.producers.forEach((t=>{const r=e.producers.get(t.id);if(!r)return e.observer.safeEmit(ge,t),void o(this,Xg,"f").info("Missing producer added to storage",{case:"restoreLocalState",producerId:t.id,producerPeerId:t.peerId});if(r.paused!==t.paused){r.paused=t.paused;const n=r.paused?oe:ae;e.observer.safeEmit(n,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused}),o(this,Xg,"f").info("Producer state fixed",{case:"restoreLocalState",producerId:t.id,producerPeerId:t.peerId})}const n=e.tracks.get(r.label);if(n&&n.consumerId&&n.isPaused!==t.paused){const{consumerId:i}=n,s=r.paused?De:Le;e.observer.safeEmit(s,i),o(this,Xg,"f").info("Consumer state fixed",{case:"restoreLocalState",consumerId:i,consumerProducerId:t.id,consumerProducerPeerId:t.peerId})}}))}restoreAppData(e,t){ht(e.appData,t.appData)||(e.observer.emit(P,t.appData),o(this,Xg,"f").info("Application data restored",{case:"restoreLocalState",peerId:e.id,appData:t.appData}))}}var rv,nv,iv,sv,ov,av,cv;Zg=new WeakMap,Xg=new WeakMap;class dv{constructor(e){rv.set(this,void 0),a(this,rv,e,"f")}create(){var e,t;const r=null!==(e=o(this,rv,"f").logger)&&void 0!==e?e:console,n=new Fg({statsParser:new Ug({ignoreSSRCList:o(this,rv,"f").ignoreSSRCList,logger:null!==(t=o(this,rv,"f").logger)&&void 0!==t?t:console})});return new qg({issueEmitter:new kg,networkScoresCalculator:new Cg,detectors:[new Og,new Dg,new Lg,new Mg,new xg,new Ig,new Eg,new Ag,new jg],statsReporter:new Rg({compositeStatsParser:n,getStatsInterval:5e3}),onIssues:this.handleIssues.bind(this,o(this,rv,"f").onIssues),onNetworkScoresUpdated:o(this,rv,"f").onNetworkScoresUpdated,ignoreSSRCList:o(this,rv,"f").ignoreSSRCList,compositeStatsParser:n,logger:r})}handleIssues(e,t){const r=t.filter((e=>e.type!==cg.Stream||e.reason!==dg.FrozenVideoTrack||this.filterNotValidFrozenVideoTrackIssues(e)));null==e||e(r)}filterNotValidFrozenVideoTrackIssues(e){const{iceCandidate:t}=e,r=t&&o(this,rv,"f").engine.getTrackByConsumerId(t);return!!r&&!r.isPaused}}rv=new WeakMap;class lv{createSystem(e){return new Kh(e)}createMedia(e){return new lh(e)}createNetwork(e){const{loadbalancer:t,logLevel:r,onLogMessage:n}=e,i=new Sm({logLevel:r,onLogMessage:n,sendAnalytics:e.sendAnalytics}),s=new km(t);return new Gh({logLevel:r,socketClient:i,loadBalancerApiClient:s,onLogMessage:n,sendAnalytics:e.sendAnalytics})}createChannelEventHandler(e){return new Qh(e)}createMediaSoupEventHandler(e){return new Jh(e)}createAudioObserverEventHandler(e){return new Pm(e)}createChannelStateSyncEventHandler(e){return new ev(e)}createChannelStateSynchronizer(e){return new tv(e)}createIssueDetector(e){return new dv(e).create()}}class uv extends AudioWorkletNode{constructor(e){super(e.context,"rnnoise",{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{module:e.noiseSuppressor.module}}),this.port.onmessage=({data:e})=>{const t=Object.assign(new Event("status"),e);this.dispatchEvent(t)}}update(e){this.port.postMessage(e)}static register(e){return s(this,void 0,void 0,(function*(){yield e.audioWorklet.addModule(`${window.location.origin}/noiseSuppressionWorklet.js`)}))}}class pv{constructor(e){nv.set(this,void 0),iv.set(this,void 0),sv.set(this,void 0),ov.set(this,void 0),av.set(this,void 0),cv.set(this,!0),a(this,nv,e.noiseSuppressor.instance.exports,"f"),a(this,iv,e.context,"f"),a(this,sv,new Float32Array(o(this,nv,"f").memory.buffer),"f"),a(this,ov,o(this,nv,"f").newState(),"f"),a(this,av,o(this,iv,"f").createScriptProcessor(),"f"),this.setOnAudioProcess()}get noiseSuppressionScriptProcessorNode(){return o(this,av,"f")}update(e){e||(a(this,cv,!1,"f"),o(this,nv,"f").deleteState(o(this,ov,"f")));const t=Object.assign(new Event("status"),{vadProb:o(this,nv,"f").getVadProb(o(this,ov,"f"))});o(this,av,"f").dispatchEvent(t)}setOnAudioProcess(){o(this,av,"f").addEventListener("audioprocess",(({inputBuffer:e,outputBuffer:t})=>{if(!o(this,cv,"f"))return;o(this,sv,"f").set(e.getChannelData(0),o(this,nv,"f").getInput(o(this,ov,"f"))/4);const r=t.getChannelData(0),n=o(this,nv,"f").pipe(o(this,ov,"f"),r.length)/4;n&&r.set(o(this,sv,"f").subarray(n,n+r.length))}))}}nv=new WeakMap,iv=new WeakMap,sv=new WeakMap,ov=new WeakMap,av=new WeakMap,cv=new WeakMap;var hv,fv,mv,gv,vv,yv,bv,wv,_v,Sv;class kv{constructor({context:e,noiseSuppressor:t}){hv.set(this,void 0),fv.set(this,void 0),mv.set(this,void 0),a(this,hv,e,"f"),a(this,fv,t,"f")}createNoiseSuppressionNode(){return s(this,void 0,void 0,(function*(){return/apple/i.test(navigator.vendor)?this.createScriptProcessorNode():this.createAudioWorkletNode()}))}stop(){var e;null===(e=o(this,mv,"f"))||void 0===e||e.update(!1)}createAudioWorkletNode(){return s(this,void 0,void 0,(function*(){return yield uv.register(o(this,hv,"f")),a(this,mv,new uv({context:o(this,hv,"f"),noiseSuppressor:o(this,fv,"f")}),"f"),o(this,mv,"f")}))}createScriptProcessorNode(){return a(this,mv,new pv({context:o(this,hv,"f"),noiseSuppressor:o(this,fv,"f")}),"f"),o(this,mv,"f").noiseSuppressionScriptProcessorNode}}hv=new WeakMap,fv=new WeakMap,mv=new WeakMap;class Rv{constructor(e){gv.set(this,void 0),vv.set(this,void 0),yv.set(this,void 0),bv.set(this,void 0),a(this,gv,e.noiseSuppressor,"f"),a(this,yv,new $s({namespace:"TrackProcessor",logLevel:e.logLevel,sendAnalytics:e.sendAnalytics}),"f")}get isProcessing(){return!!o(this,bv,"f")}processTrack(e){return s(this,void 0,void 0,(function*(){const t=(e=>{const t=window.AudioContext||window.webkitAudioContext||!1;return t?new t(e):null})();if(!t)throw new Error("AudioContext is not available");const r=new MediaStreamAudioDestinationNode(t,{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers"});yield uv.register(t);const n=t.createMediaStreamSource(new MediaStream([e])),i=new kv({context:t,noiseSuppressor:o(this,gv,"f")}),s=yield i.createNoiseSuppressionNode();s.connect(r),n.connect(s);const[c]=r.stream.getTracks();return a(this,vv,{audioContext:t,streamDestination:r,noiseSuppressionNode:s,noiseSuppressionProvider:i},"f"),a(this,bv,c,"f"),o(this,yv,"f").info("processTrack()",{track:e.id}),c}))}stopProcessing(){var e;return s(this,void 0,void 0,(function*(){if(this.isProcessing)if(o(this,vv,"f"))try{o(this,vv,"f").noiseSuppressionProvider.stop(),o(this,vv,"f").noiseSuppressionNode.disconnect(),o(this,vv,"f").streamDestination.disconnect(),yield o(this,vv,"f").audioContext.close(),null===(e=o(this,bv,"f"))||void 0===e||e.stop(),a(this,bv,void 0,"f"),o(this,yv,"f").info("stopProcessing()",{success:!0})}catch(e){o(this,yv,"f").error("stopProcessing()",{success:!1,error:e})}else o(this,yv,"f").warn("stopProcessing()",{success:!1,description:"Processing context is not available"});else o(this,yv,"f").debug("stopProcessing()",{description:"Track is not processed"})}))}}gv=new WeakMap,vv=new WeakMap,yv=new WeakMap,bv=new WeakMap;class Pv extends Lh{constructor(e){super(e),wv.set(this,void 0),_v.set(this,void 0),Sv.set(this,void 0),e.noiseSuppressor&&a(this,wv,new Rv({noiseSuppressor:e.noiseSuppressor,logLevel:e.logLevel,sendAnalytics:e.engine.sendAnalytics}),"f"),a(this,Sv,new $s({namespace:"AudioTrack",logLevel:e.logLevel,sendAnalytics:e.engine.sendAnalytics}),"f")}get isEffectsProcessing(){var e;return!!(null===(e=o(this,wv,"f"))||void 0===e?void 0:e.isProcessing)}getEncoderConfig(){return this.encoderConfig}getEncodings(){var e;return null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:Bp}getCodecOptions(){var e,t;return{opusFec:null===(e=this.getEncoderConfig().enableFec)||void 0===e||e,opusDtx:null===(t=this.getEncoderConfig().enableDtx)||void 0===t||t}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||"opus"}enableNoiseSuppression(){var e;return s(this,void 0,void 0,(function*(){if(o(this,wv,"f"))try{const t=yield null===(e=o(this,wv,"f"))||void 0===e?void 0:e.processTrack(this.mediaStreamTrack);a(this,_v,this.mediaStreamTrack,"f"),yield this.replaceTrack(t)}catch(e){throw this.logger.warn("enableNoiseSuppression()",{description:"Can not enable noise suppression",track:this.logCtx,error:e}),new Error("Can not enable noise suppression")}else this.logger.warn("enableNoiseSuppression()",{description:"Track suppressor is not defined"})}))}disableNoiseSuppression(){var e,t;return s(this,void 0,void 0,(function*(){try{if(!(null===(e=o(this,wv,"f"))||void 0===e?void 0:e.isProcessing))return void o(this,Sv,"f").debug("stopProcessing()",{description:"Track is not processed"});if(!o(this,_v,"f"))return void this.logger.warn("disableNoiseSuppression()",{description:"Original track missing"});this.isPublished&&(yield this.replaceTrack(o(this,_v,"f"))),yield null===(t=o(this,wv,"f"))||void 0===t?void 0:t.stopProcessing()}catch(e){throw this.logger.warn("disableNoiseSuppression()",{description:"Can not disable noise suppression",track:this.logCtx,error:e}),new Error("Can not disable noise suppression")}}))}publish(){return s(this,void 0,void 0,(function*(){yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),codecOptions:this.getCodecOptions()}),this.internalEventEmitter.emit(ne.trackProduced,this)}))}pause(){return s(this,void 0,void 0,(function*(){yield this.mute()}))}}wv=new WeakMap,_v=new WeakMap,Sv=new WeakMap;class Cv{createAudioTrack(e){return new Pv(e)}createVideoTrack(e){return new Mh(e)}}module.exports=class{constructor(e){var t,r;const{clientEventEmitter:n,internalEventEmitter:i,network:s,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:d,logLevel:l,disableWid:u,effectsSDKParams:p,sendAnalytics:h}=e;this._clientEventEmitter=null!=n?n:new c,this._internalEventEmitter=null!=i?i:new c;const f=new lv,m=new Cv;this.engine=new Hh({dependenciesFactory:f,clientEventEmitter:this._clientEventEmitter,internalEventEmitter:this._internalEventEmitter,media:{mediaTracksFactory:m},network:{loadbalancer:{baseURL:null===(t=null==s?void 0:s.loadbalancer)||void 0===t?void 0:t.baseURL,customNode:null===(r=null==s?void 0:s.loadbalancer)||void 0===r?void 0:r.customNode}},logLevel:l,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:d,disableWid:u,effectsSDKParams:p,sendAnalytics:h})}get observer(){return this._clientEventEmitter}get id(){return this.engine.myPeerId}get peers(){return this.engine.peers}get availableVideoDevices(){return this.engine.system.availableVideoDevices}get availableAudioDevices(){return this.engine.system.availableAudioDevices}get canUseNoiseSuppression(){return this.engine.canUseNoiseSuppression}get effectsSDKInitialized(){return this.engine.media.effectsSDKInitialized}detectDevices(e){return s(this,void 0,void 0,(function*(){return yield this.engine.system.detectDevices(e),{video:this.engine.system.availableVideoDevices,audio:this.engine.system.availableAudioDevices}}))}initEffectsSDK(){return this.engine.media.initEffectsSDK()}join(e){return this.engine.join(e)}leave(){return this.engine.release()}confirmActivity(){return this.engine.confirmActivity()}createCameraVideoTrack(e){return this.engine.createCameraVideoTrack(e)}createMicrophoneAudioTrack(e){return this.engine.createMicrophoneAudioTrack(e)}createScreenMediaTracks(e){return this.engine.createScreenMediaTracks(e)}deleteTrack(e){return this.engine.deleteTrack(e)}loadPeers(e){return this.engine.loadPeers(e)}updateAppData(e){return this.engine.updateAppData(e)}getTransportsInfo(){return s(this,void 0,void 0,(function*(){return this.engine.network.getTransportsStateInfo()}))}getNodeActiveStreamsStat(){return this.engine.getNodeActiveStreamsStat()}setPreferRelay(e){this.engine.network.setPreferRelay(e)}getPreferRelay(){return this.engine.network.getPreferRelay()}};
27
+ function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}(e,["emitter","type"]),s=null!=r?r:"N/A emitter";"error"===n&&o(this,Hp,"f").error(s,Object.assign({},i)),"warning"===n&&o(this,Hp,"f").warn(s,Object.assign({},i)),"info"===n&&o(this,Hp,"f").info(s,Object.assign({},i)),"ml_inference"===r&&(i.message.toLocaleLowerCase().includes("init lowlighter")&&(o(this,Gp,"f").lowLighter=!0),i.message.toLocaleLowerCase().includes("init colorcorrector")&&(o(this,Gp,"f").colorCorrector=!0),i.message.toLocaleLowerCase().includes("init facedetector")&&(o(this,Gp,"f").faceDetector=!0),i.message.toLocaleLowerCase().includes("init segmentation")&&(o(this,Gp,"f").segmentation=!0),this.isModelsLoaded&&(null===(t=o(this,Yp,"f"))||void 0===t||t.call(this)))}get isModelsLoaded(){return o(this,Gp,"f").colorCorrector&&o(this,Gp,"f").faceDetector&&o(this,Gp,"f").lowLighter&&o(this,Gp,"f").segmentation}get modelsLoadProgress(){return Object.values(o(this,Gp,"f")).filter(Boolean).length/Object.keys(o(this,Gp,"f")).length}get isReady(){return o(this,Jp,"f")}setOnLoadModels(e){a(this,Yp,e,"f"),this.isModelsLoaded&&o(this,Yp,"f").call(this)}onReady(){a(this,Jp,!0,"f"),o(this,Hp,"f").debug("onReady()",{description:"ESDK is ready"}),this.updateEffects(o(this,Qp,"f"))}processTrack(e){var t,r;return s(this,void 0,void 0,(function*(){if(o(this,Kp,"f")===e||"ended"===e.readyState)return(null===(t=o(this,Vp,"f").getStream())||void 0===t?void 0:t.getVideoTracks()[0])||e;this.stopProcessing();try{o(this,Vp,"f").useStream(new MediaStream([e]));const t=null===(r=o(this,Vp,"f").getStream())||void 0===r?void 0:r.getVideoTracks()[0];return t?(a(this,Kp,e,"f"),t):e}catch(t){throw o(this,Hp,"f").error("processTrack()",{error:t,track:e}),new Error("Can not process this track")}}))}stopProcessing(){try{o(this,Vp,"f").clear(),o(this,Vp,"f").stop()}catch(e){o(this,Hp,"f").error("stopProcessing()",{error:e})}finally{a(this,Kp,null,"f")}}updateEffects(e){var t,r,n,i,s,c,d,l,u,p,h,f,m,g,v,y,b,w,_,S,k;if(a(this,Qp,e,"f"),!o(this,Jp,"f"))return void o(this,Hp,"f").warn("updateEffects()",{description:"Esdk not ready"});if(!o(this,Qp,"f")||0===Object.keys(o(this,Qp,"f")).length)return void o(this,Vp,"f").stop();let R=0;if((null===(t=o(this,Qp,"f"))||void 0===t?void 0:t.blur)&&!(null===(r=o(this,Qp,"f"))||void 0===r?void 0:r.backgroundColor)?(o(this,Vp,"f").setBlur(o(this,Qp,"f").blur),R+=1):o(this,Vp,"f").clearBlur(),void 0!==(null===(n=o(this,Qp,"f"))||void 0===n?void 0:n.background)?(o(this,Vp,"f").setBackground(o(this,Qp,"f").background),R+=1):void 0!==(null===(i=o(this,Qp,"f"))||void 0===i?void 0:i.backgroundColor)?(o(this,Vp,"f").setBackgroundColor(null===(s=o(this,Qp,"f"))||void 0===s?void 0:s.backgroundColor),o(this,Vp,"f").setBackground("color"),R+=1):o(this,Vp,"f").clearBackground(),(null===(c=o(this,Qp,"f"))||void 0===c?void 0:c.beautification)?(o(this,Vp,"f").enableBeautification(),o(this,Vp,"f").setBeautificationLevel(o(this,Qp,"f").beautification),R+=1):o(this,Vp,"f").disableBeautification(),(null===(d=o(this,Qp,"f"))||void 0===d?void 0:d.lowLightEffect)?(o(this,Vp,"f").enableLowLightEffect(),o(this,Vp,"f").setLowLightEffectPower(o(this,Qp,"f").lowLightEffect),R+=1):o(this,Vp,"f").disableLowLightEffect(),(null===(l=o(this,Qp,"f"))||void 0===l?void 0:l.colorCorrector)?(o(this,Vp,"f").enableColorCorrector(),o(this,Vp,"f").setColorCorrectorPower(o(this,Qp,"f").colorCorrector),R+=1):o(this,Vp,"f").disableColorCorrector(),(null===(u=o(this,Qp,"f"))||void 0===u?void 0:u.smartZoom)?(o(this,Vp,"f").enableSmartZoom(),o(this,Vp,"f").setFaceArea(o(this,Qp,"f").smartZoom),R+=1):o(this,Vp,"f").disableSmartZoom(),(null===(p=o(this,Qp,"f"))||void 0===p?void 0:p.layout)?(o(this,Vp,"f").setLayout(o(this,Qp,"f").layout),R+=1):o(this,Vp,"f").setLayout("center"),(null===(h=o(this,Qp,"f"))||void 0===h?void 0:h.colorFilter)&&(null===(f=o(this,Qp,"f"))||void 0===f?void 0:f.colorFilter.power)&&(null===(m=o(this,Qp,"f"))||void 0===m?void 0:m.colorFilter.url)?(o(this,Vp,"f").setColorFilterConfig({lut:o(this,Qp,"f").colorFilter.url,power:o(this,Qp,"f").colorFilter.power}),o(this,Vp,"f").enableColorFilter(),R+=1):o(this,Vp,"f").disableColorFilter(),null===(g=o(this,Qp,"f"))||void 0===g?void 0:g.lowerThird){const e=o(this,Vp,"f").createComponent({component:o(this,Qp,"f").lowerThird.type,options:o(this,Qp,"f").lowerThird.options||{}});null===(b=null===(y=null===(v=o(this,Vp,"f").components)||void 0===v?void 0:v.lowerThird)||void 0===y?void 0:y.hideLowerThird)||void 0===b||b.call(y),o(this,Vp,"f").addComponent(e,"lowerThird"),o(this,Vp,"f").components.lowerThird.showLowerThird(),R+=1}else null===(S=null===(_=null===(w=o(this,Vp,"f").components)||void 0===w?void 0:w.lowerThird)||void 0===_?void 0:_.hideLowerThird)||void 0===S||S.call(_);(null===(k=o(this,Qp,"f"))||void 0===k?void 0:k.sharpness)?(o(this,Vp,"f").setSharpnessEffectConfig(o(this,Qp,"f").sharpness),R+=1):o(this,Vp,"f").disableSharpnessEffect(),R>2?o(this,Vp,"f").enableFrameSkipping():o(this,Vp,"f").disableFrameSkipping(),o(this,Vp,"f").run()}}Vp=new WeakMap,Hp=new WeakMap,Gp=new WeakMap,Kp=new WeakMap,Qp=new WeakMap,Jp=new WeakMap,Yp=new WeakMap;class lh{constructor(e){this.isDeviceLoaded=!1,this.tracks=new Map,Zp.set(this,void 0),Xp.set(this,void 0),eh.set(this,void 0),th.set(this,void 0),rh.set(this,void 0),nh.set(this,void 0),ih.set(this,null),sh.set(this,void 0),oh.set(this,!1),ah.set(this,new Map);const{logLevel:t,onLogMessage:r}=e;a(this,Xp,t,"f"),a(this,Zp,new $s({namespace:"Media",logLevel:t,onLogMessage:r,sendAnalytics:e.sendAnalytics}),"f"),a(this,eh,e.engine,"f"),a(this,th,e.internalEventEmitter,"f"),a(this,ih,e.effectsSDKParams||null,"f"),a(this,ih,e.effectsSDKParams||null,"f"),a(this,nh,e.mediaTracksFactory,"f"),a(this,rh,new Up({logLevel:t,onLogMessage:r,sendAnalytics:e.sendAnalytics}),"f")}get mediasoupDevice(){return this.device||(this.device=this.createDevice()),this.device}get isNoiseSuppressorLoaded(){return!!o(this,sh,"f")}get effectsSDKInitialized(){return o(this,oh,"f")}get effectsSDKParams(){return o(this,ih,"f")}getTrack(e){return this.tracks.get(e)}loadDevice(e){return s(this,void 0,void 0,(function*(){this.isDeviceLoaded||(yield this.mediasoupDevice.load({routerRtpCapabilities:e}),this.isDeviceLoaded=!0)}))}createNoiseSuppressor(){return s(this,void 0,void 0,(function*(){try{if(o(this,sh,"f"))return void o(this,Zp,"f").warn("createNoiseSuppressor()",{message:"Noise suppression module already created"});a(this,sh,yield class{static compileModule(e){return s(this,void 0,void 0,(function*(){if(!window.WebAssembly)throw new Error("Webassembly not supported");const t=yield fetch(`${e}/rnnoise-processor.wasm`);return WebAssembly.instantiate(yield t.arrayBuffer())}))}}.compileModule(window.location.origin),"f")}catch(e){o(this,Zp,"f").warn("createNoiseSuppressor()",{message:"Can not load wasm module",error:e})}}))}getTrackCodec(e){const{rtpCapabilities:t,rtpCapabilities:{codecs:r}}=this.mediasoupDevice;if(r)return r.find((t=>t.mimeType.toLowerCase()===`${e.kind}/${e.getPreferredCodec()}`));o(this,Zp,"f").error("getTrackCodec()",{label:e.getLabel,rtpCapabilities:t})}createTracks({constraints:e,mediaStreamTracks:t}){return t.map((t=>{const r={mediaStreamTrack:t,logLevel:o(this,Xp,"f"),engine:o(this,eh,"f"),internalEventEmitter:o(this,th,"f"),constraints:e,mediaStreamTrackManager:o(this,rh,"f")},n="audio"===t.kind?o(this,nh,"f").createAudioTrack(Object.assign(Object.assign({},r),{noiseSuppressor:o(this,sh,"f")})):o(this,nh,"f").createVideoTrack(r);return o(this,Zp,"f").debug("createTrack() track created",{trackId:n.id,kind:n.kind}),n}))}createUserMediaTracks(e){return s(this,void 0,void 0,(function*(){const t=yield o(this,rh,"f").createUserMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createDisplayMediaTracks(e){return s(this,void 0,void 0,(function*(){const t=yield o(this,rh,"f").createDisplayMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}deleteTrack(e){return s(this,void 0,void 0,(function*(){const t={trackId:e.id,label:e.getLabel(),producerId:e.producerId};try{"disableNoiseSuppression"in e&&(yield e.disableNoiseSuppression()),"disableEffects"in e&&(yield e.disableEffects())}catch(e){o(this,Zp,"f").warn("deleteTrack()",Object.assign({error:e},t))}try{this.tracks.delete(e.getLabel()),e.stopMediaStreamTrack(),yield e.closeProducer()}catch(e){o(this,Zp,"f").error("deleteTrack()",{error:e})}finally{o(this,Zp,"f").debug("deleteTrack()",t)}}))}getAllTracks(){return Array.from(this.tracks.values())}clearTracks(){return s(this,void 0,void 0,(function*(){try{this.getAllTracks().map((e=>e.stopMediaStreamTrack()))}catch(e){o(this,Zp,"f").warn("clearTracks()",{error:e})}finally{this.tracks.clear()}}))}setTrack(e){this.tracks.set(e.getLabel(),e)}initEffectsSDK(){if(o(this,oh,"f"))return Promise.resolve(!0);if(!o(this,ih,"f"))throw o(this,Zp,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Error("Effects SDK config not provided");const e=(e,t)=>s(this,void 0,void 0,(function*(){if(!window.tsvb)return o(this,Zp,"f").info("Effects SDK not loaded, skipping initialization",{case:"initEffectsSDK"}),void e(!1);o(this,Zp,"f").info("Effects SDK initializing",{case:"initEffectsSDK"});try{o(this,ah,"f").set(m.Camera,yield this.createEffectsSDKTrackProcessor(m.Camera)),o(this,ah,"f").set(m.CameraPreview,yield this.createEffectsSDKTrackProcessor(m.CameraPreview)),a(this,oh,!0,"f"),o(this,Zp,"f").info("Effects SDK initialized",{case:"initEffectsSDK"}),e(!0)}catch(e){o(this,Zp,"f").error("Failed to initilize Effects SDK",{error:e,case:"initEffectsSDK"}),t(e)}}));return new Promise(((t,r)=>{if(!window.tsvb)return o(this,Zp,"f").info("Effects SDK tsvb-web.js is not ready, waiting",{case:"initEffectsSDK"}),void window.addEventListener("load",(()=>e(t,r)));e(t,r)}))}createEffectsSDKTrackProcessor(e){return s(this,void 0,void 0,(function*(){if(e){const t=o(this,ah,"f").get(e);if(t)return t}if(!o(this,ih,"f"))throw o(this,Zp,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Error("Effects SDK config not provided");const t=new dh({logLevel:o(this,Xp,"f"),customerId:o(this,ih,"f").customerId,sendAnalytics:o(this,eh,"f").sendAnalytics});return yield t.init(),o(this,Zp,"f").info("Track effects processor initialized",{trackLabel:e}),t}))}static getVideoTrackTransformParams(e){const t=e.getSettings();return{width:t.width||Ap.width,height:t.height||Ap.height}}static getScreenVideoTrackParams(e){var t;return{videoTrackOptions:null!==(t=null==e?void 0:e.video)&&void 0!==t?t:{frameRate:{max:20},width:{max:Ap.width},height:{max:Ap.height}},encoderConfig:(null==e?void 0:e.videoEncoderConfig)||{encodings:Np}}}static getCameraVideoTrackParams(e){var t;return{videoTrackOptions:null!==(t=null==e?void 0:e.video)&&void 0!==t?t:{frameRate:{max:24},width:{max:Ap.width},height:{max:Ap.height}},encoderConfig:(null==e?void 0:e.encoderConfig)||{encodings:jp}}}createDevice(){const e=(e=>{const t=null!=e?e:null===navigator||void 0===navigator?void 0:navigator.userAgent;if(!t)return;const r=Wp.getParser(t);return r.satisfies({"yandex browser":">=23.7"})?"Chrome111":r.satisfies({"yandex browser":">=22"})?"Chrome74":void 0})();return o(this,Zp,"f").debug("Creating a media device",{handlerName:null!=e?e:"not specified"}),new Hs.Device({handlerName:e})}}Zp=new WeakMap,Xp=new WeakMap,eh=new WeakMap,th=new WeakMap,rh=new WeakMap,nh=new WeakMap,ih=new WeakMap,sh=new WeakMap,oh=new WeakMap,ah=new WeakMap,function(e){e.Connect="connect",e.Connected="connected",e.ConnectError="connect_error",e.Reconnect="reconnect",e.Reconnecting="reconnecting",e.Reconnected="reconnected",e.ReconnectAttempt="reconnect_attempt",e.NeedToJoinFirst="need_to_join_first",e.Disconnect="disconnect",e.Disconnected="disconnected",e.Error="error",e.State="state",e.BufferingStart="buffering_start",e.BufferingEnd="buffering_end"}(ch||(ch={}));const uh=new Error("request for lock canceled");var ph=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class hh{constructor(e,t=uh){if(this._maxConcurrency=e,this._cancelError=t,this._queue=[],this._waiters=[],e<=0)throw new Error("semaphore must be initialized to a positive value");this._value=e}acquire(){const e=this.isLocked(),t=new Promise(((e,t)=>this._queue.push({resolve:e,reject:t})));return e||this._dispatch(),t}runExclusive(e){return ph(this,void 0,void 0,(function*(){const[t,r]=yield this.acquire();try{return yield e(t)}finally{r()}}))}waitForUnlock(){return ph(this,void 0,void 0,(function*(){if(!this.isLocked())return Promise.resolve();return new Promise((e=>this._waiters.push({resolve:e})))}))}isLocked(){return this._value<=0}release(){if(this._maxConcurrency>1)throw new Error("this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead");if(this._currentReleaser){const e=this._currentReleaser;this._currentReleaser=void 0,e()}}cancel(){this._queue.forEach((e=>e.reject(this._cancelError))),this._queue=[]}_dispatch(){const e=this._queue.shift();if(!e)return;let t=!1;this._currentReleaser=()=>{t||(t=!0,this._value++,this._resolveWaiters(),this._dispatch())},e.resolve([this._value--,this._currentReleaser])}_resolveWaiters(){this._waiters.forEach((e=>e.resolve())),this._waiters=[]}}var fh,mh,gh,vh,yh,bh,wh,_h,Sh,kh,Rh,Ph,Ch,Th,Eh=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class Dh{constructor(e){this._semaphore=new hh(1,e)}acquire(){return Eh(this,void 0,void 0,(function*(){const[,e]=yield this._semaphore.acquire();return e}))}runExclusive(e){return this._semaphore.runExclusive((()=>e()))}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.release()}cancel(){return this._semaphore.cancel()}}class Lh{constructor(e){fh.set(this,void 0),mh.set(this,void 0),this.encoderConfig={},this.label=m.Unknown,gh.set(this,void 0),vh.set(this,void 0),yh.set(this,!1),bh.set(this,void 0),wh.set(this,void 0),_h.set(this,void 0),Sh.set(this,!0),kh.set(this,new Dh);const{mediaStreamTrack:t,logLevel:r,engine:n,internalEventEmitter:i,constraints:s,mediaStreamTrackManager:o}=e;a(this,fh,t,"f"),a(this,gh,n,"f"),a(this,vh,i,"f"),a(this,bh,s,"f"),a(this,wh,o,"f"),a(this,_h,new c,"f"),this.logger=new $s({namespace:"Track",logLevel:r,sendAnalytics:n.sendAnalytics})}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished}}get observer(){return o(this,_h,"f")}get mediaStreamTrack(){return o(this,fh,"f")}get originalTrack(){return o(this,mh,"f")}get id(){return this.mediaStreamTrack.id}get kind(){return this.mediaStreamTrack.kind}get producerId(){var e;return null===(e=this.producer)||void 0===e?void 0:e.id}get isPublished(){return!!this.producer&&!this.producer.closed}get isPaused(){var e,t;return null!==(t=null===(e=this.producer)||void 0===e?void 0:e.paused)&&void 0!==t&&t}get internalEventEmitter(){return o(this,vh,"f")}getLabel(){return this.label}setLabel(e){this.label=e}setEncoderConfig(e){this.encoderConfig=e}getEncoderConfig(){return this.encoderConfig}setProducer(e){this.producer=e}setStopTrackOnPause(e){this.isPublished||a(this,Sh,e,"f")}getProducer(){return this.producer}setOriginalTrack(){a(this,mh,this.mediaStreamTrack,"f")}closeProducer(e=!0){return s(this,void 0,void 0,(function*(){if(this.producer){try{yield o(this,gh,"f").network.closeRemoteProducer(this.producer.id)}catch(e){this.logger.warn("closeProducer()",{label:this.getLabel(),producerId:this.producerId})}this.producer.close(),this.producer=void 0,e&&this.stopMediaStreamTrack()}}))}setPriority(e){return s(this,void 0,void 0,(function*(){this.producer?(yield this.producer.setRtpEncodingParameters({priority:e}),this.logger.debug("setPriority()",{label:this.getLabel(),priority:e})):this.logger.warn("setPriority()",{priority:e,reason:"Not published yet"})}))}stopMediaStreamTrack(){this.mediaStreamTrack.stop(),this.mediaStreamTrack.dispatchEvent(new Event("ended")),this.stopOriginalTrack()}stopOriginalTrack(){o(this,mh,"f")&&(o(this,mh,"f").stop(),a(this,mh,void 0,"f"))}produce({encodings:e,codecOptions:t,preferredCodec:r,transformParams:n,keyFrameRequestDelay:i}){var a;return s(this,void 0,void 0,(function*(){if(!o(this,gh,"f").cahPublish)throw this.logger.error("produce()",{message:"Not enough access to produce"}),new Error("Not enough access to produce");if(this.producer)throw new Error("Track already produced");try{yield o(this,gh,"f").network.socket.request(B);const{rtpCapabilities:{codecs:s}}=o(this,gh,"f").media.mediasoupDevice,c=null==s?void 0:s.find((e=>e.mimeType.toLowerCase()===`${this.kind}/${r}`)),d=0,l=this.prepareProducerEncodings({codec:c,encodings:null!=e?e:[],maxSpatialLayer:(null!=e?e:[]).length-1}),u={trackTransformParams:n,peerId:String(o(this,gh,"f").myPeerId),label:this.getLabel(),maxSpatialLayer:d,encodings:l,codecOptions:t,preferredCodec:r,codec:c,keyFrameRequestDelay:i},p=yield null===(a=o(this,gh,"f").network.sendTransport)||void 0===a?void 0:a.produce({track:this.mediaStreamTrack,encodings:l,codecOptions:t,codec:c,stopTracks:!1,disableTrackOnPause:!0,zeroRtpOnPause:!0,appData:u});if(!p)return;const h=p.rtpSender,f=()=>/Safari/i.test(navigator.userAgent);if(e&&h&&f()){const t=h.getParameters();e.forEach((({maxBitrate:e,scaleResolutionDownBy:r},n)=>{t.encodings[n]&&(t.encodings[n].maxBitrate=e,t.encodings[n].scaleResolutionDownBy=r)})),yield h.setParameters(t)}this.setProducer(p),"video"===this.kind&&(e&&h&&c&&$p(c.mimeType)?yield h.setParameters(Object.assign(Object.assign({},h.getParameters()),{encodings:this.prepareProducerEncodings({encodings:e,codec:c,maxSpatialLayer:d})})):yield p.setMaxSpatialLayer(d),yield o(this,gh,"f").network.socket.request(Re,{producerId:p.id,maxSpatialLayer:d})),"audio"===this.kind&&(yield this.setPriority("high")),this.logger.debug("produce()",{track:this.logCtx,encodings:e,codecOptions:t})}catch(e){throw this.logger.error("produce()",{error:e,track:this.logCtx}),new Error("Publish track failed")}}))}publish(){return s(this,void 0,void 0,(function*(){yield this.produce({}),this.internalEventEmitter.emit(ne.trackProduced,this)}))}unpublish(){return s(this,void 0,void 0,(function*(){try{this.stopMediaStreamTrack(),this.internalEventEmitter.emit(ne.trackUnproduced,this),this.producer&&(yield this.closeProducer()),a(this,yh,!0,"f"),this.logger.debug("unpublish()",{track:this.logCtx})}catch(e){this.logger.error("unpublish()",{error:e})}}))}pauseRemoteProducer(e){return s(this,void 0,void 0,(function*(){return o(this,gh,"f").network.socket.request(ye,{producerId:e})}))}resumeRemoteProducer(e){return s(this,void 0,void 0,(function*(){return o(this,gh,"f").network.socket.request(be,{producerId:e})}))}mute(e){return s(this,void 0,void 0,(function*(){yield o(this,kh,"f").waitForUnlock();const t=yield o(this,kh,"f").acquire();if(this.producer)try{if(this.producer.pause(),this.logger.debug("pause()",{track:this.logCtx}),o(this,Sh,"f"))return null==e||e(),o(this,fh,"f").stop(),this.stopOriginalTrack(),this.internalEventEmitter.emit(ne.trackClosed,this),void(yield this.pauseRemoteProducer(this.producer.id));yield this.pauseRemoteProducer(this.producer.id),this.internalEventEmitter.emit(ne.trackPaused,this)}catch(e){throw this.logger.error("pause()",{error:e,track:this.logCtx}),yield o(this,gh,"f").media.deleteTrack(this),this.internalEventEmitter.emit(ne.trackFailed,this),new Error("Can`t pause track, removing")}finally{t()}else this.logger.warn("pause()",{message:"Track is not published",track:this.logCtx})}))}resume(){return s(this,void 0,void 0,(function*(){yield o(this,kh,"f").waitForUnlock();const e=yield o(this,kh,"f").acquire();if(this.producer)try{if(this.logger.debug("resume()",{track:this.logCtx}),o(this,Sh,"f"))return yield this.reopenMediaStreamTrack(),yield this.resumeProducer(),void this.internalEventEmitter.emit(ne.trackReopened,this);yield this.resumeProducer(),this.internalEventEmitter.emit(ne.trackResumed,this)}catch(e){throw this.logger.error("resume()",{error:e,track:this.logCtx}),new Error("Can`t resume track")}finally{e()}else this.logger.warn("resume()",{message:"Track is not published",track:this.logCtx})}))}getInfo(){return s(this,void 0,void 0,(function*(){const{width:e,height:t,frameRate:r,aspectRatio:n}=o(this,fh,"f").getSettings();return{trackId:o(this,fh,"f").id,readyState:o(this,fh,"f").readyState,kind:this.kind,label:this.label,width:e,height:t,frameRate:r,aspectRatio:n,paused:this.isPaused,trackOutboundStats:yield this.getStats()}}))}getStats(){var e,t,r,n,i;return s(this,void 0,void 0,(function*(){try{return{producerId:null===(e=this.producer)||void 0===e?void 0:e.id,codec:null===(t=this.producer)||void 0===t?void 0:t.rtpParameters.codecs.find((e=>hp(e))),dtlsState:null===(i=null===(n=null===(r=this.producer)||void 0===r?void 0:r.rtpSender)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.state,rtcStats:yield this.getOutboundRTPStreamStats()}}catch(e){return void this.logger.debug("getStats()",{error:e})}}))}replaceTrack(e){var t;return s(this,void 0,void 0,(function*(){try{a(this,fh,e,"f"),this.internalEventEmitter.emit(ne.trackReopened,this),this.observer.safeEmit("track-changed",{track:e}),yield null===(t=this.producer)||void 0===t?void 0:t.replaceTrack({track:e})}catch(e){this.logger.warn("replaceTrack()",{error:e})}}))}resumeProducer(){return s(this,void 0,void 0,(function*(){this.producer?(yield this.resumeRemoteProducer(this.producer.id),this.producer.resume()):this.logger.debug("resumeProducer()",{message:"Track not produced yet",track:this.logCtx})}))}reopenMediaStreamTrack(){var e;return s(this,void 0,void 0,(function*(){const t=yield o(this,wh,"f").createMediaStreamTrack({label:this.label,constraints:o(this,bh,"f")});a(this,fh,t,"f"),yield null===(e=this.producer)||void 0===e?void 0:e.replaceTrack({track:t})}))}prepareProducerEncodings(e){const{encodings:t,codec:r,maxSpatialLayer:n}=e;return t&&t.length>1&&r&&$p(r.mimeType)?[t[n]||t[0]]:t}getOutboundRTPStreamStats(){return new Promise(((e,t)=>{const r=(n=0)=>s(this,void 0,void 0,(function*(){if(!this.producer)throw new Error("Producer is missed");try{const i=yield this.producer.getStats(),s=Array.from(i.values()).find((e=>"outbound-rtp"===e.type));if(!s&&n<5)return void setTimeout((()=>r(n+1)),150);n>=5&&!s&&t(new Error("OutboundRTPStreamStat not exist")),e(s)}catch(e){t(new Error("Can not get RTCStatsReport")),this.logger.debug("getOutboundRTPStreamStats()",{error:e})}}));r()}))}}fh=new WeakMap,mh=new WeakMap,gh=new WeakMap,vh=new WeakMap,yh=new WeakMap,bh=new WeakMap,wh=new WeakMap,_h=new WeakMap,Sh=new WeakMap,kh=new WeakMap;class Mh extends Lh{constructor(e){super(e),this.transformParams={},Rh.set(this,void 0),Ph.set(this,void 0),Ch.set(this,!1),Th.set(this,(()=>{})),a(this,Ph,e,"f")}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished,isEffectsProcessing:this.isEffectsProcessing}}get isEffectsProcessing(){return Boolean(o(this,Rh,"f"))}getEncoderConfig(){return this.encoderConfig}getCodecOptions(){return{videoGoogleStartBitrate:this.getEncoderConfig().videoGoogleStartBitrate||1e3}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||(this.getLabel()===m.ScreenVideo?"vp8":"h264")}getEncodings(){return this.getEncoderConfig().encodings||jp}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return s(this,void 0,void 0,(function*(){const t=this.getProducer();t?(yield t.setMaxSpatialLayer(e),this.logger.debug("setMaxSpatialLayer()",{label:this.getLabel(),spatialLayer:e})):this.logger.warn("setMaxSpatialLayer()",{message:"Not produced yet"})}))}getMaxSpatialLayer(){const e=this.getProducer();if(e)return e.maxSpatialLayer;this.logger.warn("getMaxSpatialLayer()",{message:"Not produced yet"})}enableEffects(){return s(this,void 0,void 0,(function*(){if(!o(this,Ch,"f")){a(this,Ch,!0,"f");try{if(o(this,Rh,"f"))return this.logger.debug("enableEffects()",{description:"Track is already processed"}),void a(this,Ch,!1,"f");if("ended"===this.mediaStreamTrack.readyState)return void this.logger.warn("Track already ended",{case:"enableEffects"});const{media:e}=o(this,Ph,"f").engine;if(!e.effectsSDKInitialized)return void this.logger.warn("Effects SDK not initialized",{case:"enableEffects"});const t=Date.now();a(this,Rh,yield e.createEffectsSDKTrackProcessor(this.getLabel()),"f"),this.setOriginalTrack();const r=yield o(this,Rh,"f").processTrack(this.mediaStreamTrack),n=Date.now();this.logger.info("enableEffects() time",{time:(n-t)/1e3}),yield this.replaceTrack(r),this.logger.info("enableEffects()",{track:this.logCtx})}catch(e){this.logger.warn("enableEffects()",{track:this.logCtx,error:e}),this.disableEffects(),o(this,Th,"f").call(this,e)}finally{a(this,Ch,!1,"f")}}}))}disableEffects(){var e;return s(this,void 0,void 0,(function*(){try{if(!o(this,Rh,"f"))return void this.logger.debug("disableEffects()",{description:"Track is not processed"});this.originalTrack?yield this.replaceTrack(this.originalTrack):this.logger.warn("disableEffects()",{description:"Original track missing"}),null===(e=o(this,Rh,"f"))||void 0===e||e.stopProcessing(),a(this,Rh,void 0,"f"),this.logger.info("disableEffects()",{track:this.logCtx})}catch(e){this.logger.warn("disableEffects()",{track:this.logCtx,error:e})}}))}publish(e={}){var t;return s(this,void 0,void 0,(function*(){yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),transformParams:this.transformParams,codecOptions:this.getCodecOptions(),keyFrameRequestDelay:null!==(t=e.keyFrameRequestDelay)&&void 0!==t?t:0}),this.internalEventEmitter.emit(ne.trackProduced,this)}))}adjustEncodingPresetToCurrentMaxSpatialLayer(e){return s(this,void 0,void 0,(function*(){if(!$p(this.getPreferredCodec()))return;const{rtpSender:t}=this.getProducer()||{};if(!t)return void this.logger.warn("No rtpSender found in producer to change encodings",{maxSpatialLayer:e,trackId:this.id,producerId:this.producerId});const{encodings:r=[]}=this.getEncoderConfig(),n=r[e];if(!n)return void this.logger.warn("Skipping RTPSender params update. No target encoding found",{initialEncodings:r});this.logger.debug("Adjusting encoding parameters to max spatial layer",{targetEncoding:n,maxSpatialLayer:e});const i=t.getParameters();yield t.setParameters(Object.assign(Object.assign({},i),{encodings:[n]}))}))}applyEffects(e){var t;return s(this,void 0,void 0,(function*(){try{!this.isEffectsProcessing&&Object.keys(e).length>0&&(yield this.enableEffects()),null===(t=o(this,Rh,"f"))||void 0===t||t.updateEffects(e)}catch(e){o(this,Th,"f").call(this,e)}}))}resetEffects(){var e;return s(this,void 0,void 0,(function*(){null===(e=o(this,Rh,"f"))||void 0===e||e.updateEffects({})}))}setOnLoadModels(e){var t;null===(t=o(this,Rh,"f"))||void 0===t||t.setOnLoadModels(e)}get modelsLoadProgress(){var e;return(null===(e=o(this,Rh,"f"))||void 0===e?void 0:e.modelsLoadProgress)||0}pause(){return s(this,void 0,void 0,(function*(){yield this.mute((()=>{var e;o(this,Rh,"f")&&(null===(e=o(this,Rh,"f"))||void 0===e||e.stopProcessing(),a(this,Rh,void 0,"f"))}))}))}setOnEffectError(e){a(this,Th,e,"f")}}Rh=new WeakMap,Ph=new WeakMap,Ch=new WeakMap,Th=new WeakMap;const Ih=new class{sleepMs(e){return s(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}},xh=(e,t={})=>s(void 0,void 0,void 0,(function*(){var r;const n=t.maxRetries||2,i=t.minBackoffDelayMs||50;let s,o=0;for(;o<n;){o+=1;try{return yield e()}catch(e){if(s=e,t.logger&&t.logger.info("Action retry failed",{currentAttempt:o,actionName:t.actionName,error:e}),t.abortOnError&&t.abortOnError(e))throw s;if(o<n){const e=Math.pow(2,o-1)*i;yield Ih.sleepMs(Math.min(e,null!==(r=t.maxBackoffDelayMs)&&void 0!==r?r:e))}}}throw s}));class Oh extends b{constructor(e,t){super(e,null!=t?t:"need_join_first")}}var Ah,jh,Nh,Bh,Fh,Uh,qh,Wh,zh,$h;class Vh{constructor(){Ah.set(this,[]),jh.set(this,new Map),Nh.set(this,new Set),Bh.set(this,!1)}subscribeToSocket(e){o(this,Nh,"f").has(e)||(e.onAny(((e,...t)=>{this.push(e,t)})),o(this,Nh,"f").add(e))}subscribeToDataChannel(e){e.on("message",((...e)=>{this.push("message",e)}))}on(e,t){var r;o(this,jh,"f").has(e)?null===(r=o(this,jh,"f").get(e))||void 0===r||r.push(t):o(this,jh,"f").set(e,[t])}removeListener(e){o(this,jh,"f").delete(e)}removeAllListeners(e,t){t&&o(this,Nh,"f").has(t)&&(t.offAny(),o(this,Nh,"f").delete(t)),e.forEach((e=>{o(this,jh,"f").delete(e)}))}push(e,t){o(this,Ah,"f").push({event:e,args:t}),this.process()}process(){if(!o(this,Bh,"f"))for(;o(this,Ah,"f").length>0;){const e=o(this,Ah,"f").shift();this.emit(e.event,e.args)}}emit(e,t){(o(this,jh,"f").get(e)||[]).forEach((e=>{e(...t)}))}pause(){a(this,Bh,!0,"f")}size(){return o(this,Ah,"f").length}resume(){a(this,Bh,!1,"f"),this.process()}}Ah=new WeakMap,jh=new WeakMap,Nh=new WeakMap,Bh=new WeakMap;class Hh{constructor(e){var t,r;this.initialized=!1,Fh.set(this,!1),this.isChannelJoining=!1,this.rejoinRequested=!1,this.isReleasing=!1,Uh.set(this,!1),qh.set(this,new Map),Wh.set(this,void 0);const{clientEventEmitter:n,internalEventEmitter:i,network:c,media:d,dependenciesFactory:l,logLevel:u,effectsSDKParams:p}=e;this.logLevel=u||mt,a(this,Wh,null===(t=e.sendAnalytics)||void 0===t||t,"f"),this.system=l.createSystem({logLevel:this.logLevel,clientEventEmitter:n,onLogMessage:e.onLogMessage,sendAnalytics:o(this,Wh,"f")}),this.media=l.createMedia({logLevel:this.logLevel,engine:this,internalEventEmitter:i,mediaTracksFactory:d.mediaTracksFactory,onLogMessage:e.onLogMessage,effectsSDKParams:p,sendAnalytics:o(this,Wh,"f")}),this.network=l.createNetwork({logLevel:this.logLevel,loadbalancer:c.loadbalancer,onLogMessage:e.onLogMessage,sendAnalytics:o(this,Wh,"f")}),this.logger=new $s({logLevel:this.logLevel,namespace:"Engine",onLogMessage:e.onLogMessage,sendAnalytics:o(this,Wh,"f")}),this.peersRepository=new Map,this.clientEventEmitter=n,this.internalEventEmitter=i,this.eventsQueue=new Vh,this.channelEventsHandler=l.createChannelEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.mediaSoupEventsHandler=l.createMediaSoupEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.channelAudioObserverEventHandler=l.createAudioObserverEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.channelStateSynchronizer=l.createChannelStateSynchronizer({engine:this,logLevel:this.logLevel,onLogMessage:e.onLogMessage,sendAnalytics:o(this,Wh,"f")}),this.webRtcIssueDetector=e.disableWid?void 0:l.createIssueDetector({engine:this,onIssues:e.onIssues,onNetworkScoresUpdated:e.onNetworkScoresUpdated,ignoreSSRCList:[1234],logger:new $s({logLevel:this.logLevel,namespace:"WID",sendAnalytics:o(this,Wh,"f")})}),this.channelStateSyncEventHandler=l.createChannelStateSyncEventHandler({engine:this,clientEventEmitter:n,webRTCIssueEmitter:null===(r=this.webRtcIssueDetector)||void 0===r?void 0:r.eventEmitter,onLogMessage:e.onLogMessage,sendAnalytics:o(this,Wh,"f")}),this.handleChannelAudioObserverEvent=e=>{this.channelAudioObserverEventHandler.handle(e)},this.handleDataChannelEvent=e=>{this.channelEventsHandler.handleDataChannelEvent(e)},this.handleChannelStateSyncEvent=e=>s(this,void 0,void 0,(function*(){yield this.channelStateSyncEventHandler.handle(e)})),this.watchNetworkState(),this.watchDocumentUnload()}get sendAnalytics(){return o(this,Wh,"f")}get isChannelJoined(){return o(this,Fh,"f")}initialize(){var e,t,r;return s(this,void 0,void 0,(function*(){try{const{rtpCapabilities:n}=yield this.network.socket.request("router.getRtpCapabilities");yield this.media.createNoiseSuppressor(),yield this.media.loadDevice(n),this.logger.info("Supported capabilities",{codecs:zp(this.media.mediasoupDevice)}),null===(e=this.webRtcIssueDetector)||void 0===e||e.watchNewPeerConnections(),yield Promise.all([this.network.createSendTransport(this.media.mediasoupDevice),this.network.createRecvTransport(this.media.mediasoupDevice)]),this.initialized=!0,this.logger.debug("initialize()",{sendTransportId:null===(t=this.network.sendTransport)||void 0===t?void 0:t.id,recvTransportId:null===(r=this.network.receiveTransport)||void 0===r?void 0:r.id})}catch(e){this.logger.error("initialize()",{error:e});const t=e instanceof v&&"device not supported"===e.message,r=e instanceof Error&&"RTCPeerConnection is not defined"===e.message;if(t||r)throw new w("Device not supported",w.UNSUPPORTED_DEVICE_CODE);throw new Error("Error initialize engine")}}))}release(){var e,t,r,n,i,o,c;return s(this,void 0,void 0,(function*(){if(!this.isReleasing){this.isReleasing=!0;try{this.initialized=!1,a(this,Fh,!1,"f"),this.app=void 0,this.channel=void 0,this.network.peerId=void 0,null===(e=this.webRtcIssueDetector)||void 0===e||e.stopWatchingNewPeerConnections(),this.peersRepository.forEach((e=>e.reset())),this.peersRepository.clear(),yield this.network.closeSendTransport(),yield this.network.closeReceiveTransport(),yield this.media.clearTracks(),null===(t=this.audioObserver)||void 0===t||t.removeListener("message",this.handleChannelAudioObserverEvent),null===(r=this.audioObserver)||void 0===r||r.close(),null===(n=this.generalDataConsumer)||void 0===n||n.removeListener("message",this.handleDataChannelEvent),this.eventsQueue.removeListener("message"),null===(i=this.generalDataConsumer)||void 0===i||i.close(),null===(o=this.channelStateSyncDataConsumer)||void 0===o||o.removeListener("message",this.handleChannelStateSyncEvent),null===(c=this.channelStateSyncDataConsumer)||void 0===c||c.close(),this.channelEventsHandler.reset(),this.mediaSoupEventsHandler.reset(),this.removeClientEventEmitterListeners(),yield this.network.reset(),this.network.socket.disconnect(),zs.clear(),this.logger.debug("release()",{socketId:this.myPeerId})}catch(e){throw this.logger.error("release()",{error:e}),new Error("Error release engine")}finally{this.isReleasing=!1}}}))}removeClientEventEmitterListeners(){Array.from(Object.values(ne)).forEach((e=>this.internalEventEmitter.removeAllListeners(e)))}get activeSpeaker(){return this.activeSpeakerPeer}get peers(){return Array.from(this.peersRepository.values())}get hostPeers(){return this.peers.filter((e=>"host"===e.role))}get audiencePeers(){return this.peers.filter((e=>"audience"===e.role))}get myPeerId(){return this.network.peerId}get isSocketConnectionActive(){try{return this.checkSocketConnectionActivity(),!0}catch(e){return!1}}getPeerById(e){return this.peersRepository.get(e)}checkSocketConnectionActivity(){var e;if(!this.channel||this.isChannelJoining)throw new Error("Connect to the channel first");if(!(null===(e=this.network.socket.connection)||void 0===e?void 0:e.active))throw new Error("Socket is inactive");if(!this.network.socket.connection.connected)throw new Error("Socket disconnected")}confirmActivity(){return s(this,void 0,void 0,(function*(){this.checkSocketConnectionActivity(),yield this.network.socket.request(C)}))}join(e){return s(this,void 0,void 0,(function*(){try{this.logger.debug("join()",{params:e}),this.isChannelJoining=!0,this.watchClientEvents(),yield this.connectToSocketServerWithRetry(e),yield this.performJoin({appData:e.appData})}catch(e){throw this.logger.error("join()",{error:e}),e}finally{this.isChannelJoining=!1,this.rejoinRequested=!1}}))}loadPeers(e){return s(this,void 0,void 0,(function*(){const{peers:t}=yield this.network.getChannelPeers(e);t.filter((e=>!this.peersRepository.has(e.id))).forEach((e=>this.setPeer(e)))}))}setPeer(e){const t=this.peersRepository.get(e.id);if(t)return t;const r=new Op(Object.assign(Object.assign({},e),{engine:this}));return this.peersRepository.set(r.id,r),this.clientEventEmitter.safeEmit(U,r),r}removePeer(e){const t=this.peersRepository.get(e);t&&(t.tracks.forEach((e=>e.close())),t.reset(),this.peersRepository.delete(e),this.clientEventEmitter.safeEmit(q,e))}registerTrack(e){const t=e.consumerId;if(t)return o(this,qh,"f").set(t,e),()=>{o(this,qh,"f").delete(t)}}getTrackByConsumerId(e){return o(this,qh,"f").get(e)}updateAppData(e){return s(this,void 0,void 0,(function*(){const{myPeer:t}=this;if(!t)throw new Error("Need join to channel first");try{Mp(e),yield this.network.updatePeerAppData({peerId:t.id,appData:e})}catch(e){throw this.logger.error("updateAppData()",{error:e}),new Error("Can not update peer appData")}}))}createCameraVideoTrack(e){return s(this,void 0,void 0,(function*(){const t=lh.getCameraVideoTrackParams(e);try{const[r]=yield this.media.createUserMediaTracks({audio:!1,video:t.videoTrackOptions});return r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof Mh&&(r.setLabel((null==e?void 0:e.isPreview)?m.CameraPreview:m.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(lh.getVideoTrackTransformParams(r.mediaStreamTrack))),this.media.setTrack(r),this.logger.debug("createCameraVideoTrack()",{trackParams:t}),r}catch(e){throw this.logger.error("createCameraVideoTrack()",{error:e,trackParams:t}),new Error(`Can not create camera track: ${e.message}`)}}))}createMicrophoneAudioTrack(e){return s(this,void 0,void 0,(function*(){try{const[t]=yield this.media.createUserMediaTracks({video:!1,audio:null==e?void 0:e.audio});if(t.setLabel((null==e?void 0:e.isPreview)?m.MicrophonePreview:m.Microphone),t.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),(null==e?void 0:e.encoderConfig)&&t.setEncoderConfig(e.encoderConfig),"audio"===t.kind&&(null==e?void 0:e.noiseSuppression))try{yield t.enableNoiseSuppression()}catch(e){this.logger.warn("Failed to start noise suppression, featured original track",{label:t.getLabel()})}return this.media.setTrack(t),this.logger.debug("createMicrophoneAudioTrack()",{options:e}),t}catch(t){throw this.logger.error("createMicrophoneAudioTrack()",{error:t,options:e}),new Error(`Can not create microphone track: ${t.message}`)}}))}createScreenMediaTracks(e){return s(this,void 0,void 0,(function*(){const t=lh.getScreenVideoTrackParams(e);try{const r=yield this.media.createDisplayMediaTracks({audio:null==e?void 0:e.audio,video:null==e?void 0:e.video});return r.forEach((r=>{if(r.mediaStreamTrack.addEventListener("ended",(()=>{r.unpublish()}),{once:!0}),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof Mh){r.setLabel(m.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=lh.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),this.media.setTrack(r),void this.logger.debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,label:r.logCtx})}r.setLabel(m.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(r),this.logger.debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig})})),r}catch(e){throw this.logger.error("createScreenMediaTrack()",{error:e,trackParams:t}),new Error(`Can not create screen media tracks: ${e.message}`)}}))}deleteTrack(e){return this.media.deleteTrack(e)}get channelId(){return this.channel}get appId(){return this.app}get canUseNoiseSuppression(){return this.media.isNoiseSuppressorLoaded}setActiveSpeakerPeer(e){this.activeSpeaker!==e&&(this.activeSpeakerPeer=e,this.clientEventEmitter.safeEmit(J,{peer:e}))}getNodeActiveStreamsStat(){var e;const t=this.network.socket.getServerUrl(),r=this.hostPeers.filter((e=>{var t;return e.id!==(null===(t=this.myPeer)||void 0===t?void 0:t.id)})).reduce(((e,t)=>e+t.getActiveTracksCount()),0);return{node:t,inboundActiveStreams:r,outboundActiveStreams:(null===(e=this.myPeer)||void 0===e?void 0:e.getActivePublishersCount())||0}}connectToSocketServerWithRetry(e){return s(this,void 0,void 0,(function*(){return xh((()=>s(this,void 0,void 0,(function*(){return this.connectToSocketServer(e)}))),{maxRetries:15,minBackoffDelayMs:150,maxBackoffDelayMs:5e3,actionName:"connectToSocketServer",logger:new $s({namespace:"RetrySocketConnect",logLevel:this.logLevel,sendAnalytics:o(this,Wh,"f")}),abortOnError:e=>{var t;return"unauthorized"===(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.errorCode)}})}))}connectToSocketServer(e){return s(this,void 0,void 0,(function*(){const{webSocketUrl:t}=yield this.getAvailableNode({channelId:e.channelId,role:e.role});this.network.socket.connect(t,e.token);try{yield this.waitForSocketConnection()}catch(r){throw this.logger.error("Failed to connect to socket server",{error:r,role:e.role,channelId:e.channelId,webSocketUrl:t}),this.network.socket.disconnect(),r}}))}getAvailableNode(e){return s(this,void 0,void 0,(function*(){try{return{webSocketUrl:(yield this.network.loadBalancerClient.getNode(e)).webSocketUrl}}catch(e){throw this.logger.error("getAvailableNode()",{error:"No available nodes"}),e}}))}waitForSocketConnection(){return new Promise(((e,t)=>{const r=n=>s(this,void 0,void 0,(function*(){const{error:i,state:s}=n,o=()=>this.network.socket.observer.removeListener(ch.State,r),a=[ch.Disconnected,ch.Reconnecting].includes(s);return i?(o(),void t(i)):this.isChannelJoining&&a?(o(),void t(new Error(`Not expected socket state for new connection: ${s}`))):void(this.isChannelJoining&&[ch.Connected,ch.Reconnected].includes(s)&&(o(),e()))}));this.network.socket.observer.on(ch.State,r)}))}performJoin(e){return s(this,void 0,void 0,(function*(){try{const{appId:t,channelId:r,peerId:n}=yield this.sendJoinChannelRequestWithRetry(e);this.network.peerId=n,this.app=t,this.channel=r,yield this.initialize(),this.channelEventsHandler.subscribeToEvents(),this.mediaSoupEventsHandler.subscribeToEvents(),a(this,Fh,!0,"f"),this.logger.debug("Successfully joined channel",{channelId:r}),yield Promise.all([this.createAudioObserver(),this.createGeneralDataConsumer(),this.createChannelStateSyncDataConsumer()]),zs.setPeerId(n),zs.setChannelId(r),zs.setAppId(t)}catch(e){throw this.logger.error("performJoin()",{error:e}),e}}))}sendJoinChannelRequestWithRetry(e){return s(this,void 0,void 0,(function*(){return xh((()=>s(this,void 0,void 0,(function*(){return this.sendJoinChannelRequest(e)}))),{maxRetries:3,minBackoffDelayMs:300,actionName:"sendJoinChannelRequest",logger:new $s({namespace:"RetryJoin",logLevel:this.logLevel,sendAnalytics:o(this,Wh,"f")})})}))}sendJoinChannelRequest(e){return s(this,void 0,void 0,(function*(){return this.network.socket.request(S,e)}))}get cahPublish(){var e;return"host"===(null===(e=this.peers.find((e=>e.isMe)))||void 0===e?void 0:e.role)}get myPeer(){return this.peers.find((e=>e.isMe))}watchClientEvents(){this.internalEventEmitter.on(ne.trackProduced,(e=>s(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(ne.trackUnproduced,(e=>s(this,void 0,void 0,(function*(){var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close(),yield this.media.deleteTrack(e)})))),this.internalEventEmitter.on(ne.trackPaused,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.pause()})),this.internalEventEmitter.on(ne.trackResumed,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.resume()})),this.internalEventEmitter.on(ne.trackClosed,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close()})),this.internalEventEmitter.on(ne.trackReopened,(e=>s(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(ne.trackFailed,(e=>s(this,void 0,void 0,(function*(){this.clientEventEmitter.safeEmit(Q,{label:e.getLabel()})}))))}createSelfPeerTrack(e){var t;return s(this,void 0,void 0,(function*(){const r=this.peersRepository.get(this.myPeerId);if(!r)return;yield null===(t=r.tracks.get(e.getLabel()))||void 0===t?void 0:t.close();const n=new Lp({mediaStreamTrack:e.mediaStreamTrack,label:e.getLabel(),engine:this,muted:!1,paused:e.isPaused,peerEventEmitter:r.observer});r.tracks.set(n.label,n)}))}createAudioObserver(){var e;return s(this,void 0,void 0,(function*(){if(!o(this,Fh,"f"))throw new Oh("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getAudioObserverProducer(),r=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId});r.on("message",this.handleChannelAudioObserverEvent),this.audioObserver=r,this.logger.debug("Successfully create audio observer",t)}catch(e){this.logger.error("Failed to create audio observer",t)}}))}createGeneralDataConsumer(){var e;return s(this,void 0,void 0,(function*(){if(!o(this,Fh,"f"))throw new Oh("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getGeneralDataProducer();this.generalDataConsumer=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId,ordered:!0}),this.eventsQueue.subscribeToDataChannel(this.generalDataConsumer),this.eventsQueue.on("message",this.handleDataChannelEvent),this.logger.debug("Successfully created general data consumer",Object.assign(Object.assign({},t),{producerId:e}))}catch(e){this.logger.error("Failed to create general data consumer",Object.assign(Object.assign({},t),{error:e}))}}))}createChannelStateSyncDataConsumer(){var e;return s(this,void 0,void 0,(function*(){if(!o(this,Fh,"f"))throw new Oh("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getChannelStateSyncDataProducer();this.channelStateSyncDataConsumer=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId}),this.channelStateSyncDataConsumer.on("message",this.handleChannelStateSyncEvent),this.logger.debug("Successfully created ChannelStateSyncDataConsumer",t)}catch(e){this.logger.error("Failed to create ChannelStateSyncDataConsumer",Object.assign(Object.assign({},t),{error:e}))}}))}triggerRejoinEventIfAppropriate(e){this.rejoinRequested&&!this.isChannelJoining||(this.logger.debug("Triggering channel rejoin required event",{reason:e}),this.rejoinRequested=!0,this.clientEventEmitter.emit(V))}watchNetworkState(){this.network.observer.on(qe,(e=>s(this,void 0,void 0,(function*(){var t;if(this.isReleasing)return;const{code:r,error:n,state:i}=e,s="unauthorized"===(null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.errorCode)&&this.isChannelJoined,c=r===ch.NeedToJoinFirst&&this.isChannelJoined;if(s&&this.clientEventEmitter.safeEmit(te),"server.disconnect"!==r||o(this,Uh,"f")){if(c||s){const e=s?"unauthorized error":"invalid channel state";this.triggerRejoinEventIfAppropriate(e)}i===ch.Disconnected&&this.isChannelJoined&&!o(this,Uh,"f")&&this.logger.info("connection lost",{channel:"socket"}),i===ch.Reconnected&&this.isChannelJoined&&this.logger.info("connection restored",{channel:"socket"}),i===ch.BufferingStart&&(a(this,Uh,!0,"f"),this.clientEventEmitter.safeEmit(Z)),[ch.BufferingEnd,ch.Reconnected].includes(i)&&this.network.isNetworkActive&&(a(this,Uh,!1,"f"),this.clientEventEmitter.safeEmit(X))}else this.clientEventEmitter.safeEmit(ee)})))),this.network.observer.on(We,(({state:e,direction:t})=>s(this,void 0,void 0,(function*(){if(!this.isReleasing&&(["disconnected","failed"].includes(e)&&this.isChannelJoined&&!o(this,Uh,"f")&&(a(this,Uh,!0,"f"),this.logger.info("connection lost",{channel:"webrtc-transport",direction:t}),this.clientEventEmitter.safeEmit(Z)),"reconnected"===e&&this.isChannelJoined&&this.logger.info("connection restored",{channel:"webrtc-transport",direction:t}),"reconnected"===e&&this.isChannelJoined&&o(this,Uh,"f"))){if(![this.network.receiveTransport,this.network.sendTransport].every((e=>"connected"===(null==e?void 0:e.connectionState)||"new"===(null==e?void 0:e.connectionState))))return;a(this,Uh,!1,"f"),this.clientEventEmitter.safeEmit(X)}}))))}watchDocumentUnload(){try{window.addEventListener("unload",(()=>{var e,t;null===(e=this.network.sendTransport)||void 0===e||e.close(),null===(t=this.network.receiveTransport)||void 0===t||t.close()}))}catch(e){this.logger.error("Failed to add watchDocumentUnload listener",{channelId:this.channelId})}}}Fh=new WeakMap,Uh=new WeakMap,qh=new WeakMap,Wh=new WeakMap;class Gh{constructor(e){var t;this.preferRelay=!1,zh.set(this,{send:void 0,recv:void 0}),$h.set(this,void 0);const{socketClient:r,loadBalancerApiClient:n,onLogMessage:i}=e;this.socket=r,this.loadBalancerClient=n,a(this,$h,null!==(t=e.eventEmitter)&&void 0!==t?t:new c,"f"),this.logger=new $s({namespace:"Network",logLevel:e.logLevel,onLogMessage:i,sendAnalytics:e.sendAnalytics}),this.socket.observer.on(ch.State,(e=>{o(this,$h,"f").safeEmit(qe,e)}))}get isNetworkActive(){var e,t,r,n,i;return!!(null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&["connected","new"].includes(null!==(r=null===(t=this.receiveTransport)||void 0===t?void 0:t.connectionState)&&void 0!==r?r:"")&&["connected","new"].includes(null!==(i=null===(n=this.sendTransport)||void 0===n?void 0:n.connectionState)&&void 0!==i?i:"")}get observer(){return o(this,$h,"f")}removeEventListeners(){const{sendTransport:e,receiveTransport:t}=this;if(e){["connect","produce","connectionstatechange"].forEach((t=>e.removeAllListeners(t)))}if(t){["connect","produce","connectionstatechange"].forEach((e=>t.removeAllListeners(e)))}}reset(){return s(this,void 0,void 0,(function*(){this.stopRestartIceAtempts(),this.removeEventListeners()}))}closeRemoteProducer(e){return s(this,void 0,void 0,(function*(){yield this.socket.request(ve,{peerId:this.peerId,producerId:e})}))}closeSendTransport(){var e;return s(this,void 0,void 0,(function*(){this.sendTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&(yield this.closeTransport(this.sendTransport)),this.sendTransport.close(),this.sendTransport=void 0):this.logger.warn("closeSendTransport()",{message:"No available send transport"})}))}closeReceiveTransport(){var e;return s(this,void 0,void 0,(function*(){this.receiveTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&(yield this.closeTransport(this.receiveTransport)),this.receiveTransport.close(),this.receiveTransport=void 0):this.logger.warn("closeReceiveTransport()",{message:"No available receive transport"})}))}closeTransport(e){return s(this,void 0,void 0,(function*(){try{e.close(),this.logger.debug("closeTransport()",{transportId:e.id,direction:e.direction})}catch(t){this.logger.error("closeTransport()",{error:t,transportId:e.id,direction:e.direction})}}))}createSendTransport(e){return s(this,void 0,void 0,(function*(){if(this.sendTransport)return void this.logger.warn("createSendTransport()",{message:"Send transport already exists"});const t=yield this.socket.request(Ae,{sctpCapabilities:e.sctpCapabilities,localDirection:"send"}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));this.logger.debug("createSendTransport()",{transportId:r.id,direction:r.direction}),this.sendTransport=r,this.subscribeCommonTransportEvents(r)}))}createRecvTransport(e){return s(this,void 0,void 0,(function*(){if(this.receiveTransport)return void this.logger.warn("createReceiveTransport()",{message:"Receive transport already exists"});const t=yield this.socket.request(Ae,{localDirection:"receive"}),r=e.createRecvTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));this.logger.debug("createReceiveTransport()",{transportId:r.id,direction:r.direction}),this.receiveTransport=r,this.subscribeCommonTransportEvents(r)}))}getIceParameters(e){return s(this,void 0,void 0,(function*(){const t=yield this.socket.request(Fe,{transportId:e.id}),{error:r}=t;if(r)throw new Error(r);const{iceParameters:n}=t;return this.logger.debug("getIceParameters()",{iceParameters:n}),n}))}restartIce(e){return s(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),this.logger.info("restartIce completed",{iceParameters:t})}catch(e){this.logger.error("restartIce error",{error:e})}}))}createConsumer({producerId:e,rtpCapabilities:t,appId:r,channelId:n,producerPeerId:i}){return s(this,void 0,void 0,(function*(){const s=this.receiveTransport;if(!s)throw this.logger.error("createConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");this.logger.debug("createConsumer()",{producerId:e});const o=yield this.socket.request(Ce,{producerId:e,transportId:s.id,rtpCapabilities:t,appData:{peerId:this.peerId,appId:r,channelId:n},producerPeerId:i}),a=yield s.consume(o),{producerPaused:c}=o;return this.logger.debug("Consumer created",{consumerId:a.id,label:a.appData.label,isProducerPaused:c}),{consumer:a,isProducerPaused:c}}))}createDataConsumer({producerId:e,appId:t,channelId:r,ordered:n}){return s(this,void 0,void 0,(function*(){const i=this.receiveTransport;if(!i)throw this.logger.error("createDataConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");this.logger.debug("createDataConsumer()",{producerId:e});const s=yield this.socket.request(Te,{ordered:n,dataProducerId:e,transportId:i.id,appData:{peerId:this.peerId,producerId:e,appId:t,channelId:r}}),o=yield i.consumeData(s);return this.logger.debug("Data consumer created",{consumerId:o.id}),o}))}closeRemoteConsumer(e){return s(this,void 0,void 0,(function*(){return this.socket.request(Ee,{peerId:this.peerId,consumerId:e})}))}resumeRemoteConsumer(e){return s(this,void 0,void 0,(function*(){return this.socket.request(Le,{consumerId:e})}))}pauseRemoteProducer(e){return s(this,void 0,void 0,(function*(){return this.socket.request(ye,{producerId:e})}))}pauseRemoteConsumer(e){return s(this,void 0,void 0,(function*(){return this.socket.request(De,{consumerId:e})}))}updatePeerAppData({peerId:e,appData:t}){return s(this,void 0,void 0,(function*(){return this.socket.request(P,{peerId:e,appData:t})}))}getAudioObserverProducer(){return s(this,void 0,void 0,(function*(){return this.socket.request(L)}))}getGeneralDataProducer(){return s(this,void 0,void 0,(function*(){return this.socket.request(M)}))}getChannelStateSyncDataProducer(){return s(this,void 0,void 0,(function*(){return this.socket.request(I)}))}getTransportsStateInfo(){return s(this,void 0,void 0,(function*(){const[e,t]=yield Promise.all([this.getParsedTransportStats(this.receiveTransport),this.getParsedTransportStats(this.sendTransport)]);return{receive:e,send:t}}))}setPreferRelay(e){this.preferRelay=e}getPreferRelay(){return this.preferRelay}getChannelPeers(e){return s(this,void 0,void 0,(function*(){return this.socket.request(k,{role:e})}))}getParsedTransportStats(e){return s(this,void 0,void 0,(function*(){if(e)try{const t=Array.from((yield e.getStats()).values()),r=t.find((e=>"local-candidate"===e.type)),n=t.find((e=>"remote-candidate"===e.type)),i=t.find((e=>"transport"===e.type));return{dtlsState:null==i?void 0:i.dtlsState,iceState:null==i?void 0:i.iceState,dtlsRole:null==i?void 0:i.dtlsRole,iceRole:null==i?void 0:i.iceRole,selectedCandidatePairChanges:null==i?void 0:i.selectedCandidatePairChanges,tlsVersion:null==i?void 0:i.tlsVersion,localCandidateState:{ip:null==r?void 0:r.ip,address:null==r?void 0:r.address,port:null==r?void 0:r.port,protocol:null==r?void 0:r.protocol,candidateType:null==r?void 0:r.candidateType},remoteCandidateState:{ip:null==n?void 0:n.ip,address:null==n?void 0:n.address,port:null==n?void 0:n.port,protocol:null==n?void 0:n.protocol,candidateType:null==n?void 0:n.candidateType}}}catch(e){return void this.logger.warn("getParsedTransportStats()",{error:e})}else this.logger.debug("getParsedTransportStats()",{message:"Transport is missing"})}))}logTransportDetails(e){var t,r;return s(this,void 0,void 0,(function*(){let n;try{n=yield e.getStats()}catch(t){return void this.logger.error("Failed to log detailed WebRTC transport stats",{error:ut(t),transportId:e.id,reason:"failed to parse getStats"})}try{const i=[...n],[,s]=null!==(t=i.find((([,e])=>"transport"===(null==e?void 0:e.type))))&&void 0!==t?t:[],[,o]=null!==(r=i.find((([,e])=>"candidate-pair"===e.type&&"succeeded"===e.state&&e.nominated)))&&void 0!==r?r:[],a=n.get(String((null==o?void 0:o.localCandidateId)||"-")),c=n.get(String((null==o?void 0:o.remoteCandidateId)||"-")),d={hasNominatedPair:!!o,transportId:e.id,iceRole:null==s?void 0:s.iceRole,iceState:null==s?void 0:s.iceState,dtlsRole:null==s?void 0:s.dtlsRole,dtlsState:null==s?void 0:s.dtlsState,local:{address:null==a?void 0:a.address,candidateType:null==a?void 0:a.candidateType,foundation:null==a?void 0:a.foundation,networkType:null==a?void 0:a.networkType,isRemote:null==a?void 0:a.isRemote,port:null==a?void 0:a.port,protocol:null==a?void 0:a.protocol,relatedAddress:null==a?void 0:a.relatedAddress,relatedPort:null==a?void 0:a.relatedPort,transportId:null==a?void 0:a.transportId,relayProtocol:null==a?void 0:a.relayProtocol,url:null==a?void 0:a.url},remote:{address:null==c?void 0:c.address,candidateType:null==c?void 0:c.candidateType,foundation:null==c?void 0:c.foundation,isRemote:null==c?void 0:c.isRemote,port:null==c?void 0:c.port,protocol:null==c?void 0:c.protocol,transportId:null==c?void 0:c.transportId}};(null==o?void 0:o.totalRoundTripTime)&&(null==o?void 0:o.responsesReceived)&&(d.pairRoundTripTime=Math.round(o.totalRoundTripTime/o.responsesReceived*1e3)),this.logger.info("Detailed WebRTC transport stats",d)}catch(t){this.logger.error("Failed to log detailed WebRTC transport stats",{error:ut(t),transportId:e.id,reason:"-"})}}))}stopRestartIceAtempts(){clearInterval(o(this,zh,"f").send),clearInterval(o(this,zh,"f").recv)}subscribeCommonTransportEvents(e){e.on("connect",(({dtlsParameters:t},r,n)=>s(this,void 0,void 0,(function*(){try{yield this.socket.request(je,{transportId:e.id,dtlsParameters:t}),r(),this.logger.debug(`${e.direction}Transport.connect()`,{transportId:e.id,dtlsRole:t.role}),setTimeout((()=>this.logTransportDetails(e)),1500)}catch(t){this.logger.error(`${e.direction}Transport.on('connect')`,{error:t}),n(t)}})))),e.on("produce",((t,r,n)=>s(this,void 0,void 0,(function*(){try{const{id:n}=yield this.socket.request(Ne,{transportId:e.id,kind:t.kind,rtpParameters:t.rtpParameters,appData:t.appData});r({id:n}),this.logger.debug(`${e.direction}Transport.produce()`,{producerId:n,transportId:e.id,kind:t.kind})}catch(r){this.logger.error(`${e.direction}Transport.produce()`,{error:r,transportId:e.id,kind:t.kind}),n(r)}})))),e.on("connectionstatechange",(t=>{if(this.logger.info(`${e.direction}Transport.state`,{state:t}),["closed","connected"].includes(t))return o(this,$h,"f").safeEmit(We,{state:t,direction:e.direction}),o(this,zh,"f")[e.direction]&&(this.logger.debug("Stop receiveTransport.restartIce() retries",{recvTransportId:e.id}),clearInterval(o(this,zh,"f")[e.direction]),o(this,zh,"f")[e.direction]=void 0,"connected"===t&&o(this,$h,"f").safeEmit(We,{state:"reconnected",direction:e.direction})),void("connected"===t&&setTimeout((()=>this.logTransportDetails(e)),1500));if(o(this,$h,"f").safeEmit(We,{state:t,direction:e.direction}),["disconnected","failed"].includes(t)){if(o(this,zh,"f")[e.direction])return;"failed"===t&&(this.logger.debug(`${e.direction}Transport.restartIce()`,{recvTransportId:e.id}),this.restartIce(e)),o(this,zh,"f")[e.direction]=setInterval((()=>{this.restartIce(e),this.logger.debug(`${e.direction}Transport.restartIce() attempt`,{recvTransportId:e.id})}),5e3)}})),e.on("icegatheringstatechange",(t=>{this.logger.info("icegatheringstatechange",{state:t,transportId:e.id,transportDirection:e.direction})}))}}zh=new WeakMap,$h=new WeakMap;class Kh{constructor(e){this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[];const{clientEventEmitter:t,logLevel:r,onLogMessage:n}=e;this.clientEventEmitter=t,this.logger=new $s({namespace:"System",logLevel:r,onLogMessage:n,sendAnalytics:e.sendAnalytics}),this.deviceChangeHandler=this.deviceChangeHandler.bind(this),this.listenDevices()}setIsEnableVideoDevicesLock(e){this.isEnableVideoDevicesLock=e}setIsEnableAudioDevicesLock(e){this.isEnableAudioDevicesLock=e}setAvailableVideoDevices(e){this.availableVideoDevices=e}setAvailableAudioDevices(e){this.availableAudioDevices=e}requestMediaDevicesAccess(e={video:!0,audio:!0}){return s(this,void 0,void 0,(function*(){try{return(yield navigator.mediaDevices.getUserMedia(e)).getTracks()}catch(t){if(this.logger.error("getUserMedia()",{error:t,constraints:e}),"NotAllowedError"===t.name)throw new Error(g.NotAllowedError);if("NotReadableError"===t.name)throw new Error(g.DeviceIsBusy);if("NotFoundError"===t.name)throw new Error(g.NotFoundError);throw new Error(g.RequestDevicesUnknownError)}}))}hasAvailableMediaDevicesList(){return s(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices();if(0===e.length)return!0;return e.every((e=>e.deviceId&&e.label))}))}refreshAvailableMediaDevicesList(){return s(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices(),t=[],r=[];e.forEach((e=>{""!==e.deviceId&&("videoinput"===e.kind&&t.push(e),"audioinput"===e.kind&&r.push(e))})),this.setAvailableVideoDevices(t),this.setAvailableAudioDevices(r);const n=({label:e,kind:t})=>({label:e,kind:t});return this.logger.debug("Devices list updated",{videoDevices:t.map(n),audioDevices:r.map(n)}),e}))}detectDevices(e){return s(this,void 0,void 0,(function*(){if(this.isDevicesDetected&&!e)return;(yield this.hasAvailableMediaDevicesList())||(yield this.tryToAccessDevices()),this.isDevicesDetected=!0;const t=yield this.refreshAvailableMediaDevicesList(),r=t.some((e=>"audioinput"===e.kind)),n=t.some((e=>"videoinput"===e.kind));if(!r&&!n)throw new Error(g.NoDevices)}))}deviceChangeHandler(){return s(this,void 0,void 0,(function*(){this.isDevicesDetected&&(yield this.refreshAvailableMediaDevicesList(),this.clientEventEmitter.safeEmit(H,{audio:this.availableAudioDevices,video:this.availableVideoDevices}))}))}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}assertHasAccessToMediaDevices(e={video:!0,audio:!0}){return s(this,void 0,void 0,(function*(){(yield this.requestMediaDevicesAccess(e)).forEach((e=>e.stop()))}))}tryToAccessDevices(){return s(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess()).forEach((e=>e.stop()))}catch(t){if(e=t.message,![g.NotFoundError,g.NotAllowedError,g.DeviceIsBusy].includes(e))throw t;t.message!==g.DeviceIsBusy&&(yield this.assertHasAccessToMediaDevices({audio:!0}),yield this.assertHasAccessToMediaDevices({video:!0}))}var e}))}}class Qh{constructor(e){const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new $s({logLevel:t.logLevel,namespace:"ChannelEvents",onLogMessage:r,sendAnalytics:t.sendAnalytics})}handleDataChannelEvent(e){try{const{event:t,data:r}=JSON.parse(e);this.doHandleDataChannelEvent(t,r)}catch(t){this.logger.error("Failed to handle data channel event",{error:t,payload:e})}}doHandleDataChannelEvent(e,t){e===P&&this.handlePeerAppDataUpdate(t)}subscribeToEvents(){const{connection:e}=this.engine.network.socket;if(!e)throw this.logger.error("subscribeToEvents()",{error:"Socket connection not initialized"}),new Error("Socket connection not initialized");this.engine.eventsQueue.subscribeToSocket(e),this.engine.eventsQueue.on(_,(e=>{this.engine.clientEventEmitter.safeEmit(F,e),this.logger.debug("New channel event",{event:e})})),this.engine.eventsQueue.on(S,(e=>{const t=this.engine.setPeer(e);this.logger.debug("Peer joined to the channel",{peer:Ip(t)})})),this.engine.eventsQueue.on(R,(e=>{this.engine.removePeer(e),this.logger.debug("Peer left the channel",{peerId:e})})),this.engine.eventsQueue.on(E,(e=>{this.engine.clientEventEmitter.safeEmit(W,e),this.logger.info("Notify the channel that activity confirmation is required",e)})),this.engine.eventsQueue.on(D,(e=>{this.engine.clientEventEmitter.safeEmit($,e),this.logger.info("Notify the channel that it has disconnected due to the activity confirmation expiring",e)})),this.engine.eventsQueue.on(T,(e=>{this.engine.clientEventEmitter.safeEmit(z,e),this.logger.info("Notify the channel that the activity has been acquired.",e)})),this.engine.eventsQueue.on(x,(e=>{const{producePermissions:t,groups:r,changedProducePermissions:n}=e;this.engine.peers.filter((e=>e.groups.some((e=>r.includes(e))))).forEach((e=>{const r=Array.from(new Set([...e.producePermissions,...n])).filter((e=>!n.includes(e)||t.includes(e)));e.handleProducePermissionsChange(r)})),this.logger.info("Peers changed produce permissions",{groups:r,producePermissions:t})})),this.engine.eventsQueue.on(A,(e=>{const{peerId:t,producePermissions:r}=e,n=this.engine.peersRepository.get(t);n&&n.handleProducePermissionsChange(r)})),this.engine.eventsQueue.on(O,(e=>{const{producePermissions:t,groups:r}=e;this.engine.peers.filter((e=>e.groups.some((e=>r.includes(e))))).forEach((e=>{const r=e.producePermissions.filter((e=>!t.includes(e)));e.handleProducePermissionsChange(r)})),this.logger.info("Peers deleted produce permissions",{groups:r,producePermissions:t})}))}removeEventListeners(){if(!this.engine.eventsQueue)return;const e=[_,S,R,E,D,T,P,x],{connection:t}=this.engine.network.socket;this.engine.eventsQueue.removeAllListeners(e,t)}handlePeerAppDataUpdate({peerId:e,appData:t}){const r=this.engine.peers.find((({id:t})=>t===e));r&&r.observer.emit(P,t)}reset(){this.removeEventListeners()}}class Jh{constructor(e){this.queue=new Dp;const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new $s({logLevel:t.logLevel,namespace:"MediasoupEvents",onLogMessage:r,sendAnalytics:t.sendAnalytics})}subscribeToEvents(){const{connection:e}=this.engine.network.socket;if(!e)throw this.logger.error("subscribeToEvents()",{error:"Socket connection not initialized"}),new Error("Socket connection not initialized");this.engine.eventsQueue.subscribeToSocket(e),this.engine.eventsQueue.on(ve,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&t.observer.safeEmit(ve,e)})),this.engine.eventsQueue.on(ge,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&t.observer.safeEmit(ge,e)})),this.engine.eventsQueue.on(Ee,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&r.observer.safeEmit(Ee,e)})),this.engine.eventsQueue.on(Le,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(Le,e)})),this.engine.eventsQueue.on(De,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(De,e)})),this.engine.eventsQueue.on(Ie,(({peerId:e,spatialLayer:t,temporalLayer:r,consumerId:n})=>{const i=this.engine.peers.find((t=>t.id===e));i&&!i.isMe&&i.observer.safeEmit(Ie,{consumerId:n,spatialLayer:t,temporalLayer:r})})),this.engine.eventsQueue.on(Me,(e=>{const{consumerPeerId:t}=e,r=this.engine.peers.find((e=>e.id===t));if(!r||r.isMe)return;r.observer.safeEmit(Me,e);const n=this.engine.peers.find((e=>e.isMe));n&&n.observer.safeEmit(Me,e)})),this.engine.eventsQueue.on(ke,(e=>{const t=this.engine.peers.find((e=>e.isMe));t&&t.observer.safeEmit(ke,e)})),this.engine.eventsQueue.on(Pe,(({producerId:e,spatialLayer:t})=>s(this,void 0,void 0,(function*(){yield this.queue.push((()=>s(this,void 0,void 0,(function*(){yield this.handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t})}))),Pe)})))),this.engine.eventsQueue.on(Re,(({peerId:e,producerId:t,spatialLayer:r})=>s(this,void 0,void 0,(function*(){const n=this.engine.peers.find((t=>t.id===e));n&&!n.isMe&&n.observer.safeEmit(Re,{peerId:e,producerId:t,spatialLayer:r})})))),this.engine.eventsQueue.on(Be,(({reason:e,transportId:t,direction:r,timeout:n})=>s(this,void 0,void 0,(function*(){const i=[this.engine.network.receiveTransport,this.engine.network.sendTransport].find((e=>(null==e?void 0:e.id)===t));i&&"connected"!==i.connectionState&&(this.logger.warn(Be,{reason:e,transportId:t,direction:r,timeout:n}),this.engine.clientEventEmitter.emit(G,{direction:r,reason:e}))})))),this.engine.eventsQueue.on(we,(({peerId:e,producerId:t})=>{const r=this.engine.peers.find((t=>t.id===e)),n=null==r?void 0:r.producers.get(t);r&&n&&(n.paused=!0,r.observer.safeEmit(oe,{producerId:n.id,kind:n.kind,label:n.label,paused:n.paused}))})),this.engine.eventsQueue.on(_e,(({peerId:e,producerId:t})=>{const r=this.engine.peers.find((t=>t.id===e)),n=null==r?void 0:r.producers.get(t);r&&n&&(n.paused=!1,r.observer.safeEmit(ae,{producerId:n.id,kind:n.kind,label:n.label,paused:n.paused}))})),this.engine.eventsQueue.on(Se,(({label:e})=>s(this,void 0,void 0,(function*(){const t=this.engine.media.getTrack(e);t&&(t.stopMediaStreamTrack(),this.engine.internalEventEmitter.safeEmit(ne.trackClosed,t),this.engine.clientEventEmitter.emit(K,{label:e}),yield this.engine.media.deleteTrack(t))}))))}removeEventListeners(){if(!this.engine.eventsQueue)return;const e=[ve,ge,Ee,Le,De,Ie,Me,ke,Pe,Re,Be,we,_e,Se],{connection:t}=this.engine.network.socket;this.engine.eventsQueue.removeAllListeners(e,t)}reset(){this.removeEventListeners()}handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t}){return s(this,void 0,void 0,(function*(){const r=this.engine.media.getAllTracks().find((t=>{var r;return(null===(r=t.getProducer())||void 0===r?void 0:r.id)===e}));if(!r)return void this.logger.warn("producerRequestMaxSpatialLayer()",{message:"Producer not found"});if(!(r instanceof Mh))return void this.logger.warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const n=t||0,i=r.getMaxSpatialLayer();i!==n?(r.getEncodings().length>1&&(yield r.setMaxSpatialLayer(n)),yield this.engine.network.socket.request(Re,{producerId:e,maxSpatialLayer:n}),yield r.adjustEncodingPresetToCurrentMaxSpatialLayer(n)):this.logger.debug("producerRequestMaxSpatialLayer()",{message:"Skip set max spatial layer",requestedSpatialLayer:n,currentMaxSpatialLayer:i})}))}}const Yh=Object.create(null);Yh.open="0",Yh.close="1",Yh.ping="2",Yh.pong="3",Yh.message="4",Yh.upgrade="5",Yh.noop="6";const Zh=Object.create(null);Object.keys(Yh).forEach((e=>{Zh[Yh[e]]=e}));const Xh={type:"error",data:"parser error"},ef="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),tf="function"==typeof ArrayBuffer,rf=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,nf=({type:e,data:t},r,n)=>ef&&t instanceof Blob?r?n(t):sf(t,n):tf&&(t instanceof ArrayBuffer||rf(t))?r?n(t):sf(new Blob([t]),n):n(Yh[e]+(t||"")),sf=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function of(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let af;const cf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",df="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<cf.length;e++)df[cf.charCodeAt(e)]=e;const lf="function"==typeof ArrayBuffer,uf=(e,t)=>{if("string"!=typeof e)return{type:"message",data:hf(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:pf(e.substring(1),t)};return Zh[r]?e.length>1?{type:Zh[r],data:e.substring(1)}:{type:Zh[r]}:Xh},pf=(e,t)=>{if(lf){const r=(e=>{let t,r,n,i,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=df[e.charCodeAt(t)],n=df[e.charCodeAt(t+1)],i=df[e.charCodeAt(t+2)],s=df[e.charCodeAt(t+3)],l[c++]=r<<2|n>>4,l[c++]=(15&n)<<4|i>>2,l[c++]=(3&i)<<6|63&s;return d})(e);return hf(r,t)}return{base64:!0,data:e}},hf=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,ff=String.fromCharCode(30);function mf(){return new TransformStream({transform(e,t){!function(e,t){ef&&e.data instanceof Blob?e.data.arrayBuffer().then(of).then(t):tf&&(e.data instanceof ArrayBuffer||rf(e.data))?t(of(e.data)):nf(e,!1,(e=>{af||(af=new TextEncoder),t(af.encode(e))}))}(e,(r=>{const n=r.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(r)}))}})}let gf;function vf(e){return e.reduce(((e,t)=>e+t.length),0)}function yf(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function bf(e){if(e)return function(e){for(var t in bf.prototype)e[t]=bf.prototype[t];return e}(e)}bf.prototype.on=bf.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},bf.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},bf.prototype.off=bf.prototype.removeListener=bf.prototype.removeAllListeners=bf.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},bf.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},bf.prototype.emitReserved=bf.prototype.emit,bf.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},bf.prototype.hasListeners=function(e){return!!this.listeners(e).length};const wf="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function _f(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Sf=wf.setTimeout,kf=wf.clearTimeout;function Rf(e,t){t.useNativeTimers?(e.setTimeoutFn=Sf.bind(wf),e.clearTimeoutFn=kf.bind(wf)):(e.setTimeoutFn=wf.setTimeout.bind(wf),e.clearTimeoutFn=wf.clearTimeout.bind(wf))}class Pf extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class Cf extends bf{constructor(e){super(),this.writable=!1,Rf(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new Pf(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=uf(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const Tf="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),Ef={};let Df,Lf=0,Mf=0;function If(e){let t="";do{t=Tf[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function xf(){const e=If(+new Date);return e!==Df?(Lf=0,Df=e):e+"."+If(Lf++)}for(;Mf<64;Mf++)Ef[Tf[Mf]]=Mf;let Of=!1;try{Of="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(eg){}const Af=Of;function jf(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Af))return new XMLHttpRequest}catch(e){}if(!t)try{return new(wf[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function Nf(){}const Bf=null!=new jf({xdomain:!1}).responseType;class Ff extends bf{constructor(e,t){super(),Rf(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=_f(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const r=this.xhr=new jf(t);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=Ff.requestsCount++,Ff.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Nf,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Ff.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(Ff.requestsCount=0,Ff.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Uf);else if("function"==typeof addEventListener){addEventListener("onpagehide"in wf?"pagehide":"unload",Uf,!1)}function Uf(){for(let e in Ff.requests)Ff.requests.hasOwnProperty(e)&&Ff.requests[e].abort()}const qf="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Wf=wf.WebSocket||wf.MozWebSocket,zf="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const $f={websocket:class extends Cf{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=zf?{}:_f(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=zf?new Wf(e,t,r):t?new Wf(e,t):new Wf(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;nf(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}n&&qf((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=xf()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Wf}},webtransport:class extends Cf{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((e=>{this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=function(e,t){gf||(gf=new TextDecoder);const r=[];let n=0,i=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===n){if(vf(r)<1)break;const e=yf(r,1);s=128==(128&e[0]),i=127&e[0],n=i<126?3:126===i?1:2}else if(1===n){if(vf(r)<2)break;const e=yf(r,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(vf(r)<8)break;const e=yf(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(Xh);break}i=s*Math.pow(2,32)+t.getUint32(4),n=3}else{if(vf(r)<i)break;const e=yf(r,i);a.enqueue(uf(s?e:gf.decode(e),t)),n=0}if(0===i||i>e){a.enqueue(Xh);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=mf();n.readable.pipeTo(e.writable),this.writer=n.writable.getWriter();const i=()=>{r.read().then((({done:e,value:t})=>{e||(this.onPacket(t),i())})).catch((e=>{}))};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;this.writer.write(r).then((()=>{n&&qf((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends Cf{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=Bf&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(ff),n=[];for(let e=0;e<r.length;e++){const i=uf(r[e],t);if(n.push(i),"error"===i.type)break}return n})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach(((e,s)=>{nf(e,!1,(e=>{n[s]=e,++i===r&&t(n.join(ff))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=xf()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Ff(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},Vf=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hf=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Gf(e){const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=Vf.exec(e||""),s={},o=14;for(;o--;)s[Hf[o]]=i[o]||"";return-1!=r&&-1!=n&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(r[t]=n)})),r}(0,s.query),s}class Kf extends bf{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Gf(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Gf(t.host).host),Rf(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new $f[e](r)}open(){let e;if(this.opts.rememberUpgrade&&Kf.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){let t=this.createTransport(e),r=!1;Kf.priorWebsocketSuccess=!1;const n=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",(e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Kf.priorWebsocketSuccess="websocket"===t.name,this.transport.pause((()=>{r||"closed"!==this.readyState&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}})))};function i(){r||(r=!0,d(),t.close(),t=null)}const s=e=>{const r=new Error("probe error: "+e);r.transport=t.name,i(),this.emitReserved("upgradeError",r)};function o(){s("transport closed")}function a(){s("socket closed")}function c(e){t&&e.name!==t.name&&i()}const d=()=>{t.removeListener("open",n),t.removeListener("error",s),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",n),t.once("error",s),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((()=>{r||t.open()}),200):t.open()}onOpen(){if(this.readyState="open",Kf.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let r=0;r<this.writeBuffer.length;r++){const n=this.writeBuffer[r].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}var t;return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?r():e()})):this.upgrading?r():e()),this}onError(e){Kf.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}Kf.protocol=4;const Qf="function"==typeof ArrayBuffer,Jf=Object.prototype.toString,Yf="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Jf.call(Blob),Zf="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Jf.call(File);function Xf(e){return Qf&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Yf&&e instanceof Blob||Zf&&e instanceof File}function em(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(em(e[t]))return!0;return!1}if(Xf(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return em(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&em(e[t]))return!0;return!1}function tm(e){const t=[],r=e.data,n=e;return n.data=rm(r,t),n.attachments=t.length,{packet:n,buffers:t}}function rm(e,t){if(!e)return e;if(Xf(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=rm(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=rm(e[n],t));return r}return e}function nm(e,t){return e.data=im(e.data,t),delete e.attachments,e}function im(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=im(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=im(e[r],t));return e}const sm=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var om;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(om||(om={}));function am(e){return"[object Object]"===Object.prototype.toString.call(e)}class cm extends bf{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===om.BINARY_EVENT;r||t.type===om.BINARY_ACK?(t.type=r?om.EVENT:om.ACK,this.reconstructor=new dm(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Xf(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===om[r.type])throw new Error("unknown packet type "+r.type);if(r.type===om.BINARY_EVENT||r.type===om.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!cm.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case om.CONNECT:return am(t);case om.DISCONNECT:return void 0===t;case om.CONNECT_ERROR:return"string"==typeof t||am(t);case om.EVENT:case om.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===sm.indexOf(t[0]));case om.ACK:case om.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class dm{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=nm(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var lm=Object.freeze({__proto__:null,protocol:5,get PacketType(){return om},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==om.EVENT&&e.type!==om.ACK||!em(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===om.EVENT?om.BINARY_EVENT:om.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==om.BINARY_EVENT&&e.type!==om.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=tm(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}},Decoder:cm});function um(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const pm=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class hm extends bf{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[um(e,"open",this.onopen.bind(this)),um(e,"packet",this.onpacket.bind(this)),um(e,"error",this.onerror.bind(this)),um(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(pm.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:om.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const i=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,i)=>{t.push(((e,t)=>r?e?i(e):n(t):n(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...n)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()})),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:om.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case om.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case om.EVENT:case om.BINARY_EVENT:this.onevent(e);break;case om.ACK:case om.BINARY_ACK:this.onack(e);break;case om.DISCONNECT:this.ondisconnect();break;case om.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...n){r||(r=!0,t.packet({type:om.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:om.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function fm(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}fm.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},fm.prototype.reset=function(){this.attempts=0},fm.prototype.setMin=function(e){this.ms=e},fm.prototype.setMax=function(e){this.max=e},fm.prototype.setJitter=function(e){this.jitter=e};class mm extends bf{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Rf(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new fm({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||lm;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Kf(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=um(t,"open",(function(){r.onopen(),e&&e()})),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=um(t,"error",i);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn((()=>{n(),i(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}return this.subs.push(n),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(um(e,"ping",this.onping.bind(this)),um(e,"data",this.ondata.bind(this)),um(e,"error",this.onerror.bind(this)),um(e,"close",this.onclose.bind(this)),um(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){qf((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new hm(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const gm={};function vm(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),n=Gf(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,s=r.path,o=gm[i]&&s in gm[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new mm(n,t):(gm[i]||(gm[i]=new mm(n,t)),a=gm[i]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}var ym,bm,wm,_m;Object.assign(vm,{Manager:mm,Socket:hm,io:vm,connect:vm});class Sm{constructor(e){this.reconnectingAttempt=0,this.isConnected=!1,this._observer=new c,this.knownDisconnectReasonsCodes={"io server disconnect":"server.disconnect","io client disconnect":"client.disconnect","ping timeout":"ping.timeout","transport close":"transport.close","transport error":"transport.error"},ym.set(this,100),bm.set(this,!1),wm.set(this,8e3),this.logger=new $s({namespace:"Socket",logLevel:e.logLevel,onLogMessage:e.onLogMessage,sendAnalytics:e.sendAnalytics})}get observer(){return this._observer}get id(){var e;return null===(e=this.connection)||void 0===e?void 0:e.id}connect(e,t){const r=vm(e,{multiplex:!0,randomizationFactor:.2,reconnectionDelay:1e3,reconnection:!0,transports:["polling","websocket"],upgrade:!0,rememberUpgrade:!1,auth:{token:t,apiVersion:4}});this.connection=r,this.serverUrl=e,r.on(ch.Connect,(()=>{const e=this.reconnectingAttempt?ch.Reconnected:ch.Connected;this.isConnected=!0,this.setReconnectingAttempt(0),this.logger.debug(`connection.on('${ch.Connect}')`,{connectionId:r.id,recovered:r.recovered}),this.observer.safeEmit(ch.State,{state:e})})),r.on(ch.ConnectError,(e=>{this.connectionError=e,this.logger.error(`connection.on('${ch.ConnectError}')`,{error:e}),this.observer.safeEmit(ch.State,{state:ch.Error,error:e}),this.reconnectingAttempt>o(this,ym,"f")&&(r.disconnect(),this.observer.safeEmit(ch.State,{state:ch.Disconnected,code:"server.disconnect"}))})),r.on(ch.Disconnect,(e=>{this.isConnected=!1,this.setReconnectingAttempt(0),this.disconnectReason=e,this.logger.info(`connection.on('${ch.Disconnect}')`,{reason:e});const t=this.getDisconnectReasonCode(e);"server.disconnect"===t&&r.disconnect(),this.observer.safeEmit(ch.State,{state:ch.Disconnected,code:t})})),r.io.on(ch.ReconnectAttempt,(e=>{this.setReconnectingAttempt(e),this.logger.info(`connection.on('${ch.ReconnectAttempt}')`,{attempt:e}),this.observer.safeEmit(ch.State,{state:ch.Reconnecting})})),r.io.on(ch.Reconnect,(()=>{this.logger.debug(`connection.on('${ch.Reconnect}')`,{connectionId:r.id}),this.observer.safeEmit(ch.State,{state:ch.Reconnect})}))}disconnect(){this.connection&&(this.connection.offAny(),this.connection.volatile.offAny(),this.connection.disconnect(),this.connection.io.removeAllListeners(),this.setReconnectingAttempt(0))}request(e,t={}){return new Promise(((r,n)=>{this.connection?this.connection.timeout(o(this,wm,"f")).emit(e,t,((t,i)=>{if(t){const r=Ue.includes(e);return"operation has timed out"===(null==t?void 0:t.message)&&!o(this,bm,"f")&&r&&(a(this,bm,!0,"f"),this.observer.safeEmit(ch.State,{state:ch.BufferingStart})),void n(t)}i&&i.error?("Need join to channel first"===i.error&&this.observer.safeEmit(ch.State,{code:ch.NeedToJoinFirst}),n(i.error)):(o(this,bm,"f")&&(a(this,bm,!1,"f"),this.observer.safeEmit(ch.State,{state:ch.BufferingEnd})),r(i))})):n(new Error("Socket request: Socket connection is not initialized"))}))}getServerUrl(){return this.serverUrl}getDisconnectReasonCode(e){const t=String(e).toLowerCase();return this.knownDisconnectReasonsCodes[t]||t}setReconnectingAttempt(e){this.reconnectingAttempt=e}}ym=new WeakMap,bm=new WeakMap,wm=new WeakMap;class km{constructor(e){const{baseURL:t,timeout:r,customNode:n}=e;this.api=Kr.create({baseURL:t||"https://lb.livedigital.space/v1",timeout:r||5e3,withCredentials:!1,paramsSerializer:e=>us.stringify(e)}),this.customNode=n}getNode(e){return s(this,void 0,void 0,(function*(){if(this.customNode)return this.customNode;const{data:t}=yield this.api.get("/nodes/best",{params:e});return t}))}}class Rm extends b{constructor(e,t){super(e,null!=t?t:"invalid_payload")}}!function(e){e.DominantSpeaker="dominant-speaker",e.PeersVolumes="peers-volumes",e.Silence="silence"}(_m||(_m={}));class Pm{constructor(e){const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new $s({logLevel:t.logLevel,namespace:"ChannelAudioObserverEventHandler",onLogMessage:r,sendAnalytics:t.sendAnalytics})}handle(e){try{const t=JSON.parse(e);switch(Pm.validateEventPayload(t),t.event){case _m.DominantSpeaker:this.handleDominantSpeaker(t);break;case _m.PeersVolumes:this.handlePeerVolumes(t);break;case _m.Silence:this.handleSilence()}}catch(t){this.logger.warn("Failed to handle audio observer event",{error:ut(t),eventData:e})}}handleDominantSpeaker(e){const{peerId:t}=e.data,r=this.engine.getPeerById(t);this.engine.setActiveSpeakerPeer(r)}handlePeerVolumes(e){e.volumes.forEach((e=>{var t;const{peerId:r,trackLabel:n,value:i}=e,s=null===(t=this.engine.getPeerById(r))||void 0===t?void 0:t.tracks.get(n);s&&s.setVolume(i)}))}handleSilence(){this.engine.peers.flatMap((e=>Array.from(e.tracks.values()))).forEach((e=>e.setVolume(0))),this.engine.setActiveSpeakerPeer(void 0)}static validateEventPayload(e){switch(e.event){case _m.Silence:break;case _m.DominantSpeaker:{e.data||Pm.throwInvalidPayload();const{peerId:t,producerId:r,trackLabel:n}=e.data;"string"==typeof t&&"string"==typeof r&&n===m.Microphone||Pm.throwInvalidPayload();break}case _m.PeersVolumes:Array.isArray(e.volumes)||Pm.throwInvalidPayload(),e.volumes.forEach((e=>{const{peerId:t,producerId:r,value:n,trackLabel:i}=e;"string"==typeof t&&"string"==typeof r&&"number"==typeof n&&i===m.Microphone||Pm.throwInvalidPayload()}));break;default:Pm.throwInvalidPayload()}}static throwInvalidPayload(){throw new Rm("Invalid channel audio observer event handler payload")}}function Cm(e,t){var r,n;if(0===t.length)return e;for(r=0,n=t.length;r<n;r++)e=(e<<5)-e+t.charCodeAt(r),e|=0;return e<0?-2*e:e}function Tm(e,t,r,n){var i=Cm(Cm(Cm(e,r),function(e){return Object.prototype.toString.call(e)}(t)),typeof t);if(null===t)return Cm(i,"null");if(void 0===t)return Cm(i,"undefined");if("object"==typeof t||"function"==typeof t){if(-1!==n.indexOf(t))return Cm(i,"[Circular]"+r);n.push(t);var s=function(e,t,r){return Object.keys(t).sort().reduce((function(e,n){return Tm(e,t[n],n,r)}),e)}(i,t,n);if(!("valueOf"in t)||"function"!=typeof t.valueOf)return s;try{return Cm(s,String(t.valueOf()))}catch(e){return Cm(s,"[valueOf exception]"+(e.stack||e.message))}}return Cm(i,t.toString())}var Em=function(e){return function(e,t){for(;e.length<t;)e="0"+e;return e}(Tm(0,e,"",[]).toString(16),8)},Dm=Uint8Array,Lm=Uint16Array,Mm=Int32Array,Im=new Dm([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),xm=new Dm([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Om=new Dm([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Am=function(e,t){for(var r=new Lm(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var i=new Mm(r[30]);for(n=1;n<30;++n)for(var s=r[n];s<r[n+1];++s)i[s]=s-r[n]<<5|n;return{b:r,r:i}},jm=Am(Im,2),Nm=jm.b,Bm=jm.r;Nm[28]=258,Bm[258]=28;for(var Fm=Am(xm,0).b,Um=new Lm(32768),qm=0;qm<32768;++qm){var Wm=(43690&qm)>>1|(21845&qm)<<1;Wm=(61680&(Wm=(52428&Wm)>>2|(13107&Wm)<<2))>>4|(3855&Wm)<<4,Um[qm]=((65280&Wm)>>8|(255&Wm)<<8)>>1}var zm=function(e,t,r){for(var n=e.length,i=0,s=new Lm(t);i<n;++i)e[i]&&++s[e[i]-1];var o,a=new Lm(t);for(i=1;i<t;++i)a[i]=a[i-1]+s[i-1]<<1;if(r){o=new Lm(1<<t);var c=15-t;for(i=0;i<n;++i)if(e[i])for(var d=i<<4|e[i],l=t-e[i],u=a[e[i]-1]++<<l,p=u|(1<<l)-1;u<=p;++u)o[Um[u]>>c]=d}else for(o=new Lm(n),i=0;i<n;++i)e[i]&&(o[i]=Um[a[e[i]-1]++]>>15-e[i]);return o},$m=new Dm(288);for(qm=0;qm<144;++qm)$m[qm]=8;for(qm=144;qm<256;++qm)$m[qm]=9;for(qm=256;qm<280;++qm)$m[qm]=7;for(qm=280;qm<288;++qm)$m[qm]=8;var Vm=new Dm(32);for(qm=0;qm<32;++qm)Vm[qm]=5;var Hm=zm($m,9,1),Gm=zm(Vm,5,1),Km=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Qm=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},Jm=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Ym=function(e){return(e+7)/8|0},Zm=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new Dm(e.subarray(t,r))},Xm=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],eg=function(e,t,r){var n=new Error(t||Xm[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,eg),!r)throw n;return n},tg=function(e,t,r,n){var i=e.length,s=n?n.length:0;if(!i||t.f&&!t.l)return r||new Dm(0);var o=!r,a=o||2!=t.i,c=t.i;o&&(r=new Dm(3*i));var d=function(e){var t=r.length;if(e>t){var n=new Dm(Math.max(2*t,e));n.set(r),r=n}},l=t.f||0,u=t.p||0,p=t.b||0,h=t.l,f=t.d,m=t.m,g=t.n,v=8*i;do{if(!h){l=Qm(e,u,1);var y=Qm(e,u+1,3);if(u+=3,!y){var b=e[(L=Ym(u)+4)-4]|e[L-3]<<8,w=L+b;if(w>i){c&&eg(0);break}a&&d(p+b),r.set(e.subarray(L,w),p),t.b=p+=b,t.p=u=8*w,t.f=l;continue}if(1==y)h=Hm,f=Gm,m=9,g=5;else if(2==y){var _=Qm(e,u,31)+257,S=Qm(e,u+10,15)+4,k=_+Qm(e,u+5,31)+1;u+=14;for(var R=new Dm(k),P=new Dm(19),C=0;C<S;++C)P[Om[C]]=Qm(e,u+3*C,7);u+=3*S;var T=Km(P),E=(1<<T)-1,D=zm(P,T,1);for(C=0;C<k;){var L,M=D[Qm(e,u,E)];if(u+=15&M,(L=M>>4)<16)R[C++]=L;else{var I=0,x=0;for(16==L?(x=3+Qm(e,u,3),u+=2,I=R[C-1]):17==L?(x=3+Qm(e,u,7),u+=3):18==L&&(x=11+Qm(e,u,127),u+=7);x--;)R[C++]=I}}var O=R.subarray(0,_),A=R.subarray(_);m=Km(O),g=Km(A),h=zm(O,m,1),f=zm(A,g,1)}else eg(1);if(u>v){c&&eg(0);break}}a&&d(p+131072);for(var j=(1<<m)-1,N=(1<<g)-1,B=u;;B=u){var F=(I=h[Jm(e,u)&j])>>4;if((u+=15&I)>v){c&&eg(0);break}if(I||eg(2),F<256)r[p++]=F;else{if(256==F){B=u,h=null;break}var U=F-254;if(F>264){var q=Im[C=F-257];U=Qm(e,u,(1<<q)-1)+Nm[C],u+=q}var W=f[Jm(e,u)&N],z=W>>4;W||eg(3),u+=15&W;A=Fm[z];if(z>3){q=xm[z];A+=Jm(e,u)&(1<<q)-1,u+=q}if(u>v){c&&eg(0);break}a&&d(p+131072);var $=p+U;if(p<A){var V=s-A,H=Math.min(A,$);for(V+p<0&&eg(3);p<H;++p)r[p]=n[V+p]}for(;p<$;++p)r[p]=r[p-A]}}t.l=h,t.p=B,t.b=p,t.f=l,h&&(l=1,t.m=m,t.d=f,t.n=g)}while(!l);return p!=r.length&&o?Zm(r,0,p):r.subarray(0,p)},rg=new Dm(0);function ng(e,t){var r=function(e){31==e[0]&&139==e[1]&&8==e[2]||eg(6,"invalid gzip data");var t=e[3],r=10;4&t&&(r+=2+(e[10]|e[11]<<8));for(var n=(t>>3&1)+(t>>4&1);n>0;n-=!e[r++]);return r+(2&t)}(e);return r+8>e.length&&eg(6,"invalid gzip data"),tg(e.subarray(r,-8),{i:2},t&&t.out||new Dm(function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}(e)),t&&t.dictionary)}function ig(e,t){return tg(e.subarray(function(e,t){return(8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31)&&eg(6,"invalid zlib data"),(e[1]>>5&1)==+!t&&eg(6,"invalid zlib data: "+(32&e[1]?"need":"unexpected")+" dictionary"),2+(e[1]>>3&4)}(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function sg(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?ng(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return tg(e,{i:2},t&&t.out,t&&t.dictionary)}(e,t):ig(e,t)}var og="undefined"!=typeof TextDecoder&&new TextDecoder;try{og.decode(rg,{stream:!0}),1}catch(cg){}var ag,cg,dg;function lg(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}if(og)return og.decode(e);var i=function(e){for(var t="",r=0;;){var n=e[r++],i=(n>127)+(n>223)+(n>239);if(r+i>e.length)return{s:t,r:Zm(e,r-1)};i?3==i?(n=((15&n)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|n>>10,56320|1023&n)):t+=1&i?String.fromCharCode((31&n)<<6|63&e[r++]):String.fromCharCode((15&n)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(n)}}(e),s=i.s;return(r=i.r).length&&eg(8),s}function ug(){}function pg(){pg.init.call(this)}function hg(e){return void 0===e._maxListeners?pg.defaultMaxListeners:e._maxListeners}function fg(e,t,r){if(t)e.call(r);else for(var n=e.length,i=Sg(e,n),s=0;s<n;++s)i[s].call(r)}function mg(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=Sg(e,i),o=0;o<i;++o)s[o].call(r,n)}function gg(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=Sg(e,s),a=0;a<s;++a)o[a].call(r,n,i)}function vg(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=Sg(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}function yg(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=Sg(e,i),o=0;o<i;++o)s[o].apply(r,n)}function bg(e,t,r,n){var i,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]):(s=e._events=new ug,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=hg(e))&&i>0&&o.length>i){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[t]=r,++e._eventsCount;return e}function wg(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function _g(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Sg(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}ug.prototype=Object.create(null),pg.EventEmitter=pg,pg.usingDomains=!1,pg.prototype.domain=void 0,pg.prototype._events=void 0,pg.prototype._maxListeners=void 0,pg.defaultMaxListeners=10,pg.init=function(){this.domain=null,pg.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new ug,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},pg.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},pg.prototype.getMaxListeners=function(){return hg(this)},pg.prototype.emit=function(e){var t,r,n,i,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(n=arguments.length){case 1:fg(r,l,this);break;case 2:mg(r,l,this,arguments[1]);break;case 3:gg(r,l,this,arguments[1],arguments[2]);break;case 4:vg(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),s=1;s<n;s++)i[s-1]=arguments[s];yg(r,l,this,i)}return!0},pg.prototype.addListener=function(e,t){return bg(this,e,t,!1)},pg.prototype.on=pg.prototype.addListener,pg.prototype.prependListener=function(e,t){return bg(this,e,t,!0)},pg.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,wg(this,e,t)),this},pg.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,wg(this,e,t)),this},pg.prototype.removeListener=function(e,t){var r,n,i,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new ug:(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new ug,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}(r,i);n.removeListener&&this.emit("removeListener",e,o||t)}return this},pg.prototype.off=function(e,t){return this.removeListener(e,t)},pg.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new ug,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new ug:delete r[e]),this;if(0===arguments.length){for(var n,i=Object.keys(r),s=0;s<i.length;++s)"removeListener"!==(n=i[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new ug,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},pg.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},pg.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):_g.call(e,t)},pg.prototype.listenerCount=_g,pg.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class kg extends pg{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(ag||(ag={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(cg||(cg={})),function(e){e.OutboundNetworkQuality="outbound-network-quality",e.InboundNetworkQuality="inbound-network-quality",e.OutboundNetworkMediaLatency="outbound-network-media-latency",e.InboundNetworkMediaLatency="inbound-network-media-latency",e.NetworkMediaSyncFailure="network-media-sync-failure",e.OutboundNetworkThroughput="outbound-network-throughput",e.InboundNetworkThroughput="inbound-network-throughput",e.EncoderCPUThrottling="encoder-cpu-throttling",e.DecoderCPUThrottling="decoder-cpu-throttling",e.ServerIssue="server-issue",e.UnknownVideoDecoderIssue="unknown-video-decoder",e.LowInboundMOS="low-inbound-mean-opinion-score",e.LowOutboundMOS="low-outbound-mean-opinion-score",e.FrozenVideoTrack="frozen-video-track"}(dg||(dg={}));class Rg extends pg{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(e){super(),this.compositeStatsParser=e.compositeStatsParser,this.getStatsInterval=e.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;const e=()=>setTimeout((()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally((()=>{this.reportTimer=e()}))}),this.getStatsInterval);this.isStopped=!1,this.reportTimer=e()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){const e=Date.now(),t=await this.compositeStatsParser.parse(),r=Date.now()-e;this.emit(Rg.STATS_REPORTS_PARSED,{timeTaken:r}),t.forEach((e=>{this.emit(Rg.STATS_REPORT_READY_EVENT,e)}))}}const Pg=(()=>{const e=new Map;return t=>{const{taskId:r,delayMs:n,maxJitterMs:i,callback:s}=t,o=Math.ceil(Math.random()*(i||0)),a=e.get(r);a&&clearTimeout(a);const c=setTimeout((()=>{s(),e.delete(r)}),n+o);e.set(r,c)}})();class Cg{#e={};calculate(e){const{connection:{id:t}}=e,{mos:r,stats:n}=this.calculateOutboundScore(e)||{},{mos:i,stats:s}=this.calculateInboundScore(e)||{};return this.#e[t]=e,Pg({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:r,inbound:i,connectionId:t,statsSamples:{inboundStatsSample:s,outboundStatsSample:n}}}calculateOutboundScore(e){const t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:i}=e.connection,s=r.connection.packetsSent,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=i-s,u=o.packetsLost-o.lastPacketsLost,p=l&&u?Math.round(100*u/(l+u)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateInboundScore(e){const t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:i}=e.connection,s=r.connection.packetsReceived,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=i-s,u=o.packetsLost-o.lastPacketsLost,p=l&&u?Math.round(100*u/(l+u)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateMOS({avgJitter:e,rtt:t,packetsLoss:r}){const n=t+2*e+10;let i=n<160?93.2-n/40:93.2-n/120-10;return i-=2.5*r,1+.035*i+7e-6*i*(i-60)*(100-i)}}class Tg{#e;#t;constructor(e={}){this.#e=new Map,this.#t=e.statsCleanupTtlMs??35e3}detect(e){const t=this.performDetection(e);return this.performPrevStatsCleanup({connectionId:e.connection.id}),t}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;this.#e.has(t)&&Pg({taskId:t,delayMs:this.#t,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof r&&r()}})}setLastProcessedStats(e,t){this.#e.set(e,t)}getLastProcessedStats(e){return this.#e.get(e)}deleteLastProcessedStats(e){this.#e.delete(e)}}class Eg extends Tg{#r;constructor(e={}){super(e),this.#r=e.availableOutgoingBitrateThreshold??1e5}performDetection(e){const t=[],{availableOutgoingBitrate:r}=e.connection;if(void 0===r)return t;const n=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),i=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!n&&!i)return t;const s={availableOutgoingBitrate:r,videoStreamsTotalBitrate:i,audioStreamsTotalTargetBitrate:n};return n>r||i>0&&r<this.#r?(t.push({statsSample:s,type:cg.Network,reason:dg.OutboundNetworkThroughput}),t):t}}class Dg extends Tg{#n;constructor(e={}){super(e),this.#n=e.framesDroppedThreshold??.5}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.inbound.filter((e=>e.framesDropped>0)),r=[],n=this.getLastProcessedStats(e.connection.id)?.video.inbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesDropped===t.framesDropped)return;const i=e.framesReceived-t.framesReceived,s=e.framesDecoded-t.framesDecoded,o=e.framesDropped-t.framesDropped,a=o/i;if(0===i||0===s)return;const c={deltaFramesDropped:o,deltaFramesReceived:i,deltaFramesDecoded:s,framesDroppedPct:Math.round(100*a)};a>=this.#n&&r.push({statsSample:c,type:cg.CPU,reason:dg.DecoderCPUThrottling,ssrc:e.ssrc})})),r):r}}class Lg extends Tg{#i;constructor(e={}){super(e),this.#i=e.missedFramesThreshold??.15}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.outbound.filter((e=>e.framesEncoded>0)),r=[],n=this.getLastProcessedStats(e.connection.id)?.video.outbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesEncoded===t.framesEncoded)return;const i=e.framesEncoded-t.framesEncoded,s=e.framesSent-t.framesSent,o=1-s/i;if(0===i)return;if(i===s)return;const a={deltaFramesSent:s,deltaFramesEncoded:i,missedFramesPct:Math.round(100*o)};o>=this.#i&&r.push({statsSample:a,type:cg.Network,reason:dg.OutboundNetworkThroughput,ssrc:e.ssrc})})),r):r}}class Mg extends Tg{#s;#o;#a;#c;constructor(e={}){super(),this.#s=e.highPacketLossThresholdPct??5,this.#o=e.highJitterThreshold??200,this.#a=e.highJitterBufferDelayThresholdMs??500,this.#c=e.highRttThresholdMs??250}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=[],r=[...e.audio?.inbound,...e.video?.inbound];if(!r.length)return t;const n=this.getLastProcessedStats(e.connection.id);if(!n)return t;const i=[...n.video?.inbound,...n.audio?.inbound],{packetsReceived:s}=e.connection,o=n.connection.packetsReceived,a=r.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc)),n=r?.jitterBufferDelay||0,s=r?.jitterBufferEmittedCount||0,o=t.jitterBufferDelay-n,a=t.jitterBufferEmittedCount-s,c=o&&a?1e3*o/a:0;return{sumJitter:e.sumJitter+t.jitter,sumJitterBufferDelayMs:e.sumJitterBufferDelayMs+c,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d,sumJitterBufferDelayMs:l}=a,u=d/r.length,p=l/r.length,h=s-o,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.#s,v=u>=this.#o,y=c>=this.#c,b=p>this.#a,w=y&&!v&&!g,_=g&&v,S=v&&b,k={rtt:c,packetLossPct:m,avgJitter:u,avgJitterBufferDelay:p};return(v||g)&&t.push({statsSample:k,type:cg.Network,reason:dg.InboundNetworkQuality,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:k,type:cg.Server,reason:dg.ServerIssue,iceCandidate:e.connection.remote.id}),_&&t.push({statsSample:k,type:cg.Network,reason:dg.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),S&&t.push({statsSample:k,type:cg.Network,reason:dg.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class Ig extends Tg{#d;constructor(e={}){super(),this.#d=e.correctedSamplesThresholdPct??5}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.audio.inbound,r=[],n=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;const i=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,s=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(i===s)return;const o=e.track.totalSamplesReceived-t.track.totalSamplesReceived,a=i-s,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>this.#d&&r.push({statsSample:d,type:cg.Network,reason:dg.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class xg extends Tg{#s;#o;constructor(e={}){super(),this.#s=e.highPacketLossThresholdPct??5,this.#o=e.highJitterThreshold??200}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=[],r=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!r.length)return t;const n=this.getLastProcessedStats(e.connection.id);if(!n)return t;const i=[...n.remote?.audio.inbound||[],...n.remote?.video.inbound||[]],{packetsSent:s}=e.connection,o=n.connection.packetsSent,a=r.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d}=a,l=d/r.length,u=s-o,p=a.packetsLost-a.lastPacketsLost,h=u&&p?Math.round(100*p/(u+p)):0,f=h>this.#s,m=l>=this.#o,g=!f&&m||m||f,v={rtt:c,avgJitter:l,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:cg.Network,reason:dg.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:cg.Network,reason:dg.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class Og extends Tg{performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.outbound.filter((e=>"none"!==e.qualityLimitationReason)),r=[],n=this.getLastProcessedStats(e.connection.id)?.video.outbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;const i={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&r.push({statsSample:i,type:cg.CPU,reason:dg.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:i,type:cg.Network,reason:dg.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class Ag extends Tg{UNKNOWN_DECODER="unknown";#l={};performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#l[t],"function"==typeof r&&r()}})}processData(e){const t=[],{id:r}=e.connection,n=this.getLastProcessedStats(r)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:i,ssrc:s}=e,o=n?.find((e=>e.ssrc===s));if(o)if(i===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(r,s)){this.setLastDecoderWithIssue(r,s,this.UNKNOWN_DECODER);const n={mimeType:e.mimeType,decoderImplementation:i};t.push({ssrc:s,statsSample:n,type:cg.Stream,reason:dg.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,s,void 0)})),t}setLastDecoderWithIssue(e,t,r){const n=this.#l[e]??{};void 0===r?delete n[t]:n[t]=r,this.#l[e]=n}hadLastDecoderWithIssue(e,t){const r=this.#l[e];return(r&&r[t])===this.UNKNOWN_DECODER}}class jg extends Tg{#u=new Map;#p;#n;constructor(e={}){super(),this.#p=e.timeoutMs??1e4,this.#n=e.framesDroppedThreshold??.5}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const{connection:{id:t}}=e,r=this.getLastProcessedStats(t),n=[];if(!r)return n;const{video:{inbound:i}}=e,{video:{inbound:s}}=r,o=e=>new Map(e.map((e=>[e.track.trackIdentifier,e]))),a=o(i),c=o(s),d=new Set(this.#u.keys());return Array.from(a.entries()).forEach((([e,t])=>{d.delete(e);const r=c.get(e);if(!r)return;const i=t.framesReceived-r.framesReceived,s=t.framesDropped-r.framesDropped,o=t.framesDecoded-r.framesDecoded;if(0===i)return;if(s/i>=this.#n)return;if(o>0)return void this.removeMarkIssue(e);if(!this.markIssue(e))return;const a={framesReceived:t.framesReceived,framesDropped:t.framesDropped,framesDecoded:t.framesDecoded,deltaFramesReceived:i,deltaFramesDropped:s,deltaFramesDecoded:o};n.push({statsSample:a,type:cg.Stream,reason:dg.FrozenVideoTrack,trackIdentifier:e})})),d.forEach((e=>{this.removeMarkIssue(e)})),n}markIssue(e){const t=Date.now(),r=this.#u.get(e);return r?!(t-r<this.#p):(this.#u.set(e,t),!1)}removeMarkIssue(e){this.#u.delete(e)}}const Ng=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,Bg=(e,t,r)=>8*((e,t,r)=>{if(!t)return 0;const n=e[r],i=t[r];if(null==n||null==i)return 0;const s=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===s?0:(Number(n)-Number(i))/s*1e3})(e,t,r);class Fg{connections=[];statsParser;constructor(e){this.statsParser=e.statsParser}listConnections(){return[...this.connections]}addPeerConnection(e){this.connections.push({id:e.id??String(Date.now()+Math.random().toString(32)),pc:e.pc})}removePeerConnection(e){const t=this.connections.findIndex((({pc:t})=>t===e.pc));t>=0&&this.removeConnectionsByIndexes([t])}async parse(){const e=[],t=this.connections.map((async(t,r)=>{if(!Ng(t.pc))return this.statsParser.parse(t);e.unshift(r)}));return e.length&&this.removeConnectionsByIndexes(e),(await Promise.all(t)).filter((e=>void 0!==e))}removeConnectionsByIndexes(e){e.forEach((e=>{this.connections.splice(e,1)}))}}class Ug{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);ignoreSSRCList;logger;constructor(e){this.ignoreSSRCList=e.ignoreSSRCList??[],this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!Ng(e.pc))return this.getConnectionStats(e);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:e})}async getConnectionStats(e){const{pc:t,id:r}=e;try{const n=Date.now(),i=t.getReceivers().filter((e=>e.track?.enabled)),s=t.getSenders().filter((e=>e.track?.enabled)),o=await Promise.all(i.map((e=>e.getStats()))),a=await Promise.all(s.map((e=>e.getStats())));return{id:r,stats:this.mapReportsStats([...o,...a],e),timeTaken:Date.now()-n}}catch(e){return void this.logger.error("Failed to get stats for PC",{id:r,pc:t,error:e})}}mapReportsStats(e,t){const r={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};e.forEach((e=>{e.forEach((t=>{this.allowedReportTypes.has(t.type)&&this.updateMappedStatsWithReportItemData(t,r,e)}))}));const{id:n}=t,i=this.prevStats.get(n);return i&&this.propagateStatsWithRateValues(r,i.stats),this.prevStats.set(n,{stats:r,ts:Date.now()}),Pg({taskId:n,delayMs:35e3,callback:()=>this.prevStats.delete(n)}),r}updateMappedStatsWithReportItemData(e,t,r){const n=e.type;if("candidate-pair"===n&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,r));const i=this.getMediaType(e);if(!i)return;const s=e.ssrc;if(!s||!this.ignoreSSRCList.includes(s))if("outbound-rtp"!==n)if("inbound-rtp"!==n)"remote-outbound-rtp"!==n?"remote-inbound-rtp"===n&&(this.mapConnectionStatsIfNecessary(t,e,r),t.remote[i].inbound.push({...e})):t.remote[i].outbound.push({...e});else{const n=r.get(e.trackId)||r.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,r);const s={...e,track:{...n}};t[i].inbound.push(s)}else{const n=r.get(e.trackId)||r.get(e.mediaSourceId)||{},s={...e,track:{...n}};t[i].outbound.push(s)}}getMediaType(e){const t=e.mediaType||e.kind;if(!["audio","video"].includes(t)){const{id:t}=e;if(!t)return;return String(t).includes("Video")?"video":String(t).includes("Audio")?"audio":void 0}return t}propagateStatsWithRateValues(e,t){e.audio.inbound.forEach((e=>{const r=t.audio.inbound.find((({id:t})=>t===e.id));e.bitrate=Bg(e,r,"bytesReceived"),e.packetRate=Bg(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=Bg(e,r,"bytesSent"),e.packetRate=Bg(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=Bg(e,r,"bytesReceived"),e.packetRate=Bg(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=Bg(e,r,"bytesSent"),e.packetRate=Bg(e,r,"packetsSent")}))}mapConnectionStatsIfNecessary(e,t,r){if(e.connection.id||!t.transportId)return;const n=r.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=r.get(n.selectedCandidatePairId);e.connection=this.prepareConnectionStats(t,r)}}prepareConnectionStats(e,t){if(!e||!t)return{};const r={...e};if(r.remoteCandidateId){const e=t.get(r.remoteCandidateId);r.remote={...e}}if(r.localCandidateId){const e=t.get(r.localCandidateId);r.local={...e}}return r}}class qg{eventEmitter;#h=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;autoAddPeerConnections;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new kg,e.onIssues&&this.eventEmitter.on(ag.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(ag.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new Og,new Dg,new Lg,new Mg,new xg,new Ig,new Eg,new Ag,new jg],this.networkScoresCalculator=e.networkScoresCalculator??new Cg,this.compositeStatsParser=e.compositeStatsParser??new Fg({statsParser:new Ug({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new Rg({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.autoAddPeerConnections=e.autoAddPeerConnections??!0,this.autoAddPeerConnections&&this.wrapRTCPeerConnection(),this.statsReporter.on(Rg.STATS_REPORT_READY_EVENT,(e=>{this.detectIssues({data:e.stats}),this.calculateNetworkScores(e.stats)})),this.statsReporter.on(Rg.STATS_REPORTS_PARSED,(e=>{const t={timeTaken:e.timeTaken,ts:Date.now()};this.eventEmitter.emit(ag.StatsParsingFinished,t)}))}watchNewPeerConnections(){if(!this.autoAddPeerConnections)throw new Error("Auto add peer connections was disabled in the constructor.");this.#h?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#h=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#h?(this.logger.info("Stop watching peer connections"),this.#h=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e){this.#h||!this.autoAddPeerConnections?(this.#h||!1!==this.autoAddPeerConnections||(this.logger.info("Starting stats reporting for new peer connection"),this.#h=!0,this.statsReporter.startReporting()),this.logger.debug("Handling new peer connection",e),this.compositeStatsParser.addPeerConnection({pc:e})):this.logger.debug("Skip handling new peer connection. Detector is not running",e)}emitIssues(e){this.eventEmitter.emit(ag.Issue,e)}detectIssues({data:e}){const t=this.detectors.reduce(((t,r)=>[...t,...r.detect(e)]),[]);t.length>0&&this.emitIssues(t)}calculateNetworkScores(e){const t=this.networkScoresCalculator.calculate(e);this.eventEmitter.emit(ag.NetworkScoresUpdated,t)}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");const e=window.RTCPeerConnection,t=e=>this.handleNewPeerConnection(e);function r(r){const n=new e(r);return t(n),n}r.prototype=e.prototype,window.RTCPeerConnection=r}}class Wg{constructor(e){this.missingPeers=e.missingPeers,this.missingConsumers=e.missingConsumers,this.missingProducers=e.missingProducers,this.consumersWithInconsistentState=e.consumersWithInconsistentState,this.producersWithInconsistentState=e.producersWithInconsistentState,this.peersWithInconsistentAppData=e.peersWithInconsistentAppData}hasInconsistencyCases(){return this.missingPeers.length>0||this.missingConsumers.length>0||this.missingProducers.length>0||this.consumersWithInconsistentState.length>0||this.producersWithInconsistentState.length>0||this.peersWithInconsistentAppData.length>0}}class zg{constructor(e){this.missingPeers=[],this.missingConsumers=[],this.missingProducers=[],this.consumersWithInconsistentState=[],this.producersWithInconsistentState=[],this.peersWithInconsistentAppData=[],this.localState=e.localState,this.remoteState=e.remoteState,this.ignoreIds=e.ignoreIds}check(){this.resetPreviousCheckResults(),this.remoteState.peers.forEach((e=>{if(this.ignoreIds.includes(e.id))return;const t=this.findLocalPeerById(e.id);if(!t)return void this.missingPeers.push(e.id);t.appDataHash!==e.appDataHash&&this.peersWithInconsistentAppData.push(e.id),e.producers.forEach((e=>{if(this.ignoreIds.includes(e.id))return;const r=this.findLocalConsumerByProducerId(t,e.id);r&&!this.ignoreIds.includes(r.id)&&r.paused!==e.paused&&this.consumersWithInconsistentState.push(r.id);const n=this.findLocalProducerById(t,e.id);if(n||this.missingProducers.push(e.id),r||n||this.missingConsumers.push(e.id),!n)return;n.paused!==e.paused&&this.producersWithInconsistentState.push(e.id)}))}));return new Wg({missingPeers:this.missingPeers,missingConsumers:this.missingConsumers,missingProducers:this.missingProducers,consumersWithInconsistentState:this.consumersWithInconsistentState,producersWithInconsistentState:this.producersWithInconsistentState,peersWithInconsistentAppData:this.peersWithInconsistentAppData})}getMissingPeers(){return this.missingPeers}getMissingConsumers(){return this.missingConsumers}getMissingProducers(){return this.missingProducers}getConsumersWithInconsistentState(){return this.consumersWithInconsistentState}getProducersWithInconsistentState(){return this.producersWithInconsistentState}getPeersWithInconsistentAppData(){return this.peersWithInconsistentAppData}findLocalPeerById(e){return this.localState.peers.find((t=>t.id===e))}findLocalConsumerByProducerId(e,t){var r;return null===(r=e.consumers)||void 0===r?void 0:r.find((e=>e.producerId===t))}findLocalProducerById(e,t){return e.producers.find((e=>e.id===t))}resetPreviousCheckResults(){this.missingPeers=[],this.missingConsumers=[],this.missingProducers=[],this.consumersWithInconsistentState=[],this.producersWithInconsistentState=[],this.peersWithInconsistentAppData=[]}}var $g;!function(e){e.MissingPeer="missing-peer",e.MissingConsumers="missing-consumers",e.MissingProducer="missing-producer",e.IncorrectProducerState="incorrect-producer-state",e.IncorrectConsumerState="incorrect-consumer-state"}($g||($g={}));var Vg,Hg,Gg,Kg,Qg,Jg,Yg,Zg,Xg;class ev{constructor(e){Vg.set(this,[]),Hg.set(this,[]),Gg.set(this,[]),Kg.set(this,[]),Qg.set(this,[]),Jg.set(this,[]),Yg.set(this,!1),this.networkScores={inbound:4.3,outbound:4.3};const{engine:t,onLogMessage:r,clientEventEmitter:n,webRTCIssueEmitter:i}=e;this.engine=t,this.clientEventEmitter=n,this.webRTCIssueEmitter=i,this.logger=new $s({logLevel:t.logLevel,namespace:"ChannelStateSyncEventHandler",onLogMessage:r,sendAnalytics:e.sendAnalytics}),this.listenNetworkScoresUpdatedEvents()}handle(e){return s(this,void 0,void 0,(function*(){try{const{event:t,data:r}=yield this.parseChannelStateSyncEventPayload(e);"channel-state"!==t||o(this,Yg,"f")||this.handleChannelStateEvent(r)}catch(e){this.logger.error("handleChannelStateSyncEvent()",{error:ut(e)})}}))}handleChannelStateEvent(e){return s(this,void 0,void 0,(function*(){a(this,Yg,!0,"f");try{yield this.collectProbableInconsistencyCases(e);const t=this.getConfirmedInconsistencyResult();t&&t.hasInconsistencyCases()&&this.handleConfirmedInconsistencyResult(t)}finally{a(this,Yg,!1,"f")}}))}getLastInconsistencyCheckResult(){return o(this,Jg,"f")[o(this,Jg,"f").length-1]}handleConfirmedInconsistencyResult(e){e.missingPeers.forEach((e=>{o(this,Vg,"f").push(e),this.clientEventEmitter.safeEmit(Y,{peerId:e,type:$g.MissingPeer})})),e.missingProducers.forEach((e=>{o(this,Gg,"f").push(e),this.clientEventEmitter.safeEmit(Y,{producerId:e,type:$g.MissingProducer})})),e.producersWithInconsistentState.forEach((e=>{o(this,Qg,"f").push(e),this.clientEventEmitter.safeEmit(Y,{producerId:e,type:$g.IncorrectProducerState})})),e.missingConsumers.length>0&&(o(this,Hg,"f").push(...e.missingConsumers),this.clientEventEmitter.safeEmit(Y,{type:$g.MissingConsumers})),e.consumersWithInconsistentState.length>0&&(o(this,Kg,"f").push(...e.consumersWithInconsistentState),this.clientEventEmitter.safeEmit(Y,{type:$g.IncorrectConsumerState}))}getConfirmedInconsistencyResult(){const e=this.getLastInconsistencyCheckResult();if(!e)return;return new Wg({missingPeers:this.getConfirmedMissingPeers(e.missingPeers),missingConsumers:this.getConfirmedMissingConsumers(e.missingConsumers),missingProducers:this.getConfirmedMissingProducers(e.missingProducers),consumersWithInconsistentState:this.getConfirmedConsumersWithInconsistencState(e.consumersWithInconsistentState),producersWithInconsistentState:this.getConfirmedProducersWithInconsistencState(e.producersWithInconsistentState),peersWithInconsistentAppData:this.getConfirmedPeersWithInconsistentAppData(e.missingPeers)})}collectProbableInconsistencyCases(e){return s(this,void 0,void 0,(function*(){const t=new zg({remoteState:e,localState:this.getLocalState(),ignoreIds:this.getAllConfirmedInconsistentEntityIds()}).check();if(this.rotateLastProbableInconsistencyCheckResults(t),!t.hasInconsistencyCases())return;if(this.isBadNetworkScore())return void this.resetLastProbableInconsistencyCheckResults();(yield this.getIsConnectionActive())||this.resetLastProbableInconsistencyCheckResults()}))}resetLastProbableInconsistencyCheckResults(){a(this,Jg,[],"f")}rotateLastProbableInconsistencyCheckResults(e){4===o(this,Jg,"f").length&&o(this,Jg,"f").shift(),o(this,Jg,"f").push(e)}isReachedMaxCheckRetries(e,t,r=4){let n=0;return o(this,Jg,"f").forEach((r=>{r[e].includes(t)&&(n+=1)})),n>=r}getConfirmedMissingPeers(e){return e.filter((e=>this.isReachedMaxCheckRetries("missingPeers",e)))}getConfirmedMissingConsumers(e){return e.filter((e=>this.isReachedMaxCheckRetries("missingConsumers",e,1)))}getConfirmedMissingProducers(e){return e.filter((e=>this.isReachedMaxCheckRetries("missingProducers",e)))}getConfirmedConsumersWithInconsistencState(e){return e.filter((e=>this.isReachedMaxCheckRetries("consumersWithInconsistentState",e,1)))}getConfirmedProducersWithInconsistencState(e){return e.filter((e=>this.isReachedMaxCheckRetries("producersWithInconsistentState",e)))}getConfirmedPeersWithInconsistentAppData(e){return e.filter((e=>this.isReachedMaxCheckRetries("peersWithInconsistentAppData",e)))}parseChannelStateSyncEventPayload(e){return s(this,void 0,void 0,(function*(){const t=sg("arrayBuffer"in e?new Uint8Array(yield e.arrayBuffer()):new Uint8Array(e));return JSON.parse(lg(t))}))}getAllConfirmedInconsistentEntityIds(){return[...o(this,Vg,"f"),...o(this,Hg,"f"),...o(this,Gg,"f"),...o(this,Kg,"f"),...o(this,Qg,"f")]}getLocalState(){const{hostPeers:e}=this.engine;return{peers:e.map((e=>({id:e.id,appDataHash:Em(e.appData),producers:e.getProducers().map((e=>({id:e.id,paused:e.paused}))),consumers:e.getConsumersState()})))}}getIsConnectionActive(){var e;return s(this,void 0,void 0,(function*(){try{return this.engine.checkSocketConnectionActivity(),yield null===(e=this.engine.network.socket.connection)||void 0===e?void 0:e.timeout(1e3).emitWithAck("peer.ping",{}),!0}catch(e){return!1}}))}listenNetworkScoresUpdatedEvents(){this.webRTCIssueEmitter&&this.webRTCIssueEmitter.on(ag.NetworkScoresUpdated,(e=>{e.inbound&&(this.networkScores.inbound=e.inbound),e.outbound&&(this.networkScores.outbound=e.outbound)}))}isBadNetworkScore(){const{inbound:e,outbound:t}=this.networkScores;return e<=2.6||t<=2.6}}Vg=new WeakMap,Hg=new WeakMap,Gg=new WeakMap,Kg=new WeakMap,Qg=new WeakMap,Jg=new WeakMap,Yg=new WeakMap;class tv{constructor({engine:e,onLogMessage:t,logLevel:r,sendAnalytics:n}){Zg.set(this,void 0),Xg.set(this,void 0),a(this,Zg,e,"f"),a(this,Xg,new $s({logLevel:r,namespace:"ChannelStateSyncEventHandler",onLogMessage:t,sendAnalytics:n}),"f"),this.watchNetworkState(),this.debouncedRestoreState=ft(this.restoreState.bind(this),3e3),this.debouncedSyncPeerState=ft(this.syncPeerState.bind(this),1e3)}watchNetworkState(){o(this,Zg,"f").clientEventEmitter.on(X,(()=>s(this,void 0,void 0,(function*(){yield this.debouncedRestoreState()})))),o(this,Zg,"f").clientEventEmitter.on(Y,(({type:e})=>s(this,void 0,void 0,(function*(){[$g.IncorrectConsumerState,$g.MissingConsumers].includes(e)&&(yield this.debouncedSyncPeerState(e))}))))}syncPeerState(e){return s(this,void 0,void 0,(function*(){try{if(!o(this,Zg,"f").isSocketConnectionActive)return void o(this,Xg,"f").info("Connection inactive, skipping re-syncing local peers state",{case:"restoreLocalState",type:e});o(this,Zg,"f").eventsQueue.pause(),o(this,Xg,"f").info("Re-syncing local peers state",{case:"restoreLocalState",type:e});const{peers:t}=yield o(this,Zg,"f").network.getChannelPeers("host");this.restoreLocalPeersState(t)}catch(t){o(this,Xg,"f").info("Failed to re-sync local peers state",{case:"restoreLocalState",type:e,error:ut(t)})}finally{o(this,Xg,"f").info("Resume events after re-syncing local peers",{case:"restoreLocalState",type:e,accumulatedEventsAmount:o(this,Zg,"f").eventsQueue.size()}),o(this,Zg,"f").eventsQueue.resume()}}))}restoreState(){return s(this,void 0,void 0,(function*(){try{if(!o(this,Zg,"f").isSocketConnectionActive)return void o(this,Xg,"f").info("Connection inactive, skipping restore local state",{case:"restoreLocalState"});o(this,Xg,"f").info("Restoring local state",{case:"restoreLocalState"});const e=o(this,Zg,"f").hostPeers.map((e=>e.shortData)),{peers:t}=yield o(this,Zg,"f").network.getChannelPeers("host");yield this.restoreRemoteProducersState(t),this.removeUnnecessaryPeers(e,t),this.setMissingPeers(e,t),this.restoreLocalPeersState(t)}catch(e){o(this,Xg,"f").info("Failed to restore local state",{case:"restoreLocalState",error:ut(e)})}}))}restoreRemoteProducersState(e){return s(this,void 0,void 0,(function*(){const t=o(this,Zg,"f").peers.find((e=>e.id===o(this,Zg,"f").myPeerId)),r=e.find((e=>e.id===o(this,Zg,"f").myPeerId));if(!t||!r)return;const n=o(this,Zg,"f").media.getAllTracks(),i=r.producers.filter((e=>!n.map((e=>e.producerId)).some((t=>e.id===t))));yield Promise.all(i.map((e=>s(this,void 0,void 0,(function*(){yield o(this,Zg,"f").network.closeRemoteProducer(e.id),t.producers.delete(e.id),o(this,Xg,"f").info("Unnecessary local producer closed",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})})))));const a=r.producers.filter((e=>!!n.find((t=>t.isPaused&&t.isPaused!==e.paused))));yield Promise.all(a.map((e=>s(this,void 0,void 0,(function*(){yield o(this,Zg,"f").network.pauseRemoteProducer(e.id),o(this,Xg,"f").info("Remote producer state repaired",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})})))))}))}removeUnnecessaryPeers(e,t){e.filter((e=>!t.find((t=>t.id===e.id)))).forEach((e=>{o(this,Zg,"f").removePeer(e.id),o(this,Xg,"f").info("Unnecessary peer removed",{case:"restoreLocalState",removedPeerId:e.id})}))}setMissingPeers(e,t){t.forEach((t=>{e.find((e=>e.id===t.id))||(o(this,Zg,"f").setPeer(t),o(this,Xg,"f").info("Missing peer added to storage",{case:"restoreLocalState",peerId:t.id}))}))}restoreLocalPeersState(e){const t=new Map(e.map((e=>[e.id,e])));o(this,Zg,"f").hostPeers.forEach((e=>{const r=t.get(e.id);r?(this.removeUnnecessaryProducers(e,r),this.restoreAppData(e,r),this.restoreTracksState(e,r)):o(this,Xg,"f").warn("Found new local peer, skip restoring state",{case:"restoreLocalState",newPeerId:e.id})})),o(this,Xg,"f").info("Peers state restored",{case:"restoreLocalState"})}removeUnnecessaryProducers(e,t){e.getProducers().filter((e=>!t.producers.find((t=>t.id===e.id)))).forEach((t=>{e.observer.safeEmit(ve,t),o(this,Xg,"f").info("Unnecessary producer removed",{case:"restoreLocalState",removedProducerId:t.id,removedProducerPeerId:t.peerId})}))}restoreTracksState(e,t){t.producers.forEach((t=>{const r=e.producers.get(t.id);if(!r)return e.observer.safeEmit(ge,t),void o(this,Xg,"f").info("Missing producer added to storage",{case:"restoreLocalState",producerId:t.id,producerPeerId:t.peerId});if(r.paused!==t.paused){r.paused=t.paused;const n=r.paused?oe:ae;e.observer.safeEmit(n,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused}),o(this,Xg,"f").info("Producer state fixed",{case:"restoreLocalState",producerId:t.id,producerPeerId:t.peerId})}const n=e.tracks.get(r.label);if(n&&n.consumerId&&n.isPaused!==t.paused){const{consumerId:i}=n,s=r.paused?De:Le;e.observer.safeEmit(s,i),o(this,Xg,"f").info("Consumer state fixed",{case:"restoreLocalState",consumerId:i,consumerProducerId:t.id,consumerProducerPeerId:t.peerId})}}))}restoreAppData(e,t){ht(e.appData,t.appData)||(e.observer.emit(P,t.appData),o(this,Xg,"f").info("Application data restored",{case:"restoreLocalState",peerId:e.id,appData:t.appData}))}}var rv,nv,iv,sv,ov,av,cv;Zg=new WeakMap,Xg=new WeakMap;class dv{constructor(e){rv.set(this,void 0),a(this,rv,e,"f")}create(){var e,t;const r=null!==(e=o(this,rv,"f").logger)&&void 0!==e?e:console,n=new Fg({statsParser:new Ug({ignoreSSRCList:o(this,rv,"f").ignoreSSRCList,logger:null!==(t=o(this,rv,"f").logger)&&void 0!==t?t:console})});return new qg({issueEmitter:new kg,networkScoresCalculator:new Cg,detectors:[new Og,new Dg,new Lg,new Mg,new xg,new Ig,new Eg,new Ag,new jg],statsReporter:new Rg({compositeStatsParser:n,getStatsInterval:5e3}),onIssues:this.handleIssues.bind(this,o(this,rv,"f").onIssues),onNetworkScoresUpdated:o(this,rv,"f").onNetworkScoresUpdated,ignoreSSRCList:o(this,rv,"f").ignoreSSRCList,compositeStatsParser:n,logger:r})}handleIssues(e,t){const r=t.filter((e=>e.type!==cg.Stream||e.reason!==dg.FrozenVideoTrack||this.filterNotValidFrozenVideoTrackIssues(e)));null==e||e(r)}filterNotValidFrozenVideoTrackIssues(e){const{iceCandidate:t}=e,r=t&&o(this,rv,"f").engine.getTrackByConsumerId(t);return!!r&&!r.isPaused}}rv=new WeakMap;class lv{createSystem(e){return new Kh(e)}createMedia(e){return new lh(e)}createNetwork(e){const{loadbalancer:t,logLevel:r,onLogMessage:n}=e,i=new Sm({logLevel:r,onLogMessage:n,sendAnalytics:e.sendAnalytics}),s=new km(t);return new Gh({logLevel:r,socketClient:i,loadBalancerApiClient:s,onLogMessage:n,sendAnalytics:e.sendAnalytics})}createChannelEventHandler(e){return new Qh(e)}createMediaSoupEventHandler(e){return new Jh(e)}createAudioObserverEventHandler(e){return new Pm(e)}createChannelStateSyncEventHandler(e){return new ev(e)}createChannelStateSynchronizer(e){return new tv(e)}createIssueDetector(e){return new dv(e).create()}}class uv extends AudioWorkletNode{constructor(e){super(e.context,"rnnoise",{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{module:e.noiseSuppressor.module}}),this.port.onmessage=({data:e})=>{const t=Object.assign(new Event("status"),e);this.dispatchEvent(t)}}update(e){this.port.postMessage(e)}static register(e){return s(this,void 0,void 0,(function*(){yield e.audioWorklet.addModule(`${window.location.origin}/noiseSuppressionWorklet.js`)}))}}class pv{constructor(e){nv.set(this,void 0),iv.set(this,void 0),sv.set(this,void 0),ov.set(this,void 0),av.set(this,void 0),cv.set(this,!0),a(this,nv,e.noiseSuppressor.instance.exports,"f"),a(this,iv,e.context,"f"),a(this,sv,new Float32Array(o(this,nv,"f").memory.buffer),"f"),a(this,ov,o(this,nv,"f").newState(),"f"),a(this,av,o(this,iv,"f").createScriptProcessor(),"f"),this.setOnAudioProcess()}get noiseSuppressionScriptProcessorNode(){return o(this,av,"f")}update(e){e||(a(this,cv,!1,"f"),o(this,nv,"f").deleteState(o(this,ov,"f")));const t=Object.assign(new Event("status"),{vadProb:o(this,nv,"f").getVadProb(o(this,ov,"f"))});o(this,av,"f").dispatchEvent(t)}setOnAudioProcess(){o(this,av,"f").addEventListener("audioprocess",(({inputBuffer:e,outputBuffer:t})=>{if(!o(this,cv,"f"))return;o(this,sv,"f").set(e.getChannelData(0),o(this,nv,"f").getInput(o(this,ov,"f"))/4);const r=t.getChannelData(0),n=o(this,nv,"f").pipe(o(this,ov,"f"),r.length)/4;n&&r.set(o(this,sv,"f").subarray(n,n+r.length))}))}}nv=new WeakMap,iv=new WeakMap,sv=new WeakMap,ov=new WeakMap,av=new WeakMap,cv=new WeakMap;var hv,fv,mv,gv,vv,yv,bv,wv,_v,Sv;class kv{constructor({context:e,noiseSuppressor:t}){hv.set(this,void 0),fv.set(this,void 0),mv.set(this,void 0),a(this,hv,e,"f"),a(this,fv,t,"f")}createNoiseSuppressionNode(){return s(this,void 0,void 0,(function*(){return/apple/i.test(navigator.vendor)?this.createScriptProcessorNode():this.createAudioWorkletNode()}))}stop(){var e;null===(e=o(this,mv,"f"))||void 0===e||e.update(!1)}createAudioWorkletNode(){return s(this,void 0,void 0,(function*(){return yield uv.register(o(this,hv,"f")),a(this,mv,new uv({context:o(this,hv,"f"),noiseSuppressor:o(this,fv,"f")}),"f"),o(this,mv,"f")}))}createScriptProcessorNode(){return a(this,mv,new pv({context:o(this,hv,"f"),noiseSuppressor:o(this,fv,"f")}),"f"),o(this,mv,"f").noiseSuppressionScriptProcessorNode}}hv=new WeakMap,fv=new WeakMap,mv=new WeakMap;class Rv{constructor(e){gv.set(this,void 0),vv.set(this,void 0),yv.set(this,void 0),bv.set(this,void 0),a(this,gv,e.noiseSuppressor,"f"),a(this,yv,new $s({namespace:"TrackProcessor",logLevel:e.logLevel,sendAnalytics:e.sendAnalytics}),"f")}get isProcessing(){return!!o(this,bv,"f")}processTrack(e){return s(this,void 0,void 0,(function*(){const t=(e=>{const t=window.AudioContext||window.webkitAudioContext||!1;return t?new t(e):null})();if(!t)throw new Error("AudioContext is not available");const r=new MediaStreamAudioDestinationNode(t,{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers"});yield uv.register(t);const n=t.createMediaStreamSource(new MediaStream([e])),i=new kv({context:t,noiseSuppressor:o(this,gv,"f")}),s=yield i.createNoiseSuppressionNode();s.connect(r),n.connect(s);const[c]=r.stream.getTracks();return a(this,vv,{audioContext:t,streamDestination:r,noiseSuppressionNode:s,noiseSuppressionProvider:i},"f"),a(this,bv,c,"f"),o(this,yv,"f").info("processTrack()",{track:e.id}),c}))}stopProcessing(){var e;return s(this,void 0,void 0,(function*(){if(this.isProcessing)if(o(this,vv,"f"))try{o(this,vv,"f").noiseSuppressionProvider.stop(),o(this,vv,"f").noiseSuppressionNode.disconnect(),o(this,vv,"f").streamDestination.disconnect(),yield o(this,vv,"f").audioContext.close(),null===(e=o(this,bv,"f"))||void 0===e||e.stop(),a(this,bv,void 0,"f"),o(this,yv,"f").info("stopProcessing()",{success:!0})}catch(e){o(this,yv,"f").error("stopProcessing()",{success:!1,error:e})}else o(this,yv,"f").warn("stopProcessing()",{success:!1,description:"Processing context is not available"});else o(this,yv,"f").debug("stopProcessing()",{description:"Track is not processed"})}))}}gv=new WeakMap,vv=new WeakMap,yv=new WeakMap,bv=new WeakMap;class Pv extends Lh{constructor(e){super(e),wv.set(this,void 0),_v.set(this,void 0),Sv.set(this,void 0),e.noiseSuppressor&&a(this,wv,new Rv({noiseSuppressor:e.noiseSuppressor,logLevel:e.logLevel,sendAnalytics:e.engine.sendAnalytics}),"f"),a(this,Sv,new $s({namespace:"AudioTrack",logLevel:e.logLevel,sendAnalytics:e.engine.sendAnalytics}),"f")}get isEffectsProcessing(){var e;return!!(null===(e=o(this,wv,"f"))||void 0===e?void 0:e.isProcessing)}getEncoderConfig(){return this.encoderConfig}getEncodings(){var e;return null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:Bp}getCodecOptions(){var e,t;return{opusFec:null===(e=this.getEncoderConfig().enableFec)||void 0===e||e,opusDtx:null===(t=this.getEncoderConfig().enableDtx)||void 0===t||t}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||"opus"}enableNoiseSuppression(){var e;return s(this,void 0,void 0,(function*(){if(o(this,wv,"f"))try{const t=yield null===(e=o(this,wv,"f"))||void 0===e?void 0:e.processTrack(this.mediaStreamTrack);a(this,_v,this.mediaStreamTrack,"f"),yield this.replaceTrack(t)}catch(e){throw this.logger.warn("enableNoiseSuppression()",{description:"Can not enable noise suppression",track:this.logCtx,error:e}),new Error("Can not enable noise suppression")}else this.logger.warn("enableNoiseSuppression()",{description:"Track suppressor is not defined"})}))}disableNoiseSuppression(){var e,t;return s(this,void 0,void 0,(function*(){try{if(!(null===(e=o(this,wv,"f"))||void 0===e?void 0:e.isProcessing))return void o(this,Sv,"f").debug("stopProcessing()",{description:"Track is not processed"});if(!o(this,_v,"f"))return void this.logger.warn("disableNoiseSuppression()",{description:"Original track missing"});this.isPublished&&(yield this.replaceTrack(o(this,_v,"f"))),yield null===(t=o(this,wv,"f"))||void 0===t?void 0:t.stopProcessing()}catch(e){throw this.logger.warn("disableNoiseSuppression()",{description:"Can not disable noise suppression",track:this.logCtx,error:e}),new Error("Can not disable noise suppression")}}))}publish(){return s(this,void 0,void 0,(function*(){yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),codecOptions:this.getCodecOptions()}),this.internalEventEmitter.emit(ne.trackProduced,this)}))}pause(){return s(this,void 0,void 0,(function*(){yield this.mute()}))}}wv=new WeakMap,_v=new WeakMap,Sv=new WeakMap;class Cv{createAudioTrack(e){return new Pv(e)}createVideoTrack(e){return new Mh(e)}}module.exports=class{constructor(e){var t,r;const{clientEventEmitter:n,internalEventEmitter:i,network:s,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:d,logLevel:l,disableWid:u,effectsSDKParams:p,sendAnalytics:h}=e;this._clientEventEmitter=null!=n?n:new c,this._internalEventEmitter=null!=i?i:new c;const f=new lv,m=new Cv;this.engine=new Hh({dependenciesFactory:f,clientEventEmitter:this._clientEventEmitter,internalEventEmitter:this._internalEventEmitter,media:{mediaTracksFactory:m},network:{loadbalancer:{baseURL:null===(t=null==s?void 0:s.loadbalancer)||void 0===t?void 0:t.baseURL,customNode:null===(r=null==s?void 0:s.loadbalancer)||void 0===r?void 0:r.customNode}},logLevel:l,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:d,disableWid:u,effectsSDKParams:p,sendAnalytics:h})}get observer(){return this._clientEventEmitter}get id(){return this.engine.myPeerId}get peers(){return this.engine.peers}get availableVideoDevices(){return this.engine.system.availableVideoDevices}get availableAudioDevices(){return this.engine.system.availableAudioDevices}get canUseNoiseSuppression(){return this.engine.canUseNoiseSuppression}get effectsSDKInitialized(){return this.engine.media.effectsSDKInitialized}detectDevices(e){return s(this,void 0,void 0,(function*(){return yield this.engine.system.detectDevices(e),{video:this.engine.system.availableVideoDevices,audio:this.engine.system.availableAudioDevices}}))}initEffectsSDK(){return this.engine.media.initEffectsSDK()}join(e){return this.engine.join(e)}leave(){return this.engine.release()}confirmActivity(){return this.engine.confirmActivity()}createCameraVideoTrack(e){return this.engine.createCameraVideoTrack(e)}createMicrophoneAudioTrack(e){return this.engine.createMicrophoneAudioTrack(e)}createScreenMediaTracks(e){return this.engine.createScreenMediaTracks(e)}deleteTrack(e){return this.engine.deleteTrack(e)}loadPeers(e){return this.engine.loadPeers(e)}updateAppData(e){return this.engine.updateAppData(e)}getTransportsInfo(){return s(this,void 0,void 0,(function*(){return this.engine.network.getTransportsStateInfo()}))}getNodeActiveStreamsStat(){return this.engine.getNodeActiveStreamsStat()}setPreferRelay(e){this.engine.network.setPreferRelay(e)}getPreferRelay(){return this.engine.network.getPreferRelay()}};