@livedigital/client 2.41.0 → 2.41.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -236,4 +236,4 @@ PERFORMANCE OF THIS SOFTWARE.
236
236
  personMask = smoothstep(u_coverage.x, u_coverage.y, personMask);
237
237
  outColor = vec4(frameColor * personMask + backgroundColor * (1.0 - personMask), 1.0);
238
238
  }
239
- `,{width:c,height:d}=n,l=c/d,p=Xo(e,e.VERTEX_SHADER,o),u=Xo(e,e.FRAGMENT_SHADER,a),h=ea(e,p,u,t,r),f=e.getUniformLocation(h,"u_backgroundScale"),m=e.getUniformLocation(h,"u_backgroundOffset"),g=e.getUniformLocation(h,"u_inputFrame"),v=e.getUniformLocation(h,"u_personMask"),y=e.getUniformLocation(h,"u_background"),b=e.getUniformLocation(h,"u_coverage"),w=e.getUniformLocation(h,"u_lightWrapping"),_=e.getUniformLocation(h,"u_blendMode");e.useProgram(h),e.uniform2f(f,1,1),e.uniform2f(m,0,0),e.uniform1i(g,0),e.uniform1i(v,1),e.uniform2f(b,0,1),e.uniform1f(w,0),e.uniform1f(_,0);let S=null;function k(t){S=Yo(e,e.RGBA8,t.naturalWidth,t.naturalHeight,e.LINEAR,e.LINEAR),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.naturalWidth,t.naturalHeight,e.RGBA,e.UNSIGNED_BYTE,t);let r=0,i=0,s=t.naturalWidth,n=t.naturalHeight;s/n<l?(n=s/l,i=(t.naturalHeight-n)/2):(s=n*l,r=(t.naturalWidth-s)/2);const o=s/t.naturalWidth,a=n/t.naturalHeight;r/=t.naturalWidth,i/=t.naturalHeight,e.uniform2f(f,o,a),e.uniform2f(m,r,i)}return(null==s?void 0:s.complete)?k(s):s&&(s.onload=()=>{k(s)}),{render:function(){e.viewport(0,0,c,d),e.useProgram(h),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,i),null!==S&&(e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,S),e.uniform1i(y,2)),e.bindFramebuffer(e.FRAMEBUFFER,null),e.drawArrays(e.TRIANGLE_STRIP,0,4)},updateCoverage:function(t){e.useProgram(h),e.uniform2f(b,t[0],t[1])},updateLightWrapping:function(t){e.useProgram(h),e.uniform1f(w,t)},updateBlendMode:function(t){e.useProgram(h),e.uniform1f(_,"screen"===t?0:1)},cleanUp:function(){e.deleteTexture(S),e.deleteProgram(h),e.deleteShader(u),e.deleteShader(p)}}}(u,m,g,b,t,n);return{render:function(){return r(this,void 0,void 0,(function*(){u.activeTexture(u.TEXTURE0),u.bindTexture(u.TEXTURE_2D,v),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,u.RGBA,u.UNSIGNED_BYTE,e.htmlElement),u.bindVertexArray(f),yield w.render(),o._runInference(),_.render(),S.render(),k.render()}))},updatePostProcessingConfig:function(e){if(S.updateSigmaSpace(e.jointBilateralFilter.sigmaSpace),S.updateSigmaColor(e.jointBilateralFilter.sigmaColor),"image"===i.type){const t=k;t.updateCoverage(e.coverage),t.updateLightWrapping(e.lightWrapping),t.updateBlendMode(e.blendMode)}else if("blur"===i.type){k.updateCoverage(e.coverage)}else{const e=k;e.updateCoverage([0,.9999]),e.updateLightWrapping(0)}},cleanUp:function(){k.cleanUp(),S.cleanUp(),_.cleanUp(),w.cleanUp(),u.deleteTexture(b),u.deleteTexture(y),u.deleteTexture(v),u.deleteBuffer(g),u.deleteBuffer(m),u.deleteVertexArray(f),u.deleteShader(h)}}}var aa,ca,da,la,pa,ua,ha,fa,ma,ga;class va{constructor(e){aa.set(this,!1),ca.set(this,void 0),da.set(this,void 0),la.set(this,void 0),s(this,la,new Be({logLevel:e,namespace:"TensorFlowLoader"}),"f")}get isLoaded(){return i(this,aa,"f")}get tfliteModule(){return i(this,ca,"f")||i(this,da,"f")}loadTFLite(){return r(this,void 0,void 0,(function*(){yield Promise.all([this.loadTFLiteRegular(),this.loadTFLiteSIMD()]),this.tfliteModule&&s(this,aa,!0,"f")}))}loadTFLiteModel(e){return r(this,void 0,void 0,(function*(){if(this.tfliteModule)try{const t=va.getTFLiteModelFileName(e);i(this,la,"f").info("loading model",{modelFileName:t});const r=yield fetch(`${window.location.origin}/tflite/models/${t}.tflite`),s=yield r.arrayBuffer(),n=this.tfliteModule._getModelBufferMemoryOffset();this.tfliteModule.HEAPU8.set(new Uint8Array(s),n);const o=this.tfliteModule._loadModel(s.byteLength);i(this,la,"f").info("loading model result",{result:o})}catch(e){i(this,la,"f").warn("loadTFLiteModel()",{error:e})}else i(this,la,"f").warn("loadTFLiteModel()",{description:"TFLite module is not loaded"})}))}loadTFLiteRegular(){return r(this,void 0,void 0,(function*(){try{s(this,ca,yield createTFLiteModule(),"f")}catch(e){i(this,la,"f").error("Failed to create TFLite WebAssembly module.",{error:e})}}))}loadTFLiteSIMD(){return r(this,void 0,void 0,(function*(){try{s(this,da,yield createTFLiteSIMDModule(),"f")}catch(e){i(this,la,"f").error("Failed to create TFLite SIMD WebAssembly module.",{error:e})}}))}static getTFLiteModelFileName({model:e,inputResolution:t}){switch(e){case"meet":return"256x144"===t?"segm_full_v679":"segm_lite_v681";case"mlkit":return"selfiesegmentation_mlkit-256x256-2021_01_19-v1215.f16";default:throw new Error(`No TFLite file for this segmentation model: ${e}`)}}}function ya({sourcePlayback:e,backgroundConfig:t,segmentationConfig:i,canvas:s,tflite:n}){const o=s.getContext("2d");o.scale(1.031,1.031),o.translate(-11,-11);const[a,c]=ra[i.inputResolution],d=a*c,l=new ImageData(a,c),p=document.createElement("canvas");p.width=a,p.height=c;const u=p.getContext("2d"),h=n._getInputMemoryOffset()/4,f=n._getOutputMemoryOffset()/4;let m;return{render:function(){return r(this,void 0,void 0,(function*(){"none"!==t.type&&(function(){if(u.drawImage(e.htmlElement,0,0,e.width,e.height,0,0,a,c),"meet"===i.model||"mlkit"===i.model){const e=u.getImageData(0,0,a,c);for(let t=0;t<d;t+=1)n.HEAPF32[h+3*t]=e.data[4*t]/255,n.HEAPF32[h+3*t+1]=e.data[4*t+1]/255,n.HEAPF32[h+3*t+2]=e.data[4*t+2]/255}}(),function(){n._runInference();for(let e=0;e<d;e+=1)if("meet"===i.model){const t=n.HEAPF32[f+2*e],r=n.HEAPF32[f+2*e+1],i=Math.max(t,r),s=Math.exp(t-i),o=Math.exp(r-i);l.data[4*e+3]=255*o/(s+o)}else if("mlkit"===i.model){const t=n.HEAPF32[f+e];l.data[4*e+3]=255*t}u.putImageData(l,0,0)}()),o.globalCompositeOperation="copy",o.filter="none",(null==m?void 0:m.smoothSegmentationMask)&&("blur"===t.type||"image"===t.type)&&(o.filter="blur(8px)"),"none"!==t.type&&(o.drawImage(p,0,0,a,c,0,0,e.width,e.height),o.globalCompositeOperation="source-in",o.filter="none"),o.drawImage(e.htmlElement,0,0),"blur"===t.type&&(o.globalCompositeOperation="destination-over",o.filter="blur(8px)",o.drawImage(e.htmlElement,0,0))}))},updatePostProcessingConfig:function(e){m=e},cleanUp:function(){}}}aa=new WeakMap,ca=new WeakMap,da=new WeakMap,la=new WeakMap;class ba{constructor(e){pa.set(this,void 0),ua.set(this,void 0),ha.set(this,!1),fa.set(this,void 0),s(this,pa,new va(e.logLevel),"f"),s(this,fa,new Be({namespace:"VideoTrackProcessor",logLevel:e.logLevel}),"f")}get isProcessing(){return i(this,ha,"f")}processTrack(e){return r(this,void 0,void 0,(function*(){const{track:t,pipelineConfig:n}=e;i(this,ha,"f")&&this.stopProcessing();try{i(this,pa,"f").isLoaded||(yield i(this,pa,"f").loadTFLite(),yield i(this,pa,"f").loadTFLiteModel(n.segmentationConfig));const{tfliteModule:o}=i(this,pa,"f");if(!o)throw new Error("TensorFlow model is not available");const{targetFps:a}=n.segmentationConfig,c=yield ba.buildSourcePlayback(t),d=document.createElement("canvas");d.width=c.width,d.height=c.height;const l=function(){const e=new Map,t=new Worker(`${window.location.origin}/timerWorker.js`);t.onmessage=t=>{const r=e.get(t.data.callbackId);r&&(e.delete(t.data.callbackId),r())};let r=1;return{setTimeout:function(i,s){return r+=1,e.set(r,i),t.postMessage({callbackId:r,timeoutMs:s}),r},clearTimeout:function(r){e.has(r)&&(t.postMessage({callbackId:r}),e.delete(r))},terminate:function(){e.clear(),t.terminate()}}}(),p={config:n,sourcePlayback:c,destinationPlayback:d,tflite:o},u="canvas2dCpu"===e.pipelineConfig.segmentationConfig.pipeline?ba.buildCanvas2dPipeline(p):ba.buildWebGL2Pipeline(p),h=()=>r(this,void 0,void 0,(function*(){const e=performance.now();return yield u.render(),l.setTimeout(h,performance.now()-e)})),f=yield h();u.updatePostProcessingConfig(n.postprocessingConfig);const m=d.captureStream(a),[g]=m.getVideoTracks();return s(this,ua,{pipeline:u,destination:d,source:c.htmlElement,track:g,timerWorker:l,timerId:f},"f"),s(this,ha,!0,"f"),g}catch(e){throw i(this,fa,"f").error("processTrack()",{error:e,track:t}),new Error("Can not process this track")}}))}stopProcessing(){if(this.isProcessing)if(i(this,ua,"f"))try{i(this,ua,"f").pipeline.cleanUp(),i(this,ua,"f").source.remove(),i(this,ua,"f").destination.remove(),i(this,ua,"f").timerWorker.clearTimeout(i(this,ua,"f").timerId),i(this,ua,"f").timerWorker.terminate(),i(this,ua,"f").destination.remove(),i(this,ua,"f").track.stop(),s(this,ua,void 0,"f"),s(this,ha,!1,"f")}catch(e){i(this,fa,"f").error("cleanUp()",{error:e})}else i(this,fa,"f").warn("cleanUp()",{description:"This track is not processing"});else i(this,fa,"f").debug("stopProcessing()",{description:"Track is not processed"})}static buildWebGL2Pipeline(e){return oa({backgroundImage:e.config.backgroundConfig.imageSource,sourcePlayback:e.sourcePlayback,backgroundConfig:e.config.backgroundConfig,segmentationConfig:e.config.segmentationConfig,canvas:e.destinationPlayback,tflite:e.tflite})}static buildCanvas2dPipeline(e){return ya({sourcePlayback:e.sourcePlayback,backgroundConfig:e.config.backgroundConfig,segmentationConfig:e.config.segmentationConfig,canvas:e.destinationPlayback,tflite:e.tflite})}static buildSourcePlayback(e){return r(this,void 0,void 0,(function*(){const t=document.createElement("video");return t.srcObject=new MediaStream([e]),t.autoplay=!0,yield t.play(),{htmlElement:t,width:t.videoWidth,height:t.videoHeight}}))}}pa=new WeakMap,ua=new WeakMap,ha=new WeakMap,fa=new WeakMap;class wa extends Ko{constructor(e){super(e),ma.set(this,void 0),ga.set(this,void 0),this.transformParams={},s(this,ma,new ba({logLevel:e.logLevel}),"f"),this.watchOrientation(),this.watchDocumentVisibility()}get isEffectsProcessing(){return i(this,ma,"f").isProcessing}getEncoderConfig(){return this.encoderConfig}getCodecOptions(){return{videoGoogleStartBitrate:this.getEncoderConfig().videoGoogleStartBitrate||1e3}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||(this.getLabel()===u.ScreenVideo?"vp8":"h264")}getEncodings(){return this.getEncoderConfig().encodings||xo}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return r(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"})}enableBlur(){return r(this,void 0,void 0,(function*(){try{s(this,ga,this.mediaStreamTrack.clone(),"f");const e=yield i(this,ma,"f").processTrack({track:this.mediaStreamTrack,pipelineConfig:document.hidden?sa:ia});yield this.replaceTrack(e),this.logger.info("enableBlur()",{track:this})}catch(e){throw this.logger.warn("enableBlur()",{track:this,error:e}),new Error("Can not enable virtual background")}}))}disableBlur(){return r(this,void 0,void 0,(function*(){try{if(!i(this,ma,"f").isProcessing)return void this.logger.debug("disableBlur()",{description:"Track is not processed"});if(!i(this,ga,"f"))return void this.logger.warn("disableBlur()",{description:"Original track missing"});yield this.replaceTrack(i(this,ga,"f")),i(this,ma,"f").stopProcessing(),this.logger.info("disableBlur()",{track:this})}catch(e){throw this.logger.warn("disableBlur()",{track:this,error:e}),new Error("Can not disable virtual background")}}))}publish(e={}){var t;return r(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.clientEventEmitter.emit(F,this)}))}watchOrientation(){window.screen.orientation&&(this.logger.debug("watchOrientation()",{description:"Watching started"}),window.screen.orientation.addEventListener("change",(()=>r(this,void 0,void 0,(function*(){if(this.isEffectsProcessing)try{this.mediaStreamTrack.enabled=!1;const e=yield i(this,ma,"f").processTrack({track:this.mediaStreamTrack,pipelineConfig:document.hidden?sa:ia});yield this.replaceTrack(e)}catch(e){this.logger.warn("watchOrientation()",{description:"Restart blur error after orientation change",error:e})}})))))}watchDocumentVisibility(){this.logger.debug("watchDocumentVisibility()",{description:"Watching started"}),window.addEventListener("visibilitychange",(()=>r(this,void 0,void 0,(function*(){if(this.isEffectsProcessing)try{yield this.disableBlur(),yield this.enableBlur()}catch(e){this.logger.warn("watchDocumentVisibility()",{description:"Restart blur error after change document visibility",error:e})}}))))}}ma=new WeakMap,ga=new WeakMap;const _a={"yandex browser":">=22",chrome:">=74",chromium:">=74"};class Sa 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 r(this,void 0,void 0,(function*(){yield e.audioWorklet.addModule(`${window.location.origin}/noiseSuppressionWorklet.js`)}))}}var ka,Ra,Ca,Pa,Ta,Ea;class Da{constructor(e){ka.set(this,void 0),Ra.set(this,void 0),Ca.set(this,void 0),Pa.set(this,void 0),Ta.set(this,void 0),Ea.set(this,!0),s(this,ka,e.noiseSuppressor.instance.exports,"f"),s(this,Ra,e.context,"f"),s(this,Ca,new Float32Array(i(this,ka,"f").memory.buffer),"f"),s(this,Pa,i(this,ka,"f").newState(),"f"),s(this,Ta,i(this,Ra,"f").createScriptProcessor(),"f"),this.setOnAudioProcess()}get noiseSuppressionScriptProcessorNode(){return i(this,Ta,"f")}update(e){e||(s(this,Ea,!1,"f"),i(this,ka,"f").deleteState(i(this,Pa,"f")));const t=Object.assign(new Event("status"),{vadProb:i(this,ka,"f").getVadProb(i(this,Pa,"f"))});i(this,Ta,"f").dispatchEvent(t)}setOnAudioProcess(){i(this,Ta,"f").addEventListener("audioprocess",(({inputBuffer:e,outputBuffer:t})=>{if(!i(this,Ea,"f"))return;i(this,Ca,"f").set(e.getChannelData(0),i(this,ka,"f").getInput(i(this,Pa,"f"))/4);const r=t.getChannelData(0),s=i(this,ka,"f").pipe(i(this,Pa,"f"),r.length)/4;s&&r.set(i(this,Ca,"f").subarray(s,s+r.length))}))}}ka=new WeakMap,Ra=new WeakMap,Ca=new WeakMap,Pa=new WeakMap,Ta=new WeakMap,Ea=new WeakMap;var xa,Ma,La,Oa,Ia,Aa,ja,Fa,Na,Ba,Ua;class qa{constructor({context:e,noiseSuppressor:t}){xa.set(this,void 0),Ma.set(this,void 0),La.set(this,void 0),s(this,xa,e,"f"),s(this,Ma,t,"f")}createNoiseSuppressionNode(){return r(this,void 0,void 0,(function*(){return/apple/i.test(navigator.vendor)?this.createScriptProcessorNode():this.createAudioWorkletNode()}))}stop(){var e;null===(e=i(this,La,"f"))||void 0===e||e.update(!1)}createAudioWorkletNode(){return r(this,void 0,void 0,(function*(){return yield Sa.register(i(this,xa,"f")),s(this,La,new Sa({context:i(this,xa,"f"),noiseSuppressor:i(this,Ma,"f")}),"f"),i(this,La,"f")}))}createScriptProcessorNode(){return s(this,La,new Da({context:i(this,xa,"f"),noiseSuppressor:i(this,Ma,"f")}),"f"),i(this,La,"f").noiseSuppressionScriptProcessorNode}}xa=new WeakMap,Ma=new WeakMap,La=new WeakMap;class Wa{constructor(e){Oa.set(this,void 0),Ia.set(this,void 0),Aa.set(this,void 0),ja.set(this,void 0),Fa.set(this,!1),s(this,Oa,e.noiseSuppressor,"f"),s(this,Aa,new Be({namespace:"TrackProcessor",logLevel:e.logLevel}),"f")}get isProcessing(){return i(this,Fa,"f")}processTrack(e){return r(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 Sa.register(t);const n=t.createMediaStreamSource(new MediaStream([e])),o=new qa({context:t,noiseSuppressor:i(this,Oa,"f")}),a=yield o.createNoiseSuppressionNode();a.connect(r),n.connect(a);const[c]=r.stream.getTracks();return s(this,Ia,{audioContext:t,streamDestination:r,noiseSuppressionNode:a,noiseSuppressionProvider:o},"f"),s(this,ja,c,"f"),i(this,Aa,"f").info("processTrack()",{track:e}),c}))}stopProcessing(){var e;return r(this,void 0,void 0,(function*(){if(this.isProcessing)if(i(this,Ia,"f"))try{i(this,Ia,"f").noiseSuppressionProvider.stop(),i(this,Ia,"f").noiseSuppressionNode.disconnect(),i(this,Ia,"f").streamDestination.disconnect(),yield i(this,Ia,"f").audioContext.close(),null===(e=i(this,ja,"f"))||void 0===e||e.stop(),i(this,Aa,"f").info("stopProcessing()",{success:!0})}catch(e){i(this,Aa,"f").error("stopProcessing()",{success:!1,error:e})}else i(this,Aa,"f").warn("stopProcessing()",{success:!1,description:"Processing context is not available"});else i(this,Aa,"f").debug("stopProcessing()",{description:"Track is not processed"})}))}}Oa=new WeakMap,Ia=new WeakMap,Aa=new WeakMap,ja=new WeakMap,Fa=new WeakMap;class Va extends Ko{constructor(e){super(e),Na.set(this,void 0),Ba.set(this,void 0),Ua.set(this,void 0),e.noiseSuppressor&&s(this,Na,new Wa({noiseSuppressor:e.noiseSuppressor,logLevel:e.logLevel}),"f"),s(this,Ua,new Be({namespace:"AudioTrack",logLevel:e.logLevel}),"f")}get isEffectsProcessing(){var e;return!!(null===(e=i(this,Na,"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:Lo}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 r(this,void 0,void 0,(function*(){if(i(this,Na,"f"))try{const t=yield null===(e=i(this,Na,"f"))||void 0===e?void 0:e.processTrack(this.mediaStreamTrack);s(this,Ba,this.mediaStreamTrack,"f"),yield this.replaceTrack(t)}catch(e){throw this.logger.warn("enableNoiseSuppression()",{description:"Can not enable noise suppression",track:this,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 r(this,void 0,void 0,(function*(){try{if(!(null===(e=i(this,Na,"f"))||void 0===e?void 0:e.isProcessing))return void i(this,Ua,"f").debug("stopProcessing()",{description:"Track is not processed"});if(!i(this,Ba,"f"))return void this.logger.warn("disableNoiseSuppression()",{description:"Original track missing"});yield this.replaceTrack(i(this,Ba,"f")),yield null===(t=i(this,Na,"f"))||void 0===t?void 0:t.stopProcessing()}catch(e){throw this.logger.warn("disableNoiseSuppression()",{description:"Can not disable noise suppression",track:this,error:e}),new Error("Can not disable noise suppression")}}))}publish(){return r(this,void 0,void 0,(function*(){yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),codecOptions:this.getCodecOptions()}),this.clientEventEmitter.emit(F,this)}))}}Na=new WeakMap,Ba=new WeakMap,Ua=new WeakMap;const za={width:1280,height:720};var $a,Ga,Ha,Ja,Ka,Qa,Xa;class Ya{constructor(e){var t;$a.set(this,void 0),s(this,$a,new Be({namespace:"MediaStreamTrackManager",logLevel:null!==(t=e.logLevel)&&void 0!==t?t:Oe,onLogMessage:e.onLogMessage}),"f")}createMediaStreamTrack({label:e,constraints:t}){return r(this,void 0,void 0,(function*(){if(Ya.isDisplayMedia(e)){const[e]=yield this.createDisplayMediaTracks(t);return e}const[r]=yield this.createUserMediaTracks(t);return r}))}static isDisplayMedia(e){return[u.ScreenVideo,u.ScreenAudio].includes(e)}createUserMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getUserMedia(e);return i(this,$a,"f").debug("createUserMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}createDisplayMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getDisplayMedia(e);return i(this,$a,"f").debug("getDisplayMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}}$a=new WeakMap;class Za{constructor(e){this.isDeviceLoaded=!1,this.tracks=new Map,Ga.set(this,void 0),Ha.set(this,void 0),Ja.set(this,void 0),Ka.set(this,void 0),Qa.set(this,void 0),Xa.set(this,void 0),s(this,Ha,e.logLevel,"f"),s(this,Ga,new Be({namespace:"Media",logLevel:e.logLevel,onLogMessage:e.onLogMessage}),"f"),s(this,Ja,e.engine,"f"),s(this,Ka,e.clientEventEmitter,"f"),s(this,Qa,new Ya({logLevel:e.logLevel,onLogMessage:e.onLogMessage}),"f")}get mediasoupDevice(){return this.device||(this.device=this.createDevice()),this.device}get isNoiseSuppressorLoaded(){return!!i(this,Xa,"f")}loadDevice(e){return r(this,void 0,void 0,(function*(){this.isDeviceLoaded||(yield this.mediasoupDevice.load({routerRtpCapabilities:e}),this.isDeviceLoaded=!0)}))}createNoiseSuppressor(){return r(this,void 0,void 0,(function*(){try{if(i(this,Xa,"f"))return void i(this,Ga,"f").warn("createNoiseSuppressor()",{message:"Noise suppression module already created"});s(this,Xa,yield class{static compileModule(e){return r(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){i(this,Ga,"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()}`));i(this,Ga,"f").error("getTrackCodec()",{track:e,rtpCapabilities:t})}createTracks({constraints:e,mediaStreamTracks:t}){return t.map((t=>{const r={mediaStreamTrack:t,logLevel:i(this,Ha,"f"),engine:i(this,Ja,"f"),clientEventEmitter:i(this,Ka,"f"),constraints:e,mediaStreamTrackManager:i(this,Qa,"f")},s="audio"===t.kind?new Va(Object.assign(Object.assign({},r),{noiseSuppressor:i(this,Xa,"f")})):new wa(r);return this.tracks.set(s.id,s),i(this,Ga,"f").debug("createTrack() track created",{trackId:s.id,kind:s.kind}),s}))}createUserMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=yield i(this,Qa,"f").createUserMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createDisplayMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=yield i(this,Qa,"f").createDisplayMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}deleteTrack(e){return r(this,void 0,void 0,(function*(){yield e.closeProducer(),e.mediaStreamTrack.stop(),"disableNoiseSuppression"in e&&(yield e.disableNoiseSuppression()),this.tracks.delete(e.id),i(this,Ga,"f").debug("deleteTrack() tack deleted",{trackId:e.id,kind:e.kind})}))}getAllTracks(){return Array.from(this.tracks.values())}clearTracks(){return r(this,void 0,void 0,(function*(){try{this.getAllTracks().map((e=>e.stopMediaStreamTrack()))}catch(e){i(this,Ga,"f").warn("clearTracks()",{error:e})}finally{this.tracks.clear()}}))}static getVideoTrackTransformParams(e){const t=e.getSettings();return{width:t.width||za.width,height:t.height||za.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:za.width},height:{max:za.height}},encoderConfig:(null==e?void 0:e.videoEncoderConfig)||{encodings:Mo}}}static getCameraVideoTrackParams(e){var t;return{videoTrackOptions:null!==(t=null==e?void 0:e.video)&&void 0!==t?t:{frameRate:{max:24},width:{max:za.width},height:{max:za.height}},encoderConfig:(null==e?void 0:e.encoderConfig)||{encodings:xo}}}createDevice(){const e=(e=>{const t=null!=e?e:null===navigator||void 0===navigator?void 0:navigator.userAgent;if(!t)return;return Ye.getParser(t).satisfies(_a)?"Chrome74":void 0})();return i(this,Ga,"f").debug("Creating a media device",{handlerName:null!=e?e:"not specified"}),new qe.Device({handlerName:e})}}Ga=new WeakMap,Ha=new WeakMap,Ja=new WeakMap,Ka=new WeakMap,Qa=new WeakMap,Xa=new WeakMap;const ec=new class{sleepMs(e){return r(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}},tc=(e,t={})=>r(void 0,void 0,void 0,(function*(){var r;const i=t.maxRetries||2,s=t.minBackoffDelayMs||50;let n,o=0;for(;o<i;){o+=1;try{return yield e()}catch(e){if(n=e,t.logger&&t.logger.info("Action retry failed",{currentAttempt:o,actionName:t.actionName,error:e}),o<i){const e=Math.pow(2,o-1)*s;yield ec.sleepMs(Math.min(e,null!==(r=t.maxBackoffDelayMs)&&void 0!==r?r:e))}}}throw n}));class rc{constructor(e){this.initialized=!1,this.isJoined=!1,this.isChannelJoining=!1;const{clientEventEmitter:t,network:r,dependenciesFactory:i,logLevel:s}=e;this.logLevel=s||Le,this.system=i.createSystem({logLevel:this.logLevel,clientEventEmitter:t,onLogMessage:e.onLogMessage}),this.media=i.createMedia({logLevel:this.logLevel,engine:this,clientEventEmitter:t,onLogMessage:e.onLogMessage}),this.network=i.createNetwork({logLevel:this.logLevel,loadbalancer:r.loadbalancer,onLogMessage:e.onLogMessage}),this.peersRepository=new Map,this.clientEventEmitter=t,this.channelEventsHandler=i.createChannelEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.mediaSoupEventsHandler=i.createMediaSoupEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.logger=new Be({logLevel:this.logLevel,namespace:"Engine",onLogMessage:e.onLogMessage}),this.webRtcIssueDetector=e.disableWid?void 0:i.createIssueDetector({onIssues:e.onIssues,onNetworkScoresUpdated:e.onNetworkScoresUpdated,ignoreSSRCList:[1234],logger:new Be({logLevel:this.logLevel,namespace:"WID"})}),this.watchSocketState(),this.watchClientEvents()}initialize(){var e,t,i;return r(this,void 0,void 0,(function*(){try{const{rtpCapabilities:r}=yield this.network.socket.request("router.getRtpCapabilities");yield this.media.createNoiseSuppressor(),yield this.media.loadDevice(r),null===(e=this.webRtcIssueDetector)||void 0===e||e.watchNewPeerConnections(),yield this.network.createSendTransport(this.media.mediasoupDevice),yield 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===(i=this.network.receiveTransport)||void 0===i?void 0:i.id})}catch(e){if(this.logger.error("initialize()",{error:e}),e instanceof f&&"device not supported"===e.message||e instanceof Error&&"RTCPeerConnection is not defined"===e.message)throw new v("Device not supported",v.UNSUPPORTED_DEVICE_CODE);throw new Error("Error initialize engine")}}))}release(){var e;return r(this,void 0,void 0,(function*(){try{this.initialized=!1,this.isJoined=!1,this.app=void 0,this.channel=void 0,null===(e=this.webRtcIssueDetector)||void 0===e||e.stopWatchingNewPeerConnections(),this.network.socket.disconnect(),this.peersRepository.clear(),yield this.network.closeSendTransport(),yield this.network.closeReceiveTransport(),yield this.media.clearTracks(),this.logger.debug("release()",{socketId:this.mySocketId})}catch(e){throw this.logger.error("release()",{error:e}),new Error("Error release engine")}}))}watchSocketState(){this.network.socket.observer.on("state",(e=>{const{state:t,code:r}=e;this.clientEventEmitter.emit(t,{code:r}),t===Y.Reconnected&&this.clientEventEmitter.emit(O)}))}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 mySocketId(){return this.network.socket.id}confirmActivity(){var e;return r(this,void 0,void 0,(function*(){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");yield this.network.socket.request(k)}))}join(e){return r(this,void 0,void 0,(function*(){try{this.logger.debug("join()",{params:e}),this.isChannelJoining=!0,yield this.connectToSocketServerWithRetry(e),yield this.performJoin(e)}catch(e){throw this.logger.error("join()",{error:e}),e}finally{this.isChannelJoining=!1}}))}loadPeers(e){return r(this,void 0,void 0,(function*(){const{peers:t}=yield this.network.socket.request(w,{role: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 Do(Object.assign(Object.assign({},e),{engine:this,loginDate:new Date}));return this.peersRepository.set(r.id,r),r}removePeer(e){const t=this.peersRepository.get(e);t&&(t.tracks.forEach((e=>e.close())),this.peersRepository.delete(e))}updateAppData(e){return r(this,void 0,void 0,(function*(){const{myPeer:t}=this;if(!t)throw new Error("Need join to channel first");try{To(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 r(this,void 0,void 0,(function*(){const t=Za.getCameraVideoTrackParams(e);try{const[r]=yield this.media.createUserMediaTracks({audio:!1,video:t.videoTrackOptions});if(r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof wa&&(r.setLabel(u.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(Za.getVideoTrackTransformParams(r.mediaStreamTrack)),null==e?void 0:e.blur))try{yield r.enableBlur()}catch(e){this.logger.warn("Failed to start virtual background, featured original track",{track:this})}return this.logger.debug("createCameraVideoTrack()",{trackParams:t,track:r}),r}catch(e){throw this.logger.error("createCameraVideoTrack()",{error:e,trackParams:t}),new Error(`Can not create camera track: ${e.message}`)}}))}createMicrophoneAudioTrack(e){return r(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(u.Microphone),t.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),(null==e?void 0:e.encoderConfig)&&t.setEncoderConfig(e.encoderConfig),t instanceof Va&&(null==e?void 0:e.noiseSuppression))try{yield t.enableNoiseSuppression()}catch(e){this.logger.warn("Failed to start noise suppression, featured original track",{track:this})}return this.logger.debug("createMicrophoneAudioTrack()",{options:e,track:t}),t}catch(t){throw this.logger.error("createMicrophoneAudioTrack()",{error:t,options:e}),new Error(`Can not create microphone track: ${t.message}`)}}))}createScreenMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=Za.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()})),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof wa){r.setLabel(u.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=Za.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),void this.logger.debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,track:r})}r.setLabel(u.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.logger.debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig,track:r})})),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}connectToSocketServerWithRetry(e){return r(this,void 0,void 0,(function*(){return tc((()=>r(this,void 0,void 0,(function*(){return this.connectToSocketServer(e)}))),{maxRetries:15,minBackoffDelayMs:150,maxBackoffDelayMs:5e3,actionName:"connectToSocketServer",logger:new Be({namespace:"RetrySocketConnect",logLevel:this.logLevel})})}))}connectToSocketServer(e){return r(this,void 0,void 0,(function*(){const{webSocketUrl:t}=yield this.getAvailableNode({channelId:e.channelId,role:e.role});this.network.socket.connect(t);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 r(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 i=s=>r(this,void 0,void 0,(function*(){const{error:r,state:n}=s,o=()=>this.network.socket.observer.removeListener("state",i),a=[Y.Disconnected,Y.Reconnecting].includes(n);return r?(o(),void t(r)):this.isChannelJoining&&a?(o(),void t(new Error(`Not expected socket state for new connection: ${n}`))):void(this.isChannelJoining&&[Y.Connected,Y.Reconnected].includes(n)&&(o(),e()))}));this.network.socket.observer.on("state",i)}))}performJoin(e){return r(this,void 0,void 0,(function*(){try{yield this.sendJoinChannelRequestWithRetry(e),this.app=e.appId,this.channel=e.channelId,yield this.initialize(),this.channelEventsHandler.subscribeToEvents(),this.mediaSoupEventsHandler.subscribeToEvents(),this.isJoined=!0,this.logger.debug("Successfully joined channel",{channelId:e.channelId})}catch(e){throw this.logger.error("performJoin()",{error:e}),e}}))}sendJoinChannelRequestWithRetry(e){return r(this,void 0,void 0,(function*(){return tc((()=>r(this,void 0,void 0,(function*(){return this.sendJoinChannelRequest(e)}))),{maxRetries:3,minBackoffDelayMs:300,actionName:"sendJoinChannelRequest",logger:new Be({namespace:"RetryJoin",logLevel:this.logLevel})})}))}sendJoinChannelRequest(e){return r(this,void 0,void 0,(function*(){return this.network.socket.request(b,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.clientEventEmitter.on(F,(e=>r(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.clientEventEmitter.on(N,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close(),this.media.deleteTrack(e)})),this.clientEventEmitter.on(B,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.pause()})),this.clientEventEmitter.on(U,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.resume()})),this.clientEventEmitter.on(q,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close()})),this.clientEventEmitter.on(W,(e=>r(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)}))))}createSelfPeerTrack(e){var t;return r(this,void 0,void 0,(function*(){const r=this.peersRepository.get(this.mySocketId);if(!r)return;yield null===(t=r.tracks.get(e.getLabel()))||void 0===t?void 0:t.close();const i=new Po({mediaStreamTrack:e.mediaStreamTrack,label:e.getLabel(),engine:this,muted:!1,paused:e.isPaused,peerEventEmitter:r.observer});r.tracks.set(i.label,i)}))}}var ic,sc,nc;function oc(){}function ac(){ac.init.call(this)}function cc(e){return void 0===e._maxListeners?ac.defaultMaxListeners:e._maxListeners}function dc(e,t,r){if(t)e.call(r);else for(var i=e.length,s=vc(e,i),n=0;n<i;++n)s[n].call(r)}function lc(e,t,r,i){if(t)e.call(r,i);else for(var s=e.length,n=vc(e,s),o=0;o<s;++o)n[o].call(r,i)}function pc(e,t,r,i,s){if(t)e.call(r,i,s);else for(var n=e.length,o=vc(e,n),a=0;a<n;++a)o[a].call(r,i,s)}function uc(e,t,r,i,s,n){if(t)e.call(r,i,s,n);else for(var o=e.length,a=vc(e,o),c=0;c<o;++c)a[c].call(r,i,s,n)}function hc(e,t,r,i){if(t)e.apply(r,i);else for(var s=e.length,n=vc(e,s),o=0;o<s;++o)n[o].apply(r,i)}function fc(e,t,r,i){var s,n,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((n=e._events)?(n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),o=n[t]):(n=e._events=new oc,e._eventsCount=0),o){if("function"==typeof o?o=n[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(s=cc(e))&&s>0&&o.length>s){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=n[t]=r,++e._eventsCount;return e}function mc(e,t,r){var i=!1;function s(){e.removeListener(t,s),i||(i=!0,r.apply(e,arguments))}return s.listener=r,s}function gc(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 vc(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}oc.prototype=Object.create(null),ac.EventEmitter=ac,ac.usingDomains=!1,ac.prototype.domain=void 0,ac.prototype._events=void 0,ac.prototype._maxListeners=void 0,ac.defaultMaxListeners=10,ac.init=function(){this.domain=null,ac.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new oc,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},ac.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},ac.prototype.getMaxListeners=function(){return cc(this)},ac.prototype.emit=function(e){var t,r,i,s,n,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(i=arguments.length){case 1:dc(r,l,this);break;case 2:lc(r,l,this,arguments[1]);break;case 3:pc(r,l,this,arguments[1],arguments[2]);break;case 4:uc(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(i-1),n=1;n<i;n++)s[n-1]=arguments[n];hc(r,l,this,s)}return!0},ac.prototype.addListener=function(e,t){return fc(this,e,t,!1)},ac.prototype.on=ac.prototype.addListener,ac.prototype.prependListener=function(e,t){return fc(this,e,t,!0)},ac.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,mc(this,e,t)),this},ac.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,mc(this,e,t)),this},ac.prototype.removeListener=function(e,t){var r,i,s,n,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new oc:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,n=r.length;n-- >0;)if(r[n]===t||r[n].listener&&r[n].listener===t){o=r[n].listener,s=n;break}if(s<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new oc,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,s=e.length;i<s;r+=1,i+=1)e[r]=e[i];e.pop()}(r,s);i.removeListener&&this.emit("removeListener",e,o||t)}return this},ac.prototype.off=function(e,t){return this.removeListener(e,t)},ac.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new oc,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new oc:delete r[e]),this;if(0===arguments.length){for(var i,s=Object.keys(r),n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new oc,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},ac.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):[]},ac.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):gc.call(e,t)},ac.prototype.listenerCount=gc,ac.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class yc extends ac{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(ic||(ic={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(sc||(sc={})),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"}(nc||(nc={}));class bc extends ac{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(bc.STATS_REPORTS_PARSED,{timeTaken:r}),t.forEach((e=>{this.emit(bc.STATS_REPORT_READY_EVENT,e)}))}}const wc=(()=>{const e=new Map;return t=>{const{taskId:r,delayMs:i,maxJitterMs:s,callback:n}=t,o=Math.ceil(Math.random()*(s||0)),a=e.get(r);a&&clearTimeout(a);const c=setTimeout((()=>{n(),e.delete(r)}),i+o);e.set(r,c)}})();class _c{#e={};calculate(e){const{connection:{id:t}}=e,r=this.calculateOutboundScore(e),i=this.calculateInboundScore(e);return this.#e[t]=e,wc({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:r,inbound:i}}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 i=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:s}=e.connection,n=r.connection.packetsSent,o=t.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}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=s-n,p=o.packetsLost-o.lastPacketsLost,u=l&&p?Math.round(100*p/(l+p)):0;return this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:u})}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 i=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:s}=e.connection,n=r.connection.packetsReceived,o=t.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}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=s-n,p=o.packetsLost-o.lastPacketsLost,u=l&&p?Math.round(100*p/(l+p)):0;return this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:u})}calculateMOS({avgJitter:e,rtt:t,packetsLoss:r}){const i=t+2*e+10;let s=i<160?93.2-i/40:93.2-i/120-10;return s-=2.5*r,1+.035*s+7e-6*s*(s-60)*(100-s)}}class Sc{#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)&&wc({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 kc extends Sc{#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 i=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),s=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!i&&!s)return t;const n={availableOutgoingBitrate:r,videoStreamsTotalBitrate:s,audioStreamsTotalTargetBitrate:i};return i>r||s>0&&r<this.#r?(t.push({statsSample:n,type:sc.Network,reason:nc.OutboundNetworkThroughput}),t):t}}class Rc extends Sc{#i;constructor(e={}){super(e),this.#i=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=[],i=this.getLastProcessedStats(e.connection.id)?.video.inbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesDropped===t.framesDropped)return;const s=e.framesReceived-t.framesReceived,n=e.framesDecoded-t.framesDecoded,o=e.framesDropped-t.framesDropped,a=o/s;if(0===s||0===n)return;const c={deltaFramesDropped:o,deltaFramesReceived:s,deltaFramesDecoded:n,framesDroppedPct:Math.round(100*a)};a>=this.#i&&r.push({statsSample:c,type:sc.CPU,reason:nc.DecoderCPUThrottling,ssrc:e.ssrc})})),r):r}}class Cc extends Sc{#s;constructor(e={}){super(e),this.#s=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=[],i=this.getLastProcessedStats(e.connection.id)?.video.outbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesEncoded===t.framesEncoded)return;const s=e.framesEncoded-t.framesEncoded,n=e.framesSent-t.framesSent,o=1-n/s;if(0===s)return;if(s===n)return;const a={deltaFramesSent:n,deltaFramesEncoded:s,missedFramesPct:Math.round(100*o)};o>=this.#s&&r.push({statsSample:a,type:sc.Network,reason:nc.OutboundNetworkThroughput,ssrc:e.ssrc})})),r):r}}class Pc extends Sc{highPacketLossThresholdPct;highJitterThreshold;highJitterBufferDelayThresholdMs;highRttThresholdMs;constructor(e={}){super(),this.highPacketLossThresholdPct=e.highPacketLossThresholdPct??5,this.highJitterThreshold=e.highJitterThreshold??200,this.highJitterBufferDelayThresholdMs=e.highJitterBufferDelayThresholdMs??500,this.highRttThresholdMs=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 i=this.getLastProcessedStats(e.connection.id);if(!i)return t;const s=[...i.video?.inbound,...i.audio?.inbound],{packetsReceived:n}=e.connection,o=i.connection.packetsReceived,a=r.reduce(((e,t)=>{const r=s.find((e=>e.ssrc===t.ssrc)),i=r?.jitterBufferDelay||0,n=r?.jitterBufferEmittedCount||0,o=t.jitterBufferDelay-i,a=t.jitterBufferEmittedCount-n,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,p=d/r.length,u=l/r.length,h=n-o,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.highPacketLossThresholdPct,v=p>=this.highJitterThreshold,y=c>=this.highRttThresholdMs,b=u>this.highJitterBufferDelayThresholdMs,w=y&&!v&&!g,_=g&&v,S=v&&b,k={rtt:c,packetLossPct:m,avgJitter:p,avgJitterBufferDelay:u};return(v||g)&&t.push({statsSample:k,type:sc.Network,reason:nc.InboundNetworkQuality,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:k,type:sc.Server,reason:nc.ServerIssue,iceCandidate:e.connection.remote.id}),_&&t.push({statsSample:k,type:sc.Network,reason:nc.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),S&&t.push({statsSample:k,type:sc.Network,reason:nc.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class Tc extends Sc{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=[],i=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;const s=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,n=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(s===n)return;const o=e.track.totalSamplesReceived-t.track.totalSamplesReceived,a=s-n,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>5&&r.push({statsSample:d,type:sc.Network,reason:nc.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class Ec extends Sc{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 i=this.getLastProcessedStats(e.connection.id);if(!i)return t;const s=[...i.remote?.audio.inbound||[],...i.remote?.video.inbound||[]],{packetsSent:n}=e.connection,o=i.connection.packetsSent,a=r.reduce(((e,t)=>{const r=s.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,p=n-o,u=a.packetsLost-a.lastPacketsLost,h=p&&u?Math.round(100*u/(p+u)):0,f=h>5,m=l>=200,g=!f&&m||m||f,v={rtt:c,avgJitter:l,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:sc.Network,reason:nc.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:sc.Network,reason:nc.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class Dc extends Sc{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=[],i=this.getLastProcessedStats(e.connection.id)?.video.outbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;const s={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&r.push({statsSample:s,type:sc.CPU,reason:nc.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:s,type:sc.Network,reason:nc.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class xc extends Sc{UNKNOWN_DECODER="unknown";#n={};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.#n[t],"function"==typeof r&&r()}})}processData(e){const t=[],{id:r}=e.connection,i=this.getLastProcessedStats(r)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:s,ssrc:n}=e,o=i?.find((e=>e.ssrc===n));if(o)if(s===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(r,n)){this.setLastDecoderWithIssue(r,n,this.UNKNOWN_DECODER);const i={mimeType:e.mimeType,decoderImplementation:s};t.push({ssrc:n,statsSample:i,type:sc.Stream,reason:nc.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,n,void 0)})),t}setLastDecoderWithIssue(e,t,r){const i=this.#n[e]??{};void 0===r?delete i[t]:i[t]=r,this.#n[e]=i}hadLastDecoderWithIssue(e,t){const r=this.#n[e];return(r&&r[t])===this.UNKNOWN_DECODER}}const Mc=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,Lc=(e,t,r)=>8*((e,t,r)=>{if(!t)return 0;const i=e[r],s=t[r];if(null==i||null==s)return 0;const n=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===n?0:(Number(i)-Number(s))/n*1e3})(e,t,r);class Oc{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(!Mc(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 Ic{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);logger;constructor(e){this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!Mc(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 i=Date.now(),s=await Promise.all(t.getReceivers().map((e=>e.getStats()))),n=await Promise.all(t.getSenders().map((e=>e.getStats())));return{id:r,stats:this.mapReportsStats([...s,...n],e),timeTaken:Date.now()-i}}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:i}=t,s=this.prevStats.get(i);return s&&this.propagateStatsWithRateValues(r,s.stats),this.prevStats.set(i,{stats:r,ts:Date.now()}),wc({taskId:i,delayMs:35e3,callback:()=>this.prevStats.delete(i)}),r}updateMappedStatsWithReportItemData(e,t,r){const i=e.type;if("candidate-pair"===i&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,r));const s=this.getMediaType(e);if(s)if("outbound-rtp"!==i)if("inbound-rtp"!==i)"remote-outbound-rtp"!==i?"remote-inbound-rtp"===i&&(this.mapConnectionStatsIfNecessary(t,e,r),t.remote[s].inbound.push({...e})):t.remote[s].outbound.push({...e});else{const i=r.get(e.trackId)||r.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,r);const n={...e,track:{...i}};t[s].inbound.push(n)}else{const i=r.get(e.trackId)||r.get(e.mediaSourceId)||{},n={...e,track:{...i}};t[s].outbound.push(n)}}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=Lc(e,r,"bytesReceived"),e.packetRate=Lc(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=Lc(e,r,"bytesSent"),e.packetRate=Lc(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=Lc(e,r,"bytesReceived"),e.packetRate=Lc(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=Lc(e,r,"bytesSent"),e.packetRate=Lc(e,r,"packetsSent")}))}mapConnectionStatsIfNecessary(e,t,r){if(e.connection.id||!t.transportId)return;const i=r.get(t.transportId);if(i&&i.selectedCandidatePairId){const t=r.get(i.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 Ac{eventEmitter;#o=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new yc,e.onIssues&&this.eventEmitter.on(ic.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(ic.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new Dc,new Rc,new Cc,new Pc,new Ec,new Tc,new kc,new xc],this.networkScoresCalculator=e.networkScoresCalculator??new _c,this.compositeStatsParser=e.compositeStatsParser??new Oc({statsParser:new Ic({logger:this.logger})}),this.statsReporter=e.statsReporter??new bc({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.wrapRTCPeerConnection(),this.statsReporter.on(bc.STATS_REPORT_READY_EVENT,(t=>{this.detectIssues({data:t.stats,ignoreSSRCList:e.ignoreSSRCList}),this.calculateNetworkScores(t.stats)})),this.statsReporter.on(bc.STATS_REPORTS_PARSED,(e=>{const t={timeTaken:e.timeTaken,ts:Date.now()};this.eventEmitter.emit(ic.StatsParsingFinished,t)}))}watchNewPeerConnections(){this.#o?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#o=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#o?(this.logger.info("Stop watching peer connections"),this.#o=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e){this.#o?(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(ic.Issue,e)}detectIssues({data:e,ignoreSSRCList:t}){let r=this.detectors.reduce(((t,r)=>[...t,...r.detect(e)]),[]);t?.length&&(r=r.filter((e=>!e.ssrc||!t.includes(e.ssrc)))),r.length>0&&this.emitIssues(r)}calculateNetworkScores(e){const t=this.networkScoresCalculator.calculate(e);this.eventEmitter.emit(ic.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 i=new e(r);return t(i),i}r.prototype=e.prototype,window.RTCPeerConnection=r}}class jc{constructor(e){const{socketClient:t,loadBalancerApiClient:r,onLogMessage:i}=e;this.socket=t,this.loadBalancerClient=r,this.logger=new Be({namespace:"Network",logLevel:e.logLevel,onLogMessage:i})}closeRemoteProducer(e){return r(this,void 0,void 0,(function*(){yield this.socket.request(ee,{peerId:this.socket.id,producerId:e})}))}closeSendTransport(){var e;return r(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=void 0):this.logger.warn("closeSendTransport()",{message:"No available send transport"})}))}closeReceiveTransport(){var e;return r(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=void 0):this.logger.warn("closeReceiveTransport()",{message:"No available receive transport"})}))}closeTransport(e){return r(this,void 0,void 0,(function*(){try{const{success:t}=yield this.socket.request(me,{transportId:e.id});return this.logger.debug("closeTransport()",{transport:e}),Boolean(t)}catch(e){return this.logger.error("closeTransport()",{error:e}),!1}finally{e.close()}}))}createSendTransport(e){return r(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(fe,{sctpCapabilities:e.sctpCapabilities,localDirection:"send"});this.sendTransport=e.createSendTransport(t),this.logger.debug("createSendTransport()",{transport:this.sendTransport}),this.sendTransport.on(_e,(({dtlsParameters:e},i,s)=>r(this,void 0,void 0,(function*(){var r,n;try{yield this.socket.request(ge,{transportId:null===(r=this.sendTransport)||void 0===r?void 0:r.id,dtlsParameters:e}),i(),this.logger.debug("sendTransport.connect()",{transportId:null===(n=this.sendTransport)||void 0===n?void 0:n.id,dtlsRole:e.role})}catch(r){this.logger.error("sendTransport.on(`connect`)",{dtlsParameters:e,sendTransportOptions:t,error:r}),s(r)}})))),this.sendTransport.on(Se,((e,t,i)=>r(this,void 0,void 0,(function*(){var r,s,n;try{const{id:i}=yield this.socket.request(ve,{transportId:null===(r=this.sendTransport)||void 0===r?void 0:r.id,kind:e.kind,rtpParameters:e.rtpParameters,appData:e.appData});t({id:i}),this.logger.debug("sendTransport.produce()",{producerId:i,transportId:null===(s=this.sendTransport)||void 0===s?void 0:s.id,kind:e.kind})}catch(t){this.logger.error("sendTransport.produce()",{error:t,transportId:null===(n=this.sendTransport)||void 0===n?void 0:n.id,kind:e.kind}),i(t)}})))),this.sendTransport.on(be,(e=>{var t;this.logger.debug("sendTransport.state",{state:e}),"failed"===e&&this.sendTransport&&(this.restartIce(this.sendTransport),this.logger.warn("sendTransport.restartIce()",{state:e,sendTransportId:null===(t=this.sendTransport)||void 0===t?void 0:t.id})),setTimeout((()=>{var e,t;"disconnected"===(null===(e=this.sendTransport)||void 0===e?void 0:e.connectionState)&&(null===(t=this.socket.connection)||void 0===t?void 0:t.connected)&&this.logger.warn("sendTransport is closed before websocket is closed",{sendTransportId:this.sendTransport.id})}),3e3)}))}))}createRecvTransport(e){return r(this,void 0,void 0,(function*(){if(this.receiveTransport)return void this.logger.warn("createRecvTransport()",{message:"Receive transport already exists"});const t=yield this.socket.request(fe,{localDirection:"receive"});this.receiveTransport=e.createRecvTransport(t),this.logger.debug("createRecvTransport()",{transport:this.receiveTransport}),this.receiveTransport.on(_e,(({dtlsParameters:e},t,i)=>r(this,void 0,void 0,(function*(){var r,s;try{yield this.socket.request(ge,{transportId:null===(r=this.receiveTransport)||void 0===r?void 0:r.id,dtlsParameters:e}),t(),this.logger.debug("receiveTransport.connect()",{transportId:null===(s=this.receiveTransport)||void 0===s?void 0:s.id,dtlsRole:e.role})}catch(e){this.logger.error("receiveTransport.on(`connect`)",{error:e}),i(e)}})))),this.receiveTransport.on(be,(e=>{this.logger.debug("receiveTransport.state",{state:e}),"failed"===e&&this.receiveTransport&&(this.restartIce(this.receiveTransport),this.logger.debug("receiveTransport.restartIce()",{recvTransportId:this.receiveTransport.id})),setTimeout((()=>{var e,t;"disconnected"===(null===(e=this.receiveTransport)||void 0===e?void 0:e.connectionState)&&(null===(t=this.socket.connection)||void 0===t?void 0:t.connected)&&this.logger.warn("receiveTransport is closed before websocket is closed",{recvTransportId:this.receiveTransport.id})}),3e3)}))}))}getIceParameters(e){return r(this,void 0,void 0,(function*(){const t=yield this.socket.request(we,{transportId:e.id}),{error:r}=t;if(r)throw new Error(r);return this.logger.debug("getIceParameters()",{iceParameters:t}),t}))}restartIce(e){return r(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),this.logger.debug("restartIce() completed",{iceParameters:t})}catch(e){this.logger.error("restartIce()",{error:e})}}))}createConsumer({producerId:e,rtpCapabilities:t,appId:i,channelId:s,producerPeerId:n}){return r(this,void 0,void 0,(function*(){const r=this.receiveTransport;if(!r)throw this.logger.error("createConsumer()",{reason:"missing receiveTransport"}),new Error("Client not initialized");this.logger.debug("createConsumer()",{producerId:e});const o=yield this.socket.request(oe,{producerId:e,transportId:r.id,rtpCapabilities:t,appData:{peerId:this.socket.id,appId:i,channelId:s},producerPeerId:n}),a=yield r.consume(o),{producerPaused:c}=o;return this.logger.debug("Consumer created",{consumer:a,isProducerPaused:c}),{consumer:a,isProducerPaused:c}}))}closeRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(ae,{peerId:this.socket.id,consumerId:e})}))}resumeRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(de,{consumerId:e})}))}pauseRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(ce,{consumerId:e})}))}updatePeerAppData({peerId:e,appData:t}){return r(this,void 0,void 0,(function*(){return this.socket.request(S,{peerId:e,appData:t})}))}getTransportsStateInfo(){return r(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}}))}getParsedTransportStats(e){return r(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)),i=t.find((e=>"remote-candidate"===e.type)),s=t.find((e=>"transport"===e.type));return{dtlsState:null==s?void 0:s.dtlsState,iceState:null==s?void 0:s.iceState,dtlsRole:null==s?void 0:s.dtlsRole,iceRole:null==s?void 0:s.iceRole,selectedCandidatePairChanges:null==s?void 0:s.selectedCandidatePairChanges,tlsVersion:null==s?void 0:s.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==i?void 0:i.ip,address:null==i?void 0:i.address,port:null==i?void 0:i.port,protocol:null==i?void 0:i.protocol,candidateType:null==i?void 0:i.candidateType}}}catch(e){return void this.logger.warn("getParsedTransportStats()",{error:e})}else this.logger.debug("getParsedTransportStats()",{message:"Transport is missing"})}))}}class Fc{constructor(e){this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[];const{clientEventEmitter:t,logLevel:r,onLogMessage:i}=e;this.clientEventEmitter=t,this.logger=new Be({namespace:"System",logLevel:r,onLogMessage:i}),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 r(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(h.NotAllowedError);if("NotReadableError"===t.name)throw new Error(h.DeviceIsBusy);if("NotFoundError"===t.name)throw new Error(h.NotFoundError);throw new Error(h.RequestDevicesUnknownError)}}))}refreshAvailableMediaDevicesList(){return r(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 i=({label:e,kind:t})=>({label:e,kind:t});return this.logger.debug("Devices list updated",{videoDevices:t.map(i),audioDevices:r.map(i)}),e}))}detectDevices(){return r(this,void 0,void 0,(function*(){let e=[];if(this.isDevicesDetected)return;try{e=yield this.requestMediaDevicesAccess()}catch(t){if(![h.NotFoundError,h.NotAllowedError].includes(t.message))throw t;try{e=yield this.requestMediaDevicesAccess({audio:!0})}catch(t){if(![h.NotFoundError,h.NotAllowedError].includes(t.message))throw t;e=yield this.requestMediaDevicesAccess({video:!0})}}this.isDevicesDetected=!0;const t=yield this.refreshAvailableMediaDevicesList();e.forEach((e=>e.stop()));const r=t.some((e=>"audioinput"===e.kind)),i=t.some((e=>"videoinput"===e.kind));if(!r&&!i)throw new Error(h.NoDevices)}))}deviceChangeHandler(){return r(this,void 0,void 0,(function*(){this.isDevicesDetected&&(yield this.refreshAvailableMediaDevicesList(),this.clientEventEmitter.safeEmit(I,{audio:this.availableAudioDevices,video:this.availableVideoDevices}))}))}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}}class Nc{constructor(e){const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Be({logLevel:t.logLevel,namespace:"ChannelEvents",onLogMessage:r})}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");e.on(y,(e=>{this.engine.clientEventEmitter.safeEmit(T,e),this.logger.debug("New channel event",{event:e})})),e.on(b,(e=>{const t=this.engine.setPeer(e);this.engine.clientEventEmitter.safeEmit(E,t),this.logger.debug("Peer joined to the channel",{peer:t})})),e.on(_,(e=>{this.engine.removePeer(e),this.engine.clientEventEmitter.safeEmit(D,e),this.logger.debug("Peer left the channel",{peerId:e})})),e.on(C,(e=>{this.engine.clientEventEmitter.safeEmit(x,e),this.logger.info("Notify the channel that activity confirmation is required",e)})),e.on(P,(e=>{this.engine.clientEventEmitter.safeEmit(L,e),this.logger.info("Notify the channel that it has disconnected due to the activity confirmation expiring",e)})),e.on(R,(e=>{this.engine.clientEventEmitter.safeEmit(M,e),this.logger.info("Notify the channel that the activity has been acquired.",e)})),e.on(S,(({peerId:e,appData:t})=>{const r=this.engine.peers.find((t=>t.id===e));r&&r.observer.emit(S,t)}))}}class Bc{constructor(e){this.queue=new Co;const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Be({logLevel:t.logLevel,namespace:"MediasoupEvents",onLogMessage:r})}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");e.on(ee,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&!t.isMe&&t.observer.safeEmit(ee,e)})),e.on(Z,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&!t.isMe&&t.observer.safeEmit(Z,e)})),e.on(ae,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&r.observer.safeEmit(ae,e)})),e.on(de,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(de,e)})),e.on(ce,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(ce,e)})),e.on(pe,(({peerId:e,spatialLayer:t,temporalLayer:r,consumerId:i})=>{const s=this.engine.peers.find((t=>t.id===e));s&&!s.isMe&&s.observer.safeEmit(pe,{consumerId:i,spatialLayer:t,temporalLayer:r})})),e.on(le,(e=>{const{consumerPeerId:t}=e,r=this.engine.peers.find((e=>e.id===t));if(!r||r.isMe)return;r.observer.safeEmit(le,e);const i=this.engine.peers.find((e=>e.isMe));i&&i.observer.safeEmit(le,e)})),e.on(ie,(e=>{const t=this.engine.peers.find((e=>e.isMe));t&&t.observer.safeEmit(ie,e)})),e.on(ne,(({producerId:e,spatialLayer:t})=>r(this,void 0,void 0,(function*(){yield this.queue.push((()=>r(this,void 0,void 0,(function*(){yield this.handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t})}))),ne)})))),e.on(se,(({peerId:e,producerId:t,spatialLayer:i})=>r(this,void 0,void 0,(function*(){const r=this.engine.peers.find((t=>t.id===e));r&&!r.isMe&&r.observer.safeEmit(se,{peerId:e,producerId:t,spatialLayer:i})})))),e.on(ye,(({reason:e,transportId:t,direction:i,timeout:s})=>r(this,void 0,void 0,(function*(){const r=[this.engine.network.receiveTransport,this.engine.network.sendTransport].find((e=>(null==e?void 0:e.id)===t));r&&"connected"!==r.connectionState&&(this.logger.warn(ye,{reason:e,transportId:t,direction:i,timeout:s}),this.engine.clientEventEmitter.emit(A,{direction:i,reason:e}))}))))}handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t}){return r(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 wa))return void this.logger.warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const i=r.getMaxSpatialLayer();i!==t?(yield r.setMaxSpatialLayer(t),yield this.engine.network.socket.request(se,{producerId:e,maxSpatialLayer:t})):this.logger.debug("producerRequestMaxSpatialLayer()",{message:"Skip set max spatial layer",requestedSpatialLayer:t,currentMaxSpatialLayer:i})}))}}var Uc=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,qc=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],Wc=function(e){var t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));for(var s,n,o=Uc.exec(e||""),a={},c=14;c--;)a[qc[c]]=o[c]||"";return-1!=r&&-1!=i&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(e,t){var r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.substr(0,1)&&0!==t.length||i.splice(0,1);"/"==t.substr(t.length-1,1)&&i.splice(i.length-1,1);return i}(0,a.path),a.queryKey=(s=a.query,n={},s.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,r){t&&(n[t]=r)})),n),a};var Vc={exports:{}};try{Vc.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){Vc.exports=!1}var zc=Vc.exports,$c="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Gc(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||zc))return new XMLHttpRequest}catch(e){}if(!t)try{return new($c[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function Hc(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Jc=setTimeout,Kc=clearTimeout;function Qc(e,t){t.useNativeTimers?(e.setTimeoutFn=Jc.bind($c),e.clearTimeoutFn=Kc.bind($c)):(e.setTimeoutFn=setTimeout.bind($c),e.clearTimeoutFn=clearTimeout.bind($c))}var Xc=Yc;function Yc(e){if(e)return function(e){for(var t in Yc.prototype)e[t]=Yc.prototype[t];return e}(e)}Yc.prototype.on=Yc.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Yc.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},Yc.prototype.off=Yc.prototype.removeListener=Yc.prototype.removeAllListeners=Yc.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<i.length;s++)if((r=i[s])===t||r.fn===t){i.splice(s,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},Yc.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var s=(r=r.slice(0)).length;i<s;++i)r[i].apply(this,t)}return this},Yc.prototype.emitReserved=Yc.prototype.emit,Yc.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Yc.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Zc=Object.create(null);Zc.open="0",Zc.close="1",Zc.ping="2",Zc.pong="3",Zc.message="4",Zc.upgrade="5",Zc.noop="6";const ed=Object.create(null);Object.keys(Zc).forEach((e=>{ed[Zc[e]]=e}));const td={type:"error",data:"parser error"},rd="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),id="function"==typeof ArrayBuffer,sd=({type:e,data:t},r,i)=>{return rd&&t instanceof Blob?r?i(t):nd(t,i):id&&(t instanceof ArrayBuffer||(s=t,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer))?r?i(t):nd(new Blob([t]),i):i(Zc[e]+(t||""));var s},nd=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+e)},r.readAsDataURL(e)};for(var od="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ad="undefined"==typeof Uint8Array?[]:new Uint8Array(256),cd=0;cd<od.length;cd++)ad[od.charCodeAt(cd)]=cd;const dd="function"==typeof ArrayBuffer,ld=(e,t)=>{if("string"!=typeof e)return{type:"message",data:ud(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:pd(e.substring(1),t)};return ed[r]?e.length>1?{type:ed[r],data:e.substring(1)}:{type:ed[r]}:td},pd=(e,t)=>{if(dd){const r=function(e){var t,r,i,s,n,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);var d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=ad[e.charCodeAt(t)],i=ad[e.charCodeAt(t+1)],s=ad[e.charCodeAt(t+2)],n=ad[e.charCodeAt(t+3)],l[c++]=r<<2|i>>4,l[c++]=(15&i)<<4|s>>2,l[c++]=(3&s)<<6|63&n;return d}(e);return ud(r,t)}return{base64:!0,data:e}},ud=(e,t)=>"blob"===t&&e instanceof ArrayBuffer?new Blob([e]):e,hd=String.fromCharCode(30);class fd extends Xc{constructor(e){super(),this.writable=!1,Qc(this,e),this.opts=e,this.query=e.query,this.readyState="",this.socket=e.socket}onError(e,t){const r=new Error(e);return r.type="TransportError",r.description=t,super.emit("error",r),this}open(){return"closed"!==this.readyState&&""!==this.readyState||(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.emit("open")}onData(e){const t=ld(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emit("packet",e)}onClose(){this.readyState="closed",super.emit("close")}}var md,gd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),vd={},yd=0,bd=0;function wd(e){var t="";do{t=gd[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function _d(){var e=wd(+new Date);return e!==md?(yd=0,md=e):e+"."+wd(yd++)}for(;bd<64;bd++)vd[gd[bd]]=bd;_d.encode=wd,_d.decode=function(e){var t=0;for(bd=0;bd<e.length;bd++)t=64*t+vd[e.charAt(bd)];return t};var Sd=_d,kd={encode:function(e){var t="";for(var r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t},decode:function(e){for(var t={},r=e.split("&"),i=0,s=r.length;i<s;i++){var n=r[i].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}};class Rd extends fd{constructor(){super(...arguments),this.polling=!1}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.emit("poll")}onData(e){((e,t)=>{const r=e.split(hd),i=[];for(let e=0;e<r.length;e++){const s=ld(r[e],t);if(i.push(s),"error"===s.type)break}return i})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose(),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("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,i=new Array(r);let s=0;e.forEach(((e,n)=>{sd(e,!1,(e=>{i[n]=e,++s===r&&t(i.join(hd))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emit("drain")}))}))}uri(){let e=this.query||{};const t=this.opts.secure?"https":"http";let r="";!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=Sd()),this.supportsBinary||e.sid||(e.b64=1),this.opts.port&&("https"===t&&443!==Number(this.opts.port)||"http"===t&&80!==Number(this.opts.port))&&(r=":"+this.opts.port);const i=kd.encode(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(i.length?"?"+i:"")}}function Cd(){}const Pd=null!=new Gc({xdomain:!1}).responseType;class Td extends Xc{constructor(e,t){super(),Qc(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.create()}create(){const e=Hc(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;const t=this.xhr=new Gc(e);try{t.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&t.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{t.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in t&&(t.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(t.timeout=this.opts.requestTimeout),t.onreadystatechange=()=>{4===t.readyState&&(200===t.status||1223===t.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof t.status?t.status:0)}),0))},t.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=Td.requestsCount++,Td.requests[this.index]=this)}onSuccess(){this.emit("success"),this.cleanup()}onData(e){this.emit("data",e),this.onSuccess()}onError(e){this.emit("error",e),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Cd,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Td.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&this.onData(e)}abort(){this.cleanup()}}if(Td.requestsCount=0,Td.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Ed);else if("function"==typeof addEventListener){addEventListener("onpagehide"in $c?"pagehide":"unload",Ed,!1)}function Ed(){for(let e in Td.requests)Td.requests.hasOwnProperty(e)&&Td.requests[e].abort()}const Dd="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),xd=$c.WebSocket||$c.MozWebSocket,Md="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Ld extends fd{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=Md?{}:Hc(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=Md?new xd(e,t,r):t?new xd(e,t):new xd(e)}catch(e){return this.emit("error",e)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=this.onClose.bind(this),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],i=t===e.length-1;sd(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}i&&Dd((()=>{this.writable=!0,this.emit("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let e=this.query||{};const t=this.opts.secure?"wss":"ws";let r="";this.opts.port&&("wss"===t&&443!==Number(this.opts.port)||"ws"===t&&80!==Number(this.opts.port))&&(r=":"+this.opts.port),this.opts.timestampRequests&&(e[this.opts.timestampParam]=Sd()),this.supportsBinary||(e.b64=1);const i=kd.encode(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(i.length?"?"+i:"")}check(){return!(!xd||"__initialize"in xd&&this.name===Ld.prototype.name)}}const Od={websocket:Ld,polling:class extends Rd{constructor(e){if(super(e),"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,this.xs=e.secure!==t}const t=e&&e.forceBase64;this.supportsBinary=Pd&&!t}request(e={}){return Object.assign(e,{xd:this.xd,xs:this.xs},this.opts),new Td(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e=>{this.onError("xhr post error",e)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e=>{this.onError("xhr poll error",e)})),this.pollXhr=e}}};class Id extends Xc{constructor(e,t={}){super(),e&&"object"==typeof e&&(t=e,e=null),e?(e=Wc(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=Wc(t.host).host),Qc(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"],this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},t),this.opts.path=this.opts.path.replace(/\/$/,"")+"/","string"==typeof this.opts.query&&(this.opts.query=kd.decode(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&addEventListener("beforeunload",(()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())}),!1),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close")},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=function(e){const t={};for(let r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}(this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new Od[e](r)}open(){let e;if(this.opts.rememberUpgrade&&Id.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",(()=>{this.onClose("transport close")}))}probe(e){let t=this.createTransport(e),r=!1;Id.priorWebsocketSuccess=!1;const i=()=>{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;Id.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 s(){r||(r=!0,d(),t.close(),t=null)}const n=e=>{const r=new Error("probe error: "+e);r.transport=t.name,s(),this.emitReserved("upgradeError",r)};function o(){n("transport closed")}function a(){n("socket closed")}function c(e){t&&e.name!==t.name&&s()}const d=()=>{t.removeListener("open",i),t.removeListener("error",n),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",n),t.once("close",o),this.once("close",a),this.once("upgrading",c),t.open()}onOpen(){if(this.readyState="open",Id.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause){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"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.resetPingTimeout(),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.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(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emitReserved("flush"))}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,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const s={type:e,data:t,options:r};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),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){Id.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("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 i=e.length;for(;r<i;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}Id.protocol=4,Id.protocol;const Ad="function"==typeof ArrayBuffer,jd=Object.prototype.toString,Fd="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===jd.call(Blob),Nd="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===jd.call(File);function Bd(e){return Ad&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Fd&&e instanceof Blob||Nd&&e instanceof File}function Ud(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Ud(e[t]))return!0;return!1}if(Bd(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Ud(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ud(e[t]))return!0;return!1}function qd(e){const t=[],r=e.data,i=e;return i.data=Wd(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Wd(e,t){if(!e)return e;if(Bd(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 i=0;i<e.length;i++)r[i]=Wd(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)e.hasOwnProperty(i)&&(r[i]=Wd(e[i],t));return r}return e}function Vd(e,t){return e.data=zd(e.data,t),e.attachments=void 0,e}function zd(e,t){if(!e)return e;if(e&&e._placeholder)return t[e.num];if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=zd(e[r],t);else if("object"==typeof e)for(const r in e)e.hasOwnProperty(r)&&(e[r]=zd(e[r],t));return e}var $d;!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"}($d||($d={}));class Gd extends Xc{constructor(){super()}add(e){let t;if("string"==typeof e)t=this.decodeString(e),t.type===$d.BINARY_EVENT||t.type===$d.BINARY_ACK?(this.reconstructor=new Hd(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t);else{if(!Bd(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===$d[r.type])throw new Error("unknown packet type "+r.type);if(r.type===$d.BINARY_EVENT||r.type===$d.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(i,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(s)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=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(i,t+1))}if(e.charAt(++t)){const i=function(e){try{return JSON.parse(e)}catch(e){return!1}}(e.substr(t));if(!Gd.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}static isPayloadValid(e,t){switch(e){case $d.CONNECT:return"object"==typeof t;case $d.DISCONNECT:return void 0===t;case $d.CONNECT_ERROR:return"string"==typeof t||"object"==typeof t;case $d.EVENT:case $d.BINARY_EVENT:return Array.isArray(t)&&t.length>0;case $d.ACK:case $d.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&this.reconstructor.finishedReconstruction()}}class Hd{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=Vd(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Jd=Object.freeze({__proto__:null,protocol:5,get PacketType(){return $d},Encoder:class{encode(e){return e.type!==$d.EVENT&&e.type!==$d.ACK||!Ud(e)?[this.encodeAsString(e)]:(e.type=e.type===$d.EVENT?$d.BINARY_EVENT:$d.BINARY_ACK,this.encodeAsBinary(e))}encodeAsString(e){let t=""+e.type;return e.type!==$d.BINARY_EVENT&&e.type!==$d.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)),t}encodeAsBinary(e){const t=qd(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},Decoder:Gd});function Kd(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Qd=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Xd extends Xc{constructor(e,t,r){super(),this.connected=!1,this.disconnected=!0,this.receiveBuffer=[],this.sendBuffer=[],this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this.io._autoConnect&&this.open()}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Kd(e,"open",this.onopen.bind(this)),Kd(e,"packet",this.onpacket.bind(this)),Kd(e,"error",this.onerror.bind(this)),Kd(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(Qd.hasOwnProperty(e))throw new Error('"'+e+'" is a reserved event name');t.unshift(e);const r={type:$d.EVENT,data:t,options:{}};r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]&&(this.acks[this.ids]=t.pop(),r.id=this.ids++);const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?this.packet(r):this.sendBuffer.push(r)),this.flags={},this}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this.packet({type:$d.CONNECT,data:e})})):this.packet({type:$d.CONNECT,data:this.auth})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e){this.connected=!1,this.disconnected=!0,delete this.id,this.emitReserved("disconnect",e)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case $d.CONNECT:if(e.data&&e.data.sid){const t=e.data.sid;this.onconnect(t)}else 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 $d.EVENT:case $d.BINARY_EVENT:this.onevent(e);break;case $d.ACK:case $d.BINARY_ACK:this.onack(e);break;case $d.DISCONNECT:this.ondisconnect();break;case $d.CONNECT_ERROR: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)}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:$d.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e){this.id=e,this.connected=!0,this.disconnected=!1,this.emitBuffered(),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((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:$d.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}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||[]}}var Yd=Zd;function Zd(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}Zd.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)},Zd.prototype.reset=function(){this.attempts=0},Zd.prototype.setMin=function(e){this.ms=e},Zd.prototype.setMax=function(e){this.max=e},Zd.prototype.setJitter=function(e){this.jitter=e};class el extends Xc{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,Qc(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 Yd({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Jd;this.encoder=new i.Encoder,this.decoder=new i.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 Id(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=Kd(t,"open",(function(){r.onopen(),e&&e()})),s=Kd(t,"error",(t=>{r.cleanup(),r._readyState="closed",this.emitReserved("error",t),e?e(t):r.maybeReconnectOnOpen()}));if(!1!==this._timeout){const e=this._timeout;0===e&&i();const r=this.setTimeoutFn((()=>{i(),t.close(),t.emit("error",new Error("timeout"))}),e);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}return this.subs.push(i),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(Kd(e,"ping",this.onping.bind(this)),Kd(e,"data",this.ondata.bind(this)),Kd(e,"error",this.onerror.bind(this)),Kd(e,"close",this.onclose.bind(this)),Kd(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){this.decoder.add(e)}ondecoded(e){this.emitReserved("packet",e)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r||(r=new Xd(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,"opening"===this._readyState&&this.cleanup(),this.backoff.reset(),this._readyState="closed",this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e),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((function(){clearTimeout(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const tl={};function rl(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=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),i=Wc(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const s=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+s+":"+i.port+t,i.href=i.protocol+"://"+s+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,s=r.id,n=r.path,o=tl[s]&&n in tl[s].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new el(i,t):(tl[s]||(tl[s]=new el(i,t)),a=tl[s]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}class il{constructor(e){this.reconnectingAttempt=0,this.isConnected=!1,this._observer=new n,this.knownDisconnectReasonsCodes={"io server disconnect":"server.disconnect","io client disconnect":"client.disconnect","ping timeout":"ping.timeout","transport close":"transport.close","transport error":"transport.error"},this.logger=new Be({namespace:"Socket",logLevel:e.logLevel,onLogMessage:e.onLogMessage})}get observer(){return this._observer}get id(){var e;return null===(e=this.connection)||void 0===e?void 0:e.id}connect(e){const t=rl(e,{transports:["polling","websocket"],upgrade:!0,rememberUpgrade:!1});this.connection=t,this.serverUrl=e,t.on("connect",(()=>{const e=this.reconnectingAttempt?Y.Reconnected:Y.Connected;this.isConnected=!0,this.setReconnectingAttempt(0),this.logger.debug("connection.on(`connect`)",{connectionId:t.id}),this.observer.safeEmit("state",{state:e})})),t.on("connect_error",(e=>{this.connectionError=e,this.logger.error("connection.on(`connect_error`)",{error:e}),this.observer.safeEmit("state",{state:Y.Error,error:e})})),t.on("disconnect",(e=>{this.isConnected=!1,this.setReconnectingAttempt(0),this.disconnectReason=e,this.logger.warn("connection.on(`disconnect`)",{reason:e}),this.observer.safeEmit("state",{state:Y.Disconnected,code:this.getDisconnectReasonCode(e)})})),t.io.on("reconnect_attempt",(e=>{this.setReconnectingAttempt(e),this.logger.warn("connection.on(`reconnect_attempt`)",{attempt:e}),this.observer.safeEmit("state",{state:Y.Reconnecting})})),t.io.on("reconnect",(()=>{this.logger.debug("connection.on(`reconnect`)",{connectionId:t.id}),this.observer.safeEmit("state",{state:Y.Reconnect})}))}disconnect(){this.connection&&(this.connection.offAny(),this.connection.volatile.offAny(),this.connection.disconnect(),this.setReconnectingAttempt(0))}request(e,t={}){return new Promise(((r,i)=>{if(!this.connection)return this.logger.error("request()",{type:e,data:t}),void i(new Error("Socket request: Socket connection is not initialized"));this.connection.emit(e,t,(s=>{s.error?(this.logger.error("request()",{event:e,payload:t,response:s}),i(s.error)):r(s)}))}))}getDisconnectReasonCode(e){const t=String(e).toLowerCase();return this.knownDisconnectReasonsCodes[t]||t}setReconnectingAttempt(e){this.reconnectingAttempt=e}}var sl={exports:{}},nl=function(e,t){return function(){for(var r=new Array(arguments.length),i=0;i<r.length;i++)r[i]=arguments[i];return e.apply(t,r)}},ol=nl,al=Object.prototype.toString;function cl(e){return"[object Array]"===al.call(e)}function dl(e){return void 0===e}function ll(e){return null!==e&&"object"==typeof e}function pl(e){if("[object Object]"!==al.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function ul(e){return"[object Function]"===al.call(e)}function hl(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),cl(e))for(var r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.call(null,e[s],s,e)}var fl={isArray:cl,isArrayBuffer:function(e){return"[object ArrayBuffer]"===al.call(e)},isBuffer:function(e){return null!==e&&!dl(e)&&null!==e.constructor&&!dl(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:ll,isPlainObject:pl,isUndefined:dl,isDate:function(e){return"[object Date]"===al.call(e)},isFile:function(e){return"[object File]"===al.call(e)},isBlob:function(e){return"[object Blob]"===al.call(e)},isFunction:ul,isStream:function(e){return ll(e)&&ul(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:hl,merge:function e(){var t={};function r(r,i){pl(t[i])&&pl(r)?t[i]=e(t[i],r):pl(r)?t[i]=e({},r):cl(r)?t[i]=r.slice():t[i]=r}for(var i=0,s=arguments.length;i<s;i++)hl(arguments[i],r);return t},extend:function(e,t,r){return hl(t,(function(t,i){e[i]=r&&"function"==typeof t?ol(t,r):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e}},ml=fl;function gl(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var vl=function(e,t,r){if(!t)return e;var i;if(r)i=r(t);else if(ml.isURLSearchParams(t))i=t.toString();else{var s=[];ml.forEach(t,(function(e,t){null!=e&&(ml.isArray(e)?t+="[]":e=[e],ml.forEach(e,(function(e){ml.isDate(e)?e=e.toISOString():ml.isObject(e)&&(e=JSON.stringify(e)),s.push(gl(t)+"="+gl(e))})))})),i=s.join("&")}if(i){var n=e.indexOf("#");-1!==n&&(e=e.slice(0,n)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e},yl=fl;function bl(){this.handlers=[]}bl.prototype.use=function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1},bl.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},bl.prototype.forEach=function(e){yl.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var wl=bl,_l=fl,Sl=function(e,t,r,i,s){return e.config=t,r&&(e.code=r),e.request=i,e.response=s,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},e},kl=Sl,Rl=function(e,t,r,i,s){var n=new Error(e);return kl(n,t,r,i,s)},Cl=Rl,Pl=fl,Tl=Pl.isStandardBrowserEnv()?{write:function(e,t,r,i,s,n){var o=[];o.push(e+"="+encodeURIComponent(t)),Pl.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Pl.isString(i)&&o.push("path="+i),Pl.isString(s)&&o.push("domain="+s),!0===n&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},El=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)},Dl=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},xl=fl,Ml=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"],Ll=fl,Ol=Ll.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function i(e){var i=e;return t&&(r.setAttribute("href",i),i=r.href),r.setAttribute("href",i),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=i(window.location.href),function(t){var r=Ll.isString(t)?i(t):t;return r.protocol===e.protocol&&r.host===e.host}}():function(){return!0},Il=fl,Al=function(e,t,r){var i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(Cl("Request failed with status code "+r.status,r.config,null,r.request,r)):e(r)},jl=Tl,Fl=vl,Nl=function(e,t){return e&&!El(t)?Dl(e,t):t},Bl=function(e){var t,r,i,s={};return e?(xl.forEach(e.split("\n"),(function(e){if(i=e.indexOf(":"),t=xl.trim(e.substr(0,i)).toLowerCase(),r=xl.trim(e.substr(i+1)),t){if(s[t]&&Ml.indexOf(t)>=0)return;s[t]="set-cookie"===t?(s[t]?s[t]:[]).concat([r]):s[t]?s[t]+", "+r:r}})),s):s},Ul=Ol,ql=Rl,Wl=function(e){return new Promise((function(t,r){var i=e.data,s=e.headers,n=e.responseType;Il.isFormData(i)&&delete s["Content-Type"];var o=new XMLHttpRequest;if(e.auth){var a=e.auth.username||"",c=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";s.Authorization="Basic "+btoa(a+":"+c)}var d=Nl(e.baseURL,e.url);function l(){if(o){var i="getAllResponseHeaders"in o?Bl(o.getAllResponseHeaders()):null,s={data:n&&"text"!==n&&"json"!==n?o.response:o.responseText,status:o.status,statusText:o.statusText,headers:i,config:e,request:o};Al(t,r,s),o=null}}if(o.open(e.method.toUpperCase(),Fl(d,e.params,e.paramsSerializer),!0),o.timeout=e.timeout,"onloadend"in o?o.onloadend=l:o.onreadystatechange=function(){o&&4===o.readyState&&(0!==o.status||o.responseURL&&0===o.responseURL.indexOf("file:"))&&setTimeout(l)},o.onabort=function(){o&&(r(ql("Request aborted",e,"ECONNABORTED",o)),o=null)},o.onerror=function(){r(ql("Network Error",e,null,o)),o=null},o.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(ql(t,e,e.transitional&&e.transitional.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",o)),o=null},Il.isStandardBrowserEnv()){var p=(e.withCredentials||Ul(d))&&e.xsrfCookieName?jl.read(e.xsrfCookieName):void 0;p&&(s[e.xsrfHeaderName]=p)}"setRequestHeader"in o&&Il.forEach(s,(function(e,t){void 0===i&&"content-type"===t.toLowerCase()?delete s[t]:o.setRequestHeader(t,e)})),Il.isUndefined(e.withCredentials)||(o.withCredentials=!!e.withCredentials),n&&"json"!==n&&(o.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&o.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&o.upload&&o.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){o&&(o.abort(),r(e),o=null)})),i||(i=null),o.send(i)}))},Vl=fl,zl=function(e,t){_l.forEach(e,(function(r,i){i!==t&&i.toUpperCase()===t.toUpperCase()&&(e[t]=r,delete e[i])}))},$l=Sl,Gl={"Content-Type":"application/x-www-form-urlencoded"};function Hl(e,t){!Vl.isUndefined(e)&&Vl.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var Jl,Kl={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(Jl=Wl),Jl),transformRequest:[function(e,t){return zl(t,"Accept"),zl(t,"Content-Type"),Vl.isFormData(e)||Vl.isArrayBuffer(e)||Vl.isBuffer(e)||Vl.isStream(e)||Vl.isFile(e)||Vl.isBlob(e)?e:Vl.isArrayBufferView(e)?e.buffer:Vl.isURLSearchParams(e)?(Hl(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):Vl.isObject(e)||t&&"application/json"===t["Content-Type"]?(Hl(t,"application/json"),function(e,t,r){if(Vl.isString(e))try{return(t||JSON.parse)(e),Vl.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional,r=t&&t.silentJSONParsing,i=t&&t.forcedJSONParsing,s=!r&&"json"===this.responseType;if(s||i&&Vl.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(s){if("SyntaxError"===e.name)throw $l(e,this,"E_JSON_PARSE");throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300}};Kl.headers={common:{Accept:"application/json, text/plain, */*"}},Vl.forEach(["delete","get","head"],(function(e){Kl.headers[e]={}})),Vl.forEach(["post","put","patch"],(function(e){Kl.headers[e]=Vl.merge(Gl)}));var Ql=Kl,Xl=fl,Yl=Ql,Zl=function(e){return!(!e||!e.__CANCEL__)},ep=fl,tp=function(e,t,r){var i=this||Yl;return Xl.forEach(r,(function(r){e=r.call(i,e,t)})),e},rp=Zl,ip=Ql;function sp(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var np=fl,op=function(e,t){t=t||{};var r={},i=["url","method","data"],s=["headers","auth","proxy","params"],n=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],o=["validateStatus"];function a(e,t){return np.isPlainObject(e)&&np.isPlainObject(t)?np.merge(e,t):np.isPlainObject(t)?np.merge({},t):np.isArray(t)?t.slice():t}function c(i){np.isUndefined(t[i])?np.isUndefined(e[i])||(r[i]=a(void 0,e[i])):r[i]=a(e[i],t[i])}np.forEach(i,(function(e){np.isUndefined(t[e])||(r[e]=a(void 0,t[e]))})),np.forEach(s,c),np.forEach(n,(function(i){np.isUndefined(t[i])?np.isUndefined(e[i])||(r[i]=a(void 0,e[i])):r[i]=a(void 0,t[i])})),np.forEach(o,(function(i){i in t?r[i]=a(e[i],t[i]):i in e&&(r[i]=a(void 0,e[i]))}));var d=i.concat(s).concat(n).concat(o),l=Object.keys(e).concat(Object.keys(t)).filter((function(e){return-1===d.indexOf(e)}));return np.forEach(l,c),r},ap={name:"axios",version:"0.21.4",description:"Promise based HTTP client for the browser and node.js",main:"index.js",scripts:{test:"grunt test",start:"node ./sandbox/server.js",build:"NODE_ENV=production grunt build",preversion:"npm test",version:"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json",postversion:"git push && git push --tags",examples:"node ./examples/server.js",coveralls:"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",fix:"eslint --fix lib/**/*.js"},repository:{type:"git",url:"https://github.com/axios/axios.git"},keywords:["xhr","http","ajax","promise","node"],author:"Matt Zabriskie",license:"MIT",bugs:{url:"https://github.com/axios/axios/issues"},homepage:"https://axios-http.com",devDependencies:{coveralls:"^3.0.0","es6-promise":"^4.2.4",grunt:"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1",karma:"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2",minimist:"^1.2.0",mocha:"^8.2.1",sinon:"^4.5.0","terser-webpack-plugin":"^4.2.3",typescript:"^4.0.5","url-search-params":"^0.10.0",webpack:"^4.44.2","webpack-dev-server":"^3.11.0"},browser:{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},jsdelivr:"dist/axios.min.js",unpkg:"dist/axios.min.js",typings:"./index.d.ts",dependencies:{"follow-redirects":"^1.14.0"},bundlesize:[{path:"./dist/axios.min.js",threshold:"5kB"}]},cp={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){cp[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));var dp={},lp=ap.version.split(".");function pp(e,t){for(var r=t?t.split("."):lp,i=e.split("."),s=0;s<3;s++){if(r[s]>i[s])return!0;if(r[s]<i[s])return!1}return!1}cp.transitional=function(e,t,r){var i=t&&pp(t);function s(e,t){return"[Axios v"+ap.version+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,n,o){if(!1===e)throw new Error(s(n," has been removed in "+t));return i&&!dp[n]&&(dp[n]=!0,console.warn(s(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,o)}};var up={isOlderVersion:pp,assertOptions:function(e,t,r){if("object"!=typeof e)throw new TypeError("options must be an object");for(var i=Object.keys(e),s=i.length;s-- >0;){var n=i[s],o=t[n];if(o){var a=e[n],c=void 0===a||o(a,n,e);if(!0!==c)throw new TypeError("option "+n+" must be "+c)}else if(!0!==r)throw Error("Unknown option "+n)}},validators:cp},hp=fl,fp=vl,mp=wl,gp=function(e){return sp(e),e.headers=e.headers||{},e.data=tp.call(e,e.data,e.headers,e.transformRequest),e.headers=ep.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),ep.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||ip.adapter)(e).then((function(t){return sp(e),t.data=tp.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return rp(t)||(sp(e),t&&t.response&&(t.response.data=tp.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},vp=op,yp=up,bp=yp.validators;function wp(e){this.defaults=e,this.interceptors={request:new mp,response:new mp}}wp.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=vp(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=e.transitional;void 0!==t&&yp.assertOptions(t,{silentJSONParsing:bp.transitional(bp.boolean,"1.0.0"),forcedJSONParsing:bp.transitional(bp.boolean,"1.0.0"),clarifyTimeoutError:bp.transitional(bp.boolean,"1.0.0")},!1);var r=[],i=!0;this.interceptors.request.forEach((function(t){"function"==typeof t.runWhen&&!1===t.runWhen(e)||(i=i&&t.synchronous,r.unshift(t.fulfilled,t.rejected))}));var s,n=[];if(this.interceptors.response.forEach((function(e){n.push(e.fulfilled,e.rejected)})),!i){var o=[gp,void 0];for(Array.prototype.unshift.apply(o,r),o=o.concat(n),s=Promise.resolve(e);o.length;)s=s.then(o.shift(),o.shift());return s}for(var a=e;r.length;){var c=r.shift(),d=r.shift();try{a=c(a)}catch(e){d(e);break}}try{s=gp(a)}catch(e){return Promise.reject(e)}for(;n.length;)s=s.then(n.shift(),n.shift());return s},wp.prototype.getUri=function(e){return e=vp(this.defaults,e),fp(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},hp.forEach(["delete","get","head","options"],(function(e){wp.prototype[e]=function(t,r){return this.request(vp(r||{},{method:e,url:t,data:(r||{}).data}))}})),hp.forEach(["post","put","patch"],(function(e){wp.prototype[e]=function(t,r,i){return this.request(vp(i||{},{method:e,url:t,data:r}))}}));var _p=wp;function Sp(e){this.message=e}Sp.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},Sp.prototype.__CANCEL__=!0;var kp=Sp,Rp=kp;function Cp(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var r=this;e((function(e){r.reason||(r.reason=new Rp(e),t(r.reason))}))}Cp.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},Cp.source=function(){var e,t=new Cp((function(t){e=t}));return{token:t,cancel:e}};var Pp=Cp,Tp=fl,Ep=nl,Dp=_p,xp=op;function Mp(e){var t=new Dp(e),r=Ep(Dp.prototype.request,t);return Tp.extend(r,Dp.prototype,t),Tp.extend(r,t),r}var Lp=Mp(Ql);Lp.Axios=Dp,Lp.create=function(e){return Mp(xp(Lp.defaults,e))},Lp.Cancel=kp,Lp.CancelToken=Pp,Lp.isCancel=Zl,Lp.all=function(e){return Promise.all(e)},Lp.spread=function(e){return function(t){return e.apply(null,t)}},Lp.isAxiosError=function(e){return"object"==typeof e&&!0===e.isAxiosError},sl.exports=Lp,sl.exports.default=Lp;var Op=sl.exports,Ip="undefined"!=typeof Symbol&&Symbol,Ap=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var s=Object.getOwnPropertyDescriptor(e,t);if(42!==s.value||!0!==s.enumerable)return!1}return!0},jp="Function.prototype.bind called on incompatible ",Fp=Array.prototype.slice,Np=Object.prototype.toString,Bp=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==Np.call(t))throw new TypeError(jp+t);for(var r,i=Fp.call(arguments,1),s=function(){if(this instanceof r){var s=t.apply(this,i.concat(Fp.call(arguments)));return Object(s)===s?s:this}return t.apply(e,i.concat(Fp.call(arguments)))},n=Math.max(0,t.length-i.length),o=[],a=0;a<n;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(s),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},Up=Function.prototype.bind||Bp,qp=Up.call(Function.call,Object.prototype.hasOwnProperty),Wp=SyntaxError,Vp=Function,zp=TypeError,$p=function(e){try{return Vp('"use strict"; return ('+e+").constructor;")()}catch(e){}},Gp=Object.getOwnPropertyDescriptor;if(Gp)try{Gp({},"")}catch(sc){Gp=null}var Hp=function(){throw new zp},Jp=Gp?function(){try{return Hp}catch(e){try{return Gp(arguments,"callee").get}catch(e){return Hp}}}():Hp,Kp="function"==typeof Ip&&"function"==typeof Symbol&&"symbol"==typeof Ip("foo")&&"symbol"==typeof Symbol("bar")&&Ap(),Qp=Object.getPrototypeOf||function(e){return e.__proto__},Xp={},Yp="undefined"==typeof Uint8Array?undefined:Qp(Uint8Array),Zp={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":Kp?Qp([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":Xp,"%AsyncGenerator%":Xp,"%AsyncGeneratorFunction%":Xp,"%AsyncIteratorPrototype%":Xp,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":Vp,"%GeneratorFunction%":Xp,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Kp?Qp(Qp([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&Kp?Qp((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&Kp?Qp((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Kp?Qp(""[Symbol.iterator]()):undefined,"%Symbol%":Kp?Symbol:undefined,"%SyntaxError%":Wp,"%ThrowTypeError%":Jp,"%TypedArray%":Yp,"%TypeError%":zp,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet},eu=function e(t){var r;if("%AsyncFunction%"===t)r=$p("async function () {}");else if("%GeneratorFunction%"===t)r=$p("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=$p("async function* () {}");else if("%AsyncGenerator%"===t){var i=e("%AsyncGeneratorFunction%");i&&(r=i.prototype)}else if("%AsyncIteratorPrototype%"===t){var s=e("%AsyncGenerator%");s&&(r=Qp(s.prototype))}return Zp[t]=r,r},tu={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},ru=Up,iu=qp,su=ru.call(Function.call,Array.prototype.concat),nu=ru.call(Function.apply,Array.prototype.splice),ou=ru.call(Function.call,String.prototype.replace),au=ru.call(Function.call,String.prototype.slice),cu=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,du=/\\(\\)?/g,lu=function(e){var t=au(e,0,1),r=au(e,-1);if("%"===t&&"%"!==r)throw new Wp("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new Wp("invalid intrinsic syntax, expected opening `%`");var i=[];return ou(e,cu,(function(e,t,r,s){i[i.length]=r?ou(s,du,"$1"):t||e})),i},pu=function(e,t){var r,i=e;if(iu(tu,i)&&(i="%"+(r=tu[i])[0]+"%"),iu(Zp,i)){var s=Zp[i];if(s===Xp&&(s=eu(i)),void 0===s&&!t)throw new zp("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:i,value:s}}throw new Wp("intrinsic "+e+" does not exist!")},uu=function(e,t){if("string"!=typeof e||0===e.length)throw new zp("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new zp('"allowMissing" argument must be a boolean');var r=lu(e),i=r.length>0?r[0]:"",s=pu("%"+i+"%",t),n=s.name,o=s.value,a=!1,c=s.alias;c&&(i=c[0],nu(r,su([0,1],c)));for(var d=1,l=!0;d<r.length;d+=1){var p=r[d],u=au(p,0,1),h=au(p,-1);if(('"'===u||"'"===u||"`"===u||'"'===h||"'"===h||"`"===h)&&u!==h)throw new Wp("property names with quotes must have matching quotes");if("constructor"!==p&&l||(a=!0),iu(Zp,n="%"+(i+="."+p)+"%"))o=Zp[n];else if(null!=o){if(!(p in o)){if(!t)throw new zp("base intrinsic for "+e+" exists, but the property is not available.");return}if(Gp&&d+1>=r.length){var f=Gp(o,p);o=(l=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:o[p]}else l=iu(o,p),o=o[p];l&&!a&&(Zp[n]=o)}}return o},hu={exports:{}};!function(e){var t=Up,r=uu,i=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),n=r("%Reflect.apply%",!0)||t.call(s,i),o=r("%Object.getOwnPropertyDescriptor%",!0),a=r("%Object.defineProperty%",!0),c=r("%Math.max%");if(a)try{a({},"a",{value:1})}catch(e){a=null}e.exports=function(e){var r=n(t,s,arguments);if(o&&a){var i=o(r,"length");i.configurable&&a(r,"length",{value:1+c(0,e.length-(arguments.length-1))})}return r};var d=function(){return n(t,i,arguments)};a?a(e.exports,"apply",{value:d}):e.exports.apply=d}(hu);var fu=uu,mu=hu.exports,gu=mu(fu("String.prototype.indexOf")),vu=c(Object.freeze({__proto__:null,default:{}})),yu="function"==typeof Map&&Map.prototype,bu=Object.getOwnPropertyDescriptor&&yu?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,wu=yu&&bu&&"function"==typeof bu.get?bu.get:null,_u=yu&&Map.prototype.forEach,Su="function"==typeof Set&&Set.prototype,ku=Object.getOwnPropertyDescriptor&&Su?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,Ru=Su&&ku&&"function"==typeof ku.get?ku.get:null,Cu=Su&&Set.prototype.forEach,Pu="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,Tu="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,Eu="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,Du=Boolean.prototype.valueOf,xu=Object.prototype.toString,Mu=Function.prototype.toString,Lu=String.prototype.match,Ou="function"==typeof BigInt?BigInt.prototype.valueOf:null,Iu=Object.getOwnPropertySymbols,Au="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,ju="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Fu=Object.prototype.propertyIsEnumerable,Nu=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),Bu=vu.custom,Uu=Bu&&$u(Bu)?Bu:null,qu="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function Wu(e,t,r){var i="double"===(r.quoteStyle||t)?'"':"'";return i+e+i}function Vu(e){return String(e).replace(/"/g,"&quot;")}function zu(e){return!("[object Array]"!==Ju(e)||qu&&"object"==typeof e&&qu in e)}function $u(e){if(ju)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Au)return!1;try{return Au.call(e),!0}catch(e){}return!1}var Gu=Object.prototype.hasOwnProperty||function(e){return e in this};function Hu(e,t){return Gu.call(e,t)}function Ju(e){return xu.call(e)}function Ku(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,i=e.length;r<i;r++)if(e[r]===t)return r;return-1}function Qu(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,i="... "+r+" more character"+(r>1?"s":"");return Qu(e.slice(0,t.maxStringLength),t)+i}return Wu(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,Xu),"single",t)}function Xu(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+t.toString(16).toUpperCase()}function Yu(e){return"Object("+e+")"}function Zu(e){return e+" { ? }"}function eh(e,t,r,i){return e+" ("+t+") {"+(i?th(r,i):r.join(", "))+"}"}function th(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function rh(e,t){var r=zu(e),i=[];if(r){i.length=e.length;for(var s=0;s<e.length;s++)i[s]=Hu(e,s)?t(e[s],e):""}var n,o="function"==typeof Iu?Iu(e):[];if(ju){n={};for(var a=0;a<o.length;a++)n["$"+o[a]]=o[a]}for(var c in e)Hu(e,c)&&(r&&String(Number(c))===c&&c<e.length||ju&&n["$"+c]instanceof Symbol||(/[^\w$]/.test(c)?i.push(t(c,e)+": "+t(e[c],e)):i.push(c+": "+t(e[c],e))));if("function"==typeof Iu)for(var d=0;d<o.length;d++)Fu.call(e,o[d])&&i.push("["+t(o[d])+"]: "+t(e[o[d]],e));return i}var ih=uu,sh=function(e,t){var r=fu(e,!!t);return"function"==typeof r&&gu(e,".prototype.")>-1?mu(r):r},nh=function e(t,r,i,s){var n=r||{};if(Hu(n,"quoteStyle")&&"single"!==n.quoteStyle&&"double"!==n.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Hu(n,"maxStringLength")&&("number"==typeof n.maxStringLength?n.maxStringLength<0&&n.maxStringLength!==1/0:null!==n.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=!Hu(n,"customInspect")||n.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Hu(n,"indent")&&null!==n.indent&&"\t"!==n.indent&&!(parseInt(n.indent,10)===n.indent&&n.indent>0))throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return Qu(t,n);if("number"==typeof t)return 0===t?1/0/t>0?"0":"-0":String(t);if("bigint"==typeof t)return String(t)+"n";var a=void 0===n.depth?5:n.depth;if(void 0===i&&(i=0),i>=a&&a>0&&"object"==typeof t)return zu(t)?"[Array]":"[Object]";var c=function(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=Array(e.indent+1).join(" ")}return{base:r,prev:Array(t+1).join(r)}}(n,i);if(void 0===s)s=[];else if(Ku(s,t)>=0)return"[Circular]";function d(t,r,o){if(r&&(s=s.slice()).push(r),o){var a={depth:n.depth};return Hu(n,"quoteStyle")&&(a.quoteStyle=n.quoteStyle),e(t,a,i+1,s)}return e(t,n,i+1,s)}if("function"==typeof t){var l=function(e){if(e.name)return e.name;var t=Lu.call(Mu.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),p=rh(t,d);return"[Function"+(l?": "+l:" (anonymous)")+"]"+(p.length>0?" { "+p.join(", ")+" }":"")}if($u(t)){var u=ju?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):Au.call(t);return"object"!=typeof t||ju?u:Yu(u)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var h="<"+String(t.nodeName).toLowerCase(),f=t.attributes||[],m=0;m<f.length;m++)h+=" "+f[m].name+"="+Wu(Vu(f[m].value),"double",n);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if(zu(t)){if(0===t.length)return"[]";var g=rh(t,d);return c&&!function(e){for(var t=0;t<e.length;t++)if(Ku(e[t],"\n")>=0)return!1;return!0}(g)?"["+th(g,c)+"]":"[ "+g.join(", ")+" ]"}if(function(e){return!("[object Error]"!==Ju(e)||qu&&"object"==typeof e&&qu in e)}(t)){var v=rh(t,d);return 0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+v.join(", ")+" }"}if("object"==typeof t&&o){if(Uu&&"function"==typeof t[Uu])return t[Uu]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!wu||!e||"object"!=typeof e)return!1;try{wu.call(e);try{Ru.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var y=[];return _u.call(t,(function(e,r){y.push(d(r,t,!0)+" => "+d(e,t))})),eh("Map",wu.call(t),y,c)}if(function(e){if(!Ru||!e||"object"!=typeof e)return!1;try{Ru.call(e);try{wu.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var b=[];return Cu.call(t,(function(e){b.push(d(e,t))})),eh("Set",Ru.call(t),b,c)}if(function(e){if(!Pu||!e||"object"!=typeof e)return!1;try{Pu.call(e,Pu);try{Tu.call(e,Tu)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Zu("WeakMap");if(function(e){if(!Tu||!e||"object"!=typeof e)return!1;try{Tu.call(e,Tu);try{Pu.call(e,Pu)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Zu("WeakSet");if(function(e){if(!Eu||!e||"object"!=typeof e)return!1;try{return Eu.call(e),!0}catch(e){}return!1}(t))return Zu("WeakRef");if(function(e){return!("[object Number]"!==Ju(e)||qu&&"object"==typeof e&&qu in e)}(t))return Yu(d(Number(t)));if(function(e){if(!e||"object"!=typeof e||!Ou)return!1;try{return Ou.call(e),!0}catch(e){}return!1}(t))return Yu(d(Ou.call(t)));if(function(e){return!("[object Boolean]"!==Ju(e)||qu&&"object"==typeof e&&qu in e)}(t))return Yu(Du.call(t));if(function(e){return!("[object String]"!==Ju(e)||qu&&"object"==typeof e&&qu in e)}(t))return Yu(d(String(t)));if(!function(e){return!("[object Date]"!==Ju(e)||qu&&"object"==typeof e&&qu in e)}(t)&&!function(e){return!("[object RegExp]"!==Ju(e)||qu&&"object"==typeof e&&qu in e)}(t)){var w=rh(t,d),_=Nu?Nu(t)===Object.prototype:t instanceof Object||t.constructor===Object,S=t instanceof Object?"":"null prototype",k=!_&&qu&&Object(t)===t&&qu in t?Ju(t).slice(8,-1):S?"Object":"",R=(_||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(k||S?"["+[].concat(k||[],S||[]).join(": ")+"] ":"");return 0===w.length?R+"{}":c?R+"{"+th(w,c)+"}":R+"{ "+w.join(", ")+" }"}return String(t)},oh=ih("%TypeError%"),ah=ih("%WeakMap%",!0),ch=ih("%Map%",!0),dh=sh("WeakMap.prototype.get",!0),lh=sh("WeakMap.prototype.set",!0),ph=sh("WeakMap.prototype.has",!0),uh=sh("Map.prototype.get",!0),hh=sh("Map.prototype.set",!0),fh=sh("Map.prototype.has",!0),mh=function(e,t){for(var r,i=e;null!==(r=i.next);i=r)if(r.key===t)return i.next=r.next,r.next=e.next,e.next=r,r},gh=String.prototype.replace,vh=/%20/g,yh="RFC3986",bh={default:yh,formatters:{RFC1738:function(e){return gh.call(e,vh,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:yh},wh=bh,_h=Object.prototype.hasOwnProperty,Sh=Array.isArray,kh=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),Rh=function(e,t){for(var r=t&&t.plainObjects?Object.create(null):{},i=0;i<e.length;++i)void 0!==e[i]&&(r[i]=e[i]);return r},Ch={arrayToObject:Rh,assign:function(e,t){return Object.keys(t).reduce((function(e,r){return e[r]=t[r],e}),e)},combine:function(e,t){return[].concat(e,t)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],r=[],i=0;i<t.length;++i)for(var s=t[i],n=s.obj[s.prop],o=Object.keys(n),a=0;a<o.length;++a){var c=o[a],d=n[c];"object"==typeof d&&null!==d&&-1===r.indexOf(d)&&(t.push({obj:n,prop:c}),r.push(d))}return function(e){for(;e.length>1;){var t=e.pop(),r=t.obj[t.prop];if(Sh(r)){for(var i=[],s=0;s<r.length;++s)void 0!==r[s]&&i.push(r[s]);t.obj[t.prop]=i}}}(t),e},decode:function(e,t,r){var i=e.replace(/\+/g," ");if("iso-8859-1"===r)return i.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(i)}catch(e){return i}},encode:function(e,t,r,i,s){if(0===e.length)return e;var n=e;if("symbol"==typeof e?n=Symbol.prototype.toString.call(e):"string"!=typeof e&&(n=String(e)),"iso-8859-1"===r)return escape(n).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var o="",a=0;a<n.length;++a){var c=n.charCodeAt(a);45===c||46===c||95===c||126===c||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===wh.RFC1738&&(40===c||41===c)?o+=n.charAt(a):c<128?o+=kh[c]:c<2048?o+=kh[192|c>>6]+kh[128|63&c]:c<55296||c>=57344?o+=kh[224|c>>12]+kh[128|c>>6&63]+kh[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&n.charCodeAt(a)),o+=kh[240|c>>18]+kh[128|c>>12&63]+kh[128|c>>6&63]+kh[128|63&c])}return o},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(Sh(e)){for(var r=[],i=0;i<e.length;i+=1)r.push(t(e[i]));return r}return t(e)},merge:function e(t,r,i){if(!r)return t;if("object"!=typeof r){if(Sh(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(i&&(i.plainObjects||i.allowPrototypes)||!_h.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var s=t;return Sh(t)&&!Sh(r)&&(s=Rh(t,i)),Sh(t)&&Sh(r)?(r.forEach((function(r,s){if(_h.call(t,s)){var n=t[s];n&&"object"==typeof n&&r&&"object"==typeof r?t[s]=e(n,r,i):t.push(r)}else t[s]=r})),t):Object.keys(r).reduce((function(t,s){var n=r[s];return _h.call(t,s)?t[s]=e(t[s],n,i):t[s]=n,t}),s)}},Ph=function(){var e,t,r,i={assert:function(e){if(!i.has(e))throw new oh("Side channel does not contain "+nh(e))},get:function(i){if(ah&&i&&("object"==typeof i||"function"==typeof i)){if(e)return dh(e,i)}else if(ch){if(t)return uh(t,i)}else if(r)return function(e,t){var r=mh(e,t);return r&&r.value}(r,i)},has:function(i){if(ah&&i&&("object"==typeof i||"function"==typeof i)){if(e)return ph(e,i)}else if(ch){if(t)return fh(t,i)}else if(r)return function(e,t){return!!mh(e,t)}(r,i);return!1},set:function(i,s){ah&&i&&("object"==typeof i||"function"==typeof i)?(e||(e=new ah),lh(e,i,s)):ch?(t||(t=new ch),hh(t,i,s)):(r||(r={key:{},next:null}),function(e,t,r){var i=mh(e,t);i?i.value=r:e.next={key:t,next:e.next,value:r}}(r,i,s))}};return i},Th=Ch,Eh=bh,Dh=Object.prototype.hasOwnProperty,xh={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},Mh=Array.isArray,Lh=String.prototype.split,Oh=Array.prototype.push,Ih=function(e,t){Oh.apply(e,Mh(t)?t:[t])},Ah=Date.prototype.toISOString,jh=Eh.default,Fh={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Th.encode,encodeValuesOnly:!1,format:jh,formatter:Eh.formatters[jh],indices:!1,serializeDate:function(e){return Ah.call(e)},skipNulls:!1,strictNullHandling:!1},Nh={},Bh=function e(t,r,i,s,n,o,a,c,d,l,p,u,h,f,m,g){for(var v=t,y=g,b=0,w=!1;void 0!==(y=y.get(Nh))&&!w;){var _=y.get(t);if(b+=1,void 0!==_){if(_===b)throw new RangeError("Cyclic object value");w=!0}void 0===y.get(Nh)&&(b=0)}if("function"==typeof c?v=c(r,v):v instanceof Date?v=p(v):"comma"===i&&Mh(v)&&(v=Th.maybeMap(v,(function(e){return e instanceof Date?p(e):e}))),null===v){if(n)return a&&!f?a(r,Fh.encoder,m,"key",u):r;v=""}if(function(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}(v)||Th.isBuffer(v)){if(a){var S=f?r:a(r,Fh.encoder,m,"key",u);if("comma"===i&&f){for(var k=Lh.call(String(v),","),R="",C=0;C<k.length;++C)R+=(0===C?"":",")+h(a(k[C],Fh.encoder,m,"value",u));return[h(S)+(s&&Mh(v)&&1===k.length?"[]":"")+"="+R]}return[h(S)+"="+h(a(v,Fh.encoder,m,"value",u))]}return[h(r)+"="+h(String(v))]}var P,T=[];if(void 0===v)return T;if("comma"===i&&Mh(v))P=[{value:v.length>0?v.join(",")||null:void 0}];else if(Mh(c))P=c;else{var E=Object.keys(v);P=d?E.sort(d):E}for(var D=s&&Mh(v)&&1===v.length?r+"[]":r,x=0;x<P.length;++x){var M=P[x],L="object"==typeof M&&void 0!==M.value?M.value:v[M];if(!o||null!==L){var O=Mh(v)?"function"==typeof i?i(D,M):D:D+(l?"."+M:"["+M+"]");g.set(t,b);var I=Ph();I.set(Nh,g),Ih(T,e(L,O,i,s,n,o,a,c,d,l,p,u,h,f,m,I))}}return T},Uh=Ch,qh=Object.prototype.hasOwnProperty,Wh=Array.isArray,Vh={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:Uh.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},zh=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},$h=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},Gh=function(e,t,r,i){if(e){var s=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,n=/(\[[^[\]]*])/g,o=r.depth>0&&/(\[[^[\]]*])/.exec(s),a=o?s.slice(0,o.index):s,c=[];if(a){if(!r.plainObjects&&qh.call(Object.prototype,a)&&!r.allowPrototypes)return;c.push(a)}for(var d=0;r.depth>0&&null!==(o=n.exec(s))&&d<r.depth;){if(d+=1,!r.plainObjects&&qh.call(Object.prototype,o[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(o[1])}return o&&c.push("["+s.slice(o.index)+"]"),function(e,t,r,i){for(var s=i?t:$h(t,r),n=e.length-1;n>=0;--n){var o,a=e[n];if("[]"===a&&r.parseArrays)o=[].concat(s);else{o=r.plainObjects?Object.create(null):{};var c="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,d=parseInt(c,10);r.parseArrays||""!==c?!isNaN(d)&&a!==c&&String(d)===c&&d>=0&&r.parseArrays&&d<=r.arrayLimit?(o=[])[d]=s:"__proto__"!==c&&(o[c]=s):o={0:s}}s=o}return s}(c,t,r,i)}},Hh=function(e,t){var r,i=e,s=function(e){if(!e)return Fh;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||Fh.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var r=Eh.default;if(void 0!==e.format){if(!Dh.call(Eh.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var i=Eh.formatters[r],s=Fh.filter;return("function"==typeof e.filter||Mh(e.filter))&&(s=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Fh.addQueryPrefix,allowDots:void 0===e.allowDots?Fh.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Fh.charsetSentinel,delimiter:void 0===e.delimiter?Fh.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Fh.encode,encoder:"function"==typeof e.encoder?e.encoder:Fh.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Fh.encodeValuesOnly,filter:s,format:r,formatter:i,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Fh.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Fh.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Fh.strictNullHandling}}(t);"function"==typeof s.filter?i=(0,s.filter)("",i):Mh(s.filter)&&(r=s.filter);var n,o=[];if("object"!=typeof i||null===i)return"";n=t&&t.arrayFormat in xh?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=xh[n];if(t&&"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var c="comma"===a&&t&&t.commaRoundTrip;r||(r=Object.keys(i)),s.sort&&r.sort(s.sort);for(var d=Ph(),l=0;l<r.length;++l){var p=r[l];s.skipNulls&&null===i[p]||Ih(o,Bh(i[p],p,a,c,s.strictNullHandling,s.skipNulls,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,d))}var u=o.join(s.delimiter),h=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""},Jh=function(e,t){var r=function(e){if(!e)return Vh;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?Vh.charset:e.charset;return{allowDots:void 0===e.allowDots?Vh.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:Vh.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:Vh.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:Vh.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Vh.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:Vh.comma,decoder:"function"==typeof e.decoder?e.decoder:Vh.decoder,delimiter:"string"==typeof e.delimiter||Uh.isRegExp(e.delimiter)?e.delimiter:Vh.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:Vh.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:Vh.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:Vh.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:Vh.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Vh.strictNullHandling}}(t);if(""===e||null==e)return r.plainObjects?Object.create(null):{};for(var i="string"==typeof e?function(e,t){var r,i={},s=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,n=t.parameterLimit===1/0?void 0:t.parameterLimit,o=s.split(t.delimiter,n),a=-1,c=t.charset;if(t.charsetSentinel)for(r=0;r<o.length;++r)0===o[r].indexOf("utf8=")&&("utf8=%E2%9C%93"===o[r]?c="utf-8":"utf8=%26%2310003%3B"===o[r]&&(c="iso-8859-1"),a=r,r=o.length);for(r=0;r<o.length;++r)if(r!==a){var d,l,p=o[r],u=p.indexOf("]="),h=-1===u?p.indexOf("="):u+1;-1===h?(d=t.decoder(p,Vh.decoder,c,"key"),l=t.strictNullHandling?null:""):(d=t.decoder(p.slice(0,h),Vh.decoder,c,"key"),l=Uh.maybeMap($h(p.slice(h+1),t),(function(e){return t.decoder(e,Vh.decoder,c,"value")}))),l&&t.interpretNumericEntities&&"iso-8859-1"===c&&(l=zh(l)),p.indexOf("[]=")>-1&&(l=Wh(l)?[l]:l),qh.call(i,d)?i[d]=Uh.combine(i[d],l):i[d]=l}return i}(e,r):e,s=r.plainObjects?Object.create(null):{},n=Object.keys(i),o=0;o<n.length;++o){var a=n[o],c=Gh(a,i[a],r,"string"==typeof e);s=Uh.merge(s,c,r)}return!0===r.allowSparse?s:Uh.compact(s)},Kh={formats:bh,parse:Jh,stringify:Hh};class Qh{constructor(e){const{baseURL:t,timeout:r,customNode:i}=e;this.api=Op.create({baseURL:t||"https://lb.livedigital.space/v1",timeout:r||5e3,withCredentials:!1,paramsSerializer:e=>Kh.stringify(e)}),this.customNode=i}getNode(e){return r(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 Xh{createSystem(e){return new Fc(e)}createMedia(e){return new Za(e)}createNetwork(e){const{loadbalancer:t,logLevel:r,onLogMessage:i}=e,s=new il({logLevel:r,onLogMessage:i}),n=new Qh(t);return new jc({logLevel:r,socketClient:s,loadBalancerApiClient:n,onLogMessage:i})}createChannelEventHandler(e){return new Nc(e)}createMediaSoupEventHandler(e){return new Bc(e)}createIssueDetector(e){var t,r;const i=null!==(t=e.logger)&&void 0!==t?t:console,s=new Oc({statsParser:new Ic({logger:null!==(r=e.logger)&&void 0!==r?r:console})});return new Ac({issueEmitter:new yc,networkScoresCalculator:new _c,detectors:[new Dc,new Rc,new Cc,new Pc,new Ec,new Tc,new kc,new xc],statsReporter:new bc({compositeStatsParser:s,getStatsInterval:5e3}),onIssues:e.onIssues,onNetworkScoresUpdated:e.onNetworkScoresUpdated,ignoreSSRCList:e.ignoreSSRCList,compositeStatsParser:s,logger:i})}}class Yh{constructor(e){var t,r;const{observer:i,network:s,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:c,logLevel:d,disableWid:l}=e;this._observer=null!=i?i:new n;const p=new Xh;this.engine=new rc({dependenciesFactory:p,clientEventEmitter:this.observer,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:d,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:c,disableWid:l})}get observer(){return this._observer}get id(){return this.engine.mySocketId}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}detectDevices(){return r(this,void 0,void 0,(function*(){return yield this.engine.system.detectDevices(),{video:this.engine.system.availableVideoDevices,audio:this.engine.system.availableAudioDevices}}))}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 r(this,void 0,void 0,(function*(){return this.engine.network.getTransportsStateInfo()}))}}export{Yh as default};
239
+ `,{width:c,height:d}=n,l=c/d,p=Xo(e,e.VERTEX_SHADER,o),u=Xo(e,e.FRAGMENT_SHADER,a),h=ea(e,p,u,t,r),f=e.getUniformLocation(h,"u_backgroundScale"),m=e.getUniformLocation(h,"u_backgroundOffset"),g=e.getUniformLocation(h,"u_inputFrame"),v=e.getUniformLocation(h,"u_personMask"),y=e.getUniformLocation(h,"u_background"),b=e.getUniformLocation(h,"u_coverage"),w=e.getUniformLocation(h,"u_lightWrapping"),_=e.getUniformLocation(h,"u_blendMode");e.useProgram(h),e.uniform2f(f,1,1),e.uniform2f(m,0,0),e.uniform1i(g,0),e.uniform1i(v,1),e.uniform2f(b,0,1),e.uniform1f(w,0),e.uniform1f(_,0);let S=null;function k(t){S=Yo(e,e.RGBA8,t.naturalWidth,t.naturalHeight,e.LINEAR,e.LINEAR),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.naturalWidth,t.naturalHeight,e.RGBA,e.UNSIGNED_BYTE,t);let r=0,i=0,s=t.naturalWidth,n=t.naturalHeight;s/n<l?(n=s/l,i=(t.naturalHeight-n)/2):(s=n*l,r=(t.naturalWidth-s)/2);const o=s/t.naturalWidth,a=n/t.naturalHeight;r/=t.naturalWidth,i/=t.naturalHeight,e.uniform2f(f,o,a),e.uniform2f(m,r,i)}return(null==s?void 0:s.complete)?k(s):s&&(s.onload=()=>{k(s)}),{render:function(){e.viewport(0,0,c,d),e.useProgram(h),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,i),null!==S&&(e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,S),e.uniform1i(y,2)),e.bindFramebuffer(e.FRAMEBUFFER,null),e.drawArrays(e.TRIANGLE_STRIP,0,4)},updateCoverage:function(t){e.useProgram(h),e.uniform2f(b,t[0],t[1])},updateLightWrapping:function(t){e.useProgram(h),e.uniform1f(w,t)},updateBlendMode:function(t){e.useProgram(h),e.uniform1f(_,"screen"===t?0:1)},cleanUp:function(){e.deleteTexture(S),e.deleteProgram(h),e.deleteShader(u),e.deleteShader(p)}}}(u,m,g,b,t,n);return{render:function(){return r(this,void 0,void 0,(function*(){u.activeTexture(u.TEXTURE0),u.bindTexture(u.TEXTURE_2D,v),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,u.RGBA,u.UNSIGNED_BYTE,e.htmlElement),u.bindVertexArray(f),yield w.render(),o._runInference(),_.render(),S.render(),k.render()}))},updatePostProcessingConfig:function(e){if(S.updateSigmaSpace(e.jointBilateralFilter.sigmaSpace),S.updateSigmaColor(e.jointBilateralFilter.sigmaColor),"image"===i.type){const t=k;t.updateCoverage(e.coverage),t.updateLightWrapping(e.lightWrapping),t.updateBlendMode(e.blendMode)}else if("blur"===i.type){k.updateCoverage(e.coverage)}else{const e=k;e.updateCoverage([0,.9999]),e.updateLightWrapping(0)}},cleanUp:function(){k.cleanUp(),S.cleanUp(),_.cleanUp(),w.cleanUp(),u.deleteTexture(b),u.deleteTexture(y),u.deleteTexture(v),u.deleteBuffer(g),u.deleteBuffer(m),u.deleteVertexArray(f),u.deleteShader(h)}}}var aa,ca,da,la,pa,ua,ha,fa,ma,ga;class va{constructor(e){aa.set(this,!1),ca.set(this,void 0),da.set(this,void 0),la.set(this,void 0),s(this,la,new Be({logLevel:e,namespace:"TensorFlowLoader"}),"f")}get isLoaded(){return i(this,aa,"f")}get tfliteModule(){return i(this,ca,"f")||i(this,da,"f")}loadTFLite(){return r(this,void 0,void 0,(function*(){yield Promise.all([this.loadTFLiteRegular(),this.loadTFLiteSIMD()]),this.tfliteModule&&s(this,aa,!0,"f")}))}loadTFLiteModel(e){return r(this,void 0,void 0,(function*(){if(this.tfliteModule)try{const t=va.getTFLiteModelFileName(e);i(this,la,"f").info("loading model",{modelFileName:t});const r=yield fetch(`${window.location.origin}/tflite/models/${t}.tflite`),s=yield r.arrayBuffer(),n=this.tfliteModule._getModelBufferMemoryOffset();this.tfliteModule.HEAPU8.set(new Uint8Array(s),n);const o=this.tfliteModule._loadModel(s.byteLength);i(this,la,"f").info("loading model result",{result:o})}catch(e){i(this,la,"f").warn("loadTFLiteModel()",{error:e})}else i(this,la,"f").warn("loadTFLiteModel()",{description:"TFLite module is not loaded"})}))}loadTFLiteRegular(){return r(this,void 0,void 0,(function*(){try{s(this,ca,yield createTFLiteModule(),"f")}catch(e){i(this,la,"f").error("Failed to create TFLite WebAssembly module.",{error:e})}}))}loadTFLiteSIMD(){return r(this,void 0,void 0,(function*(){try{s(this,da,yield createTFLiteSIMDModule(),"f")}catch(e){i(this,la,"f").error("Failed to create TFLite SIMD WebAssembly module.",{error:e})}}))}static getTFLiteModelFileName({model:e,inputResolution:t}){switch(e){case"meet":return"256x144"===t?"segm_full_v679":"segm_lite_v681";case"mlkit":return"selfiesegmentation_mlkit-256x256-2021_01_19-v1215.f16";default:throw new Error(`No TFLite file for this segmentation model: ${e}`)}}}function ya({sourcePlayback:e,backgroundConfig:t,segmentationConfig:i,canvas:s,tflite:n}){const o=s.getContext("2d");o.scale(1.031,1.031),o.translate(-11,-11);const[a,c]=ra[i.inputResolution],d=a*c,l=new ImageData(a,c),p=document.createElement("canvas");p.width=a,p.height=c;const u=p.getContext("2d"),h=n._getInputMemoryOffset()/4,f=n._getOutputMemoryOffset()/4;let m;return{render:function(){return r(this,void 0,void 0,(function*(){"none"!==t.type&&(function(){if(u.drawImage(e.htmlElement,0,0,e.width,e.height,0,0,a,c),"meet"===i.model||"mlkit"===i.model){const e=u.getImageData(0,0,a,c);for(let t=0;t<d;t+=1)n.HEAPF32[h+3*t]=e.data[4*t]/255,n.HEAPF32[h+3*t+1]=e.data[4*t+1]/255,n.HEAPF32[h+3*t+2]=e.data[4*t+2]/255}}(),function(){n._runInference();for(let e=0;e<d;e+=1)if("meet"===i.model){const t=n.HEAPF32[f+2*e],r=n.HEAPF32[f+2*e+1],i=Math.max(t,r),s=Math.exp(t-i),o=Math.exp(r-i);l.data[4*e+3]=255*o/(s+o)}else if("mlkit"===i.model){const t=n.HEAPF32[f+e];l.data[4*e+3]=255*t}u.putImageData(l,0,0)}()),o.globalCompositeOperation="copy",o.filter="none",(null==m?void 0:m.smoothSegmentationMask)&&("blur"===t.type||"image"===t.type)&&(o.filter="blur(8px)"),"none"!==t.type&&(o.drawImage(p,0,0,a,c,0,0,e.width,e.height),o.globalCompositeOperation="source-in",o.filter="none"),o.drawImage(e.htmlElement,0,0),"blur"===t.type&&(o.globalCompositeOperation="destination-over",o.filter="blur(8px)",o.drawImage(e.htmlElement,0,0))}))},updatePostProcessingConfig:function(e){m=e},cleanUp:function(){}}}aa=new WeakMap,ca=new WeakMap,da=new WeakMap,la=new WeakMap;class ba{constructor(e){pa.set(this,void 0),ua.set(this,void 0),ha.set(this,!1),fa.set(this,void 0),s(this,pa,new va(e.logLevel),"f"),s(this,fa,new Be({namespace:"VideoTrackProcessor",logLevel:e.logLevel}),"f")}get isProcessing(){return i(this,ha,"f")}processTrack(e){return r(this,void 0,void 0,(function*(){const{track:t,pipelineConfig:n}=e;i(this,ha,"f")&&this.stopProcessing();try{i(this,pa,"f").isLoaded||(yield i(this,pa,"f").loadTFLite(),yield i(this,pa,"f").loadTFLiteModel(n.segmentationConfig));const{tfliteModule:o}=i(this,pa,"f");if(!o)throw new Error("TensorFlow model is not available");const{targetFps:a}=n.segmentationConfig,c=yield ba.buildSourcePlayback(t),d=document.createElement("canvas");d.width=c.width,d.height=c.height;const l=function(){const e=new Map,t=new Worker(`${window.location.origin}/timerWorker.js`);t.onmessage=t=>{const r=e.get(t.data.callbackId);r&&(e.delete(t.data.callbackId),r())};let r=1;return{setTimeout:function(i,s){return r+=1,e.set(r,i),t.postMessage({callbackId:r,timeoutMs:s}),r},clearTimeout:function(r){e.has(r)&&(t.postMessage({callbackId:r}),e.delete(r))},terminate:function(){e.clear(),t.terminate()}}}(),p={config:n,sourcePlayback:c,destinationPlayback:d,tflite:o},u="canvas2dCpu"===e.pipelineConfig.segmentationConfig.pipeline?ba.buildCanvas2dPipeline(p):ba.buildWebGL2Pipeline(p),h=()=>r(this,void 0,void 0,(function*(){const e=performance.now();return yield u.render(),l.setTimeout(h,performance.now()-e)})),f=yield h();u.updatePostProcessingConfig(n.postprocessingConfig);const m=d.captureStream(a),[g]=m.getVideoTracks();return s(this,ua,{pipeline:u,destination:d,source:c.htmlElement,track:g,timerWorker:l,timerId:f},"f"),s(this,ha,!0,"f"),g}catch(e){throw i(this,fa,"f").error("processTrack()",{error:e,track:t}),new Error("Can not process this track")}}))}stopProcessing(){if(this.isProcessing)if(i(this,ua,"f"))try{i(this,ua,"f").pipeline.cleanUp(),i(this,ua,"f").source.remove(),i(this,ua,"f").destination.remove(),i(this,ua,"f").timerWorker.clearTimeout(i(this,ua,"f").timerId),i(this,ua,"f").timerWorker.terminate(),i(this,ua,"f").destination.remove(),i(this,ua,"f").track.stop(),s(this,ua,void 0,"f"),s(this,ha,!1,"f")}catch(e){i(this,fa,"f").error("cleanUp()",{error:e})}else i(this,fa,"f").warn("cleanUp()",{description:"This track is not processing"});else i(this,fa,"f").debug("stopProcessing()",{description:"Track is not processed"})}static buildWebGL2Pipeline(e){return oa({backgroundImage:e.config.backgroundConfig.imageSource,sourcePlayback:e.sourcePlayback,backgroundConfig:e.config.backgroundConfig,segmentationConfig:e.config.segmentationConfig,canvas:e.destinationPlayback,tflite:e.tflite})}static buildCanvas2dPipeline(e){return ya({sourcePlayback:e.sourcePlayback,backgroundConfig:e.config.backgroundConfig,segmentationConfig:e.config.segmentationConfig,canvas:e.destinationPlayback,tflite:e.tflite})}static buildSourcePlayback(e){return r(this,void 0,void 0,(function*(){const t=document.createElement("video");return t.srcObject=new MediaStream([e]),t.autoplay=!0,yield t.play(),{htmlElement:t,width:t.videoWidth,height:t.videoHeight}}))}}pa=new WeakMap,ua=new WeakMap,ha=new WeakMap,fa=new WeakMap;class wa extends Ko{constructor(e){super(e),ma.set(this,void 0),ga.set(this,void 0),this.transformParams={},s(this,ma,new ba({logLevel:e.logLevel}),"f"),this.watchOrientation(),this.watchDocumentVisibility()}get isEffectsProcessing(){return i(this,ma,"f").isProcessing}getEncoderConfig(){return this.encoderConfig}getCodecOptions(){return{videoGoogleStartBitrate:this.getEncoderConfig().videoGoogleStartBitrate||1e3}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||(this.getLabel()===u.ScreenVideo?"vp8":"h264")}getEncodings(){return this.getEncoderConfig().encodings||xo}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return r(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"})}enableBlur(){return r(this,void 0,void 0,(function*(){try{s(this,ga,this.mediaStreamTrack.clone(),"f");const e=yield i(this,ma,"f").processTrack({track:this.mediaStreamTrack,pipelineConfig:document.hidden?sa:ia});yield this.replaceTrack(e),this.logger.info("enableBlur()",{track:this})}catch(e){throw this.logger.warn("enableBlur()",{track:this,error:e}),new Error("Can not enable virtual background")}}))}disableBlur(){return r(this,void 0,void 0,(function*(){try{if(!i(this,ma,"f").isProcessing)return void this.logger.debug("disableBlur()",{description:"Track is not processed"});if(!i(this,ga,"f"))return void this.logger.warn("disableBlur()",{description:"Original track missing"});yield this.replaceTrack(i(this,ga,"f")),i(this,ma,"f").stopProcessing(),this.logger.info("disableBlur()",{track:this})}catch(e){throw this.logger.warn("disableBlur()",{track:this,error:e}),new Error("Can not disable virtual background")}}))}publish(e={}){var t;return r(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.clientEventEmitter.emit(F,this)}))}watchOrientation(){window.screen.orientation&&(this.logger.debug("watchOrientation()",{description:"Watching started"}),window.screen.orientation.addEventListener("change",(()=>r(this,void 0,void 0,(function*(){if(this.isEffectsProcessing)try{this.mediaStreamTrack.enabled=!1;const e=yield i(this,ma,"f").processTrack({track:this.mediaStreamTrack,pipelineConfig:document.hidden?sa:ia});yield this.replaceTrack(e)}catch(e){this.logger.warn("watchOrientation()",{description:"Restart blur error after orientation change",error:e})}})))))}watchDocumentVisibility(){this.logger.debug("watchDocumentVisibility()",{description:"Watching started"}),window.addEventListener("visibilitychange",(()=>r(this,void 0,void 0,(function*(){if(this.isEffectsProcessing)try{yield this.disableBlur(),yield this.enableBlur()}catch(e){this.logger.warn("watchDocumentVisibility()",{description:"Restart blur error after change document visibility",error:e})}}))))}}ma=new WeakMap,ga=new WeakMap;const _a={"yandex browser":">=22",chrome:">=74",chromium:">=74"};class Sa 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 r(this,void 0,void 0,(function*(){yield e.audioWorklet.addModule(`${window.location.origin}/noiseSuppressionWorklet.js`)}))}}var ka,Ra,Ca,Pa,Ta,Ea;class Da{constructor(e){ka.set(this,void 0),Ra.set(this,void 0),Ca.set(this,void 0),Pa.set(this,void 0),Ta.set(this,void 0),Ea.set(this,!0),s(this,ka,e.noiseSuppressor.instance.exports,"f"),s(this,Ra,e.context,"f"),s(this,Ca,new Float32Array(i(this,ka,"f").memory.buffer),"f"),s(this,Pa,i(this,ka,"f").newState(),"f"),s(this,Ta,i(this,Ra,"f").createScriptProcessor(),"f"),this.setOnAudioProcess()}get noiseSuppressionScriptProcessorNode(){return i(this,Ta,"f")}update(e){e||(s(this,Ea,!1,"f"),i(this,ka,"f").deleteState(i(this,Pa,"f")));const t=Object.assign(new Event("status"),{vadProb:i(this,ka,"f").getVadProb(i(this,Pa,"f"))});i(this,Ta,"f").dispatchEvent(t)}setOnAudioProcess(){i(this,Ta,"f").addEventListener("audioprocess",(({inputBuffer:e,outputBuffer:t})=>{if(!i(this,Ea,"f"))return;i(this,Ca,"f").set(e.getChannelData(0),i(this,ka,"f").getInput(i(this,Pa,"f"))/4);const r=t.getChannelData(0),s=i(this,ka,"f").pipe(i(this,Pa,"f"),r.length)/4;s&&r.set(i(this,Ca,"f").subarray(s,s+r.length))}))}}ka=new WeakMap,Ra=new WeakMap,Ca=new WeakMap,Pa=new WeakMap,Ta=new WeakMap,Ea=new WeakMap;var xa,Ma,La,Oa,Ia,Aa,ja,Fa,Na,Ba,Ua;class qa{constructor({context:e,noiseSuppressor:t}){xa.set(this,void 0),Ma.set(this,void 0),La.set(this,void 0),s(this,xa,e,"f"),s(this,Ma,t,"f")}createNoiseSuppressionNode(){return r(this,void 0,void 0,(function*(){return/apple/i.test(navigator.vendor)?this.createScriptProcessorNode():this.createAudioWorkletNode()}))}stop(){var e;null===(e=i(this,La,"f"))||void 0===e||e.update(!1)}createAudioWorkletNode(){return r(this,void 0,void 0,(function*(){return yield Sa.register(i(this,xa,"f")),s(this,La,new Sa({context:i(this,xa,"f"),noiseSuppressor:i(this,Ma,"f")}),"f"),i(this,La,"f")}))}createScriptProcessorNode(){return s(this,La,new Da({context:i(this,xa,"f"),noiseSuppressor:i(this,Ma,"f")}),"f"),i(this,La,"f").noiseSuppressionScriptProcessorNode}}xa=new WeakMap,Ma=new WeakMap,La=new WeakMap;class Wa{constructor(e){Oa.set(this,void 0),Ia.set(this,void 0),Aa.set(this,void 0),ja.set(this,void 0),Fa.set(this,!1),s(this,Oa,e.noiseSuppressor,"f"),s(this,Aa,new Be({namespace:"TrackProcessor",logLevel:e.logLevel}),"f")}get isProcessing(){return i(this,Fa,"f")}processTrack(e){return r(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 Sa.register(t);const n=t.createMediaStreamSource(new MediaStream([e])),o=new qa({context:t,noiseSuppressor:i(this,Oa,"f")}),a=yield o.createNoiseSuppressionNode();a.connect(r),n.connect(a);const[c]=r.stream.getTracks();return s(this,Ia,{audioContext:t,streamDestination:r,noiseSuppressionNode:a,noiseSuppressionProvider:o},"f"),s(this,ja,c,"f"),i(this,Aa,"f").info("processTrack()",{track:e}),c}))}stopProcessing(){var e;return r(this,void 0,void 0,(function*(){if(this.isProcessing)if(i(this,Ia,"f"))try{i(this,Ia,"f").noiseSuppressionProvider.stop(),i(this,Ia,"f").noiseSuppressionNode.disconnect(),i(this,Ia,"f").streamDestination.disconnect(),yield i(this,Ia,"f").audioContext.close(),null===(e=i(this,ja,"f"))||void 0===e||e.stop(),i(this,Aa,"f").info("stopProcessing()",{success:!0})}catch(e){i(this,Aa,"f").error("stopProcessing()",{success:!1,error:e})}else i(this,Aa,"f").warn("stopProcessing()",{success:!1,description:"Processing context is not available"});else i(this,Aa,"f").debug("stopProcessing()",{description:"Track is not processed"})}))}}Oa=new WeakMap,Ia=new WeakMap,Aa=new WeakMap,ja=new WeakMap,Fa=new WeakMap;class Va extends Ko{constructor(e){super(e),Na.set(this,void 0),Ba.set(this,void 0),Ua.set(this,void 0),e.noiseSuppressor&&s(this,Na,new Wa({noiseSuppressor:e.noiseSuppressor,logLevel:e.logLevel}),"f"),s(this,Ua,new Be({namespace:"AudioTrack",logLevel:e.logLevel}),"f")}get isEffectsProcessing(){var e;return!!(null===(e=i(this,Na,"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:Lo}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 r(this,void 0,void 0,(function*(){if(i(this,Na,"f"))try{const t=yield null===(e=i(this,Na,"f"))||void 0===e?void 0:e.processTrack(this.mediaStreamTrack);s(this,Ba,this.mediaStreamTrack,"f"),yield this.replaceTrack(t)}catch(e){throw this.logger.warn("enableNoiseSuppression()",{description:"Can not enable noise suppression",track:this,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 r(this,void 0,void 0,(function*(){try{if(!(null===(e=i(this,Na,"f"))||void 0===e?void 0:e.isProcessing))return void i(this,Ua,"f").debug("stopProcessing()",{description:"Track is not processed"});if(!i(this,Ba,"f"))return void this.logger.warn("disableNoiseSuppression()",{description:"Original track missing"});yield this.replaceTrack(i(this,Ba,"f")),yield null===(t=i(this,Na,"f"))||void 0===t?void 0:t.stopProcessing()}catch(e){throw this.logger.warn("disableNoiseSuppression()",{description:"Can not disable noise suppression",track:this,error:e}),new Error("Can not disable noise suppression")}}))}publish(){return r(this,void 0,void 0,(function*(){yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),codecOptions:this.getCodecOptions()}),this.clientEventEmitter.emit(F,this)}))}}Na=new WeakMap,Ba=new WeakMap,Ua=new WeakMap;const za={width:1280,height:720};var $a,Ga,Ha,Ja,Ka,Qa,Xa;class Ya{constructor(e){var t;$a.set(this,void 0),s(this,$a,new Be({namespace:"MediaStreamTrackManager",logLevel:null!==(t=e.logLevel)&&void 0!==t?t:Oe,onLogMessage:e.onLogMessage}),"f")}createMediaStreamTrack({label:e,constraints:t}){return r(this,void 0,void 0,(function*(){if(Ya.isDisplayMedia(e)){const[e]=yield this.createDisplayMediaTracks(t);return e}const[r]=yield this.createUserMediaTracks(t);return r}))}static isDisplayMedia(e){return[u.ScreenVideo,u.ScreenAudio].includes(e)}createUserMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getUserMedia(e);return i(this,$a,"f").debug("createUserMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}createDisplayMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getDisplayMedia(e);return i(this,$a,"f").debug("getDisplayMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}}$a=new WeakMap;class Za{constructor(e){this.isDeviceLoaded=!1,this.tracks=new Map,Ga.set(this,void 0),Ha.set(this,void 0),Ja.set(this,void 0),Ka.set(this,void 0),Qa.set(this,void 0),Xa.set(this,void 0),s(this,Ha,e.logLevel,"f"),s(this,Ga,new Be({namespace:"Media",logLevel:e.logLevel,onLogMessage:e.onLogMessage}),"f"),s(this,Ja,e.engine,"f"),s(this,Ka,e.clientEventEmitter,"f"),s(this,Qa,new Ya({logLevel:e.logLevel,onLogMessage:e.onLogMessage}),"f")}get mediasoupDevice(){return this.device||(this.device=this.createDevice()),this.device}get isNoiseSuppressorLoaded(){return!!i(this,Xa,"f")}loadDevice(e){return r(this,void 0,void 0,(function*(){this.isDeviceLoaded||(yield this.mediasoupDevice.load({routerRtpCapabilities:e}),this.isDeviceLoaded=!0)}))}createNoiseSuppressor(){return r(this,void 0,void 0,(function*(){try{if(i(this,Xa,"f"))return void i(this,Ga,"f").warn("createNoiseSuppressor()",{message:"Noise suppression module already created"});s(this,Xa,yield class{static compileModule(e){return r(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){i(this,Ga,"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()}`));i(this,Ga,"f").error("getTrackCodec()",{track:e,rtpCapabilities:t})}createTracks({constraints:e,mediaStreamTracks:t}){return t.map((t=>{const r={mediaStreamTrack:t,logLevel:i(this,Ha,"f"),engine:i(this,Ja,"f"),clientEventEmitter:i(this,Ka,"f"),constraints:e,mediaStreamTrackManager:i(this,Qa,"f")},s="audio"===t.kind?new Va(Object.assign(Object.assign({},r),{noiseSuppressor:i(this,Xa,"f")})):new wa(r);return this.tracks.set(s.id,s),i(this,Ga,"f").debug("createTrack() track created",{trackId:s.id,kind:s.kind}),s}))}createUserMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=yield i(this,Qa,"f").createUserMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createDisplayMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=yield i(this,Qa,"f").createDisplayMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}deleteTrack(e){return r(this,void 0,void 0,(function*(){yield e.closeProducer(),e.mediaStreamTrack.stop(),"disableNoiseSuppression"in e&&(yield e.disableNoiseSuppression()),this.tracks.delete(e.id),i(this,Ga,"f").debug("deleteTrack() tack deleted",{trackId:e.id,kind:e.kind})}))}getAllTracks(){return Array.from(this.tracks.values())}clearTracks(){return r(this,void 0,void 0,(function*(){try{this.getAllTracks().map((e=>e.stopMediaStreamTrack()))}catch(e){i(this,Ga,"f").warn("clearTracks()",{error:e})}finally{this.tracks.clear()}}))}static getVideoTrackTransformParams(e){const t=e.getSettings();return{width:t.width||za.width,height:t.height||za.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:za.width},height:{max:za.height}},encoderConfig:(null==e?void 0:e.videoEncoderConfig)||{encodings:Mo}}}static getCameraVideoTrackParams(e){var t;return{videoTrackOptions:null!==(t=null==e?void 0:e.video)&&void 0!==t?t:{frameRate:{max:24},width:{max:za.width},height:{max:za.height}},encoderConfig:(null==e?void 0:e.encoderConfig)||{encodings:xo}}}createDevice(){const e=(e=>{const t=null!=e?e:null===navigator||void 0===navigator?void 0:navigator.userAgent;if(!t)return;return Ye.getParser(t).satisfies(_a)?"Chrome74":void 0})();return i(this,Ga,"f").debug("Creating a media device",{handlerName:null!=e?e:"not specified"}),new qe.Device({handlerName:e})}}Ga=new WeakMap,Ha=new WeakMap,Ja=new WeakMap,Ka=new WeakMap,Qa=new WeakMap,Xa=new WeakMap;const ec=new class{sleepMs(e){return r(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}},tc=(e,t={})=>r(void 0,void 0,void 0,(function*(){var r;const i=t.maxRetries||2,s=t.minBackoffDelayMs||50;let n,o=0;for(;o<i;){o+=1;try{return yield e()}catch(e){if(n=e,t.logger&&t.logger.info("Action retry failed",{currentAttempt:o,actionName:t.actionName,error:e}),o<i){const e=Math.pow(2,o-1)*s;yield ec.sleepMs(Math.min(e,null!==(r=t.maxBackoffDelayMs)&&void 0!==r?r:e))}}}throw n}));class rc{constructor(e){this.initialized=!1,this.isJoined=!1,this.isChannelJoining=!1;const{clientEventEmitter:t,network:r,dependenciesFactory:i,logLevel:s}=e;this.logLevel=s||Le,this.system=i.createSystem({logLevel:this.logLevel,clientEventEmitter:t,onLogMessage:e.onLogMessage}),this.media=i.createMedia({logLevel:this.logLevel,engine:this,clientEventEmitter:t,onLogMessage:e.onLogMessage}),this.network=i.createNetwork({logLevel:this.logLevel,loadbalancer:r.loadbalancer,onLogMessage:e.onLogMessage}),this.peersRepository=new Map,this.clientEventEmitter=t,this.channelEventsHandler=i.createChannelEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.mediaSoupEventsHandler=i.createMediaSoupEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.logger=new Be({logLevel:this.logLevel,namespace:"Engine",onLogMessage:e.onLogMessage}),this.webRtcIssueDetector=e.disableWid?void 0:i.createIssueDetector({onIssues:e.onIssues,onNetworkScoresUpdated:e.onNetworkScoresUpdated,ignoreSSRCList:[1234],logger:new Be({logLevel:this.logLevel,namespace:"WID"})}),this.watchSocketState(),this.watchClientEvents()}initialize(){var e,t,i;return r(this,void 0,void 0,(function*(){try{const{rtpCapabilities:r}=yield this.network.socket.request("router.getRtpCapabilities");yield this.media.createNoiseSuppressor(),yield this.media.loadDevice(r),null===(e=this.webRtcIssueDetector)||void 0===e||e.watchNewPeerConnections(),yield this.network.createSendTransport(this.media.mediasoupDevice),yield 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===(i=this.network.receiveTransport)||void 0===i?void 0:i.id})}catch(e){if(this.logger.error("initialize()",{error:e}),e instanceof f&&"device not supported"===e.message||e instanceof Error&&"RTCPeerConnection is not defined"===e.message)throw new v("Device not supported",v.UNSUPPORTED_DEVICE_CODE);throw new Error("Error initialize engine")}}))}release(){var e;return r(this,void 0,void 0,(function*(){try{this.initialized=!1,this.isJoined=!1,this.app=void 0,this.channel=void 0,null===(e=this.webRtcIssueDetector)||void 0===e||e.stopWatchingNewPeerConnections(),this.network.socket.disconnect(),this.peersRepository.clear(),yield this.network.closeSendTransport(),yield this.network.closeReceiveTransport(),yield this.media.clearTracks(),this.logger.debug("release()",{socketId:this.mySocketId})}catch(e){throw this.logger.error("release()",{error:e}),new Error("Error release engine")}}))}watchSocketState(){this.network.socket.observer.on("state",(e=>{const{state:t,code:r}=e;this.clientEventEmitter.emit(t,{code:r}),t===Y.Reconnected&&this.clientEventEmitter.emit(O)}))}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 mySocketId(){return this.network.socket.id}confirmActivity(){var e;return r(this,void 0,void 0,(function*(){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");yield this.network.socket.request(k)}))}join(e){return r(this,void 0,void 0,(function*(){try{this.logger.debug("join()",{params:e}),this.isChannelJoining=!0,yield this.connectToSocketServerWithRetry(e),yield this.performJoin(e)}catch(e){throw this.logger.error("join()",{error:e}),e}finally{this.isChannelJoining=!1}}))}loadPeers(e){return r(this,void 0,void 0,(function*(){const{peers:t}=yield this.network.socket.request(w,{role: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 Do(Object.assign(Object.assign({},e),{engine:this,loginDate:new Date}));return this.peersRepository.set(r.id,r),r}removePeer(e){const t=this.peersRepository.get(e);t&&(t.tracks.forEach((e=>e.close())),this.peersRepository.delete(e))}updateAppData(e){return r(this,void 0,void 0,(function*(){const{myPeer:t}=this;if(!t)throw new Error("Need join to channel first");try{To(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 r(this,void 0,void 0,(function*(){const t=Za.getCameraVideoTrackParams(e);try{const[r]=yield this.media.createUserMediaTracks({audio:!1,video:t.videoTrackOptions});if(r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof wa&&(r.setLabel(u.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(Za.getVideoTrackTransformParams(r.mediaStreamTrack)),null==e?void 0:e.blur))try{yield r.enableBlur()}catch(e){this.logger.warn("Failed to start virtual background, featured original track",{track:this})}return this.logger.debug("createCameraVideoTrack()",{trackParams:t,track:r}),r}catch(e){throw this.logger.error("createCameraVideoTrack()",{error:e,trackParams:t}),new Error(`Can not create camera track: ${e.message}`)}}))}createMicrophoneAudioTrack(e){return r(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(u.Microphone),t.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),(null==e?void 0:e.encoderConfig)&&t.setEncoderConfig(e.encoderConfig),t instanceof Va&&(null==e?void 0:e.noiseSuppression))try{yield t.enableNoiseSuppression()}catch(e){this.logger.warn("Failed to start noise suppression, featured original track",{track:this})}return this.logger.debug("createMicrophoneAudioTrack()",{options:e,track:t}),t}catch(t){throw this.logger.error("createMicrophoneAudioTrack()",{error:t,options:e}),new Error(`Can not create microphone track: ${t.message}`)}}))}createScreenMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=Za.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()})),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof wa){r.setLabel(u.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=Za.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),void this.logger.debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,track:r})}r.setLabel(u.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.logger.debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig,track:r})})),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}connectToSocketServerWithRetry(e){return r(this,void 0,void 0,(function*(){return tc((()=>r(this,void 0,void 0,(function*(){return this.connectToSocketServer(e)}))),{maxRetries:15,minBackoffDelayMs:150,maxBackoffDelayMs:5e3,actionName:"connectToSocketServer",logger:new Be({namespace:"RetrySocketConnect",logLevel:this.logLevel})})}))}connectToSocketServer(e){return r(this,void 0,void 0,(function*(){const{webSocketUrl:t}=yield this.getAvailableNode({channelId:e.channelId,role:e.role});this.network.socket.connect(t);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 r(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 i=s=>r(this,void 0,void 0,(function*(){const{error:r,state:n}=s,o=()=>this.network.socket.observer.removeListener("state",i),a=[Y.Disconnected,Y.Reconnecting].includes(n);return r?(o(),void t(r)):this.isChannelJoining&&a?(o(),void t(new Error(`Not expected socket state for new connection: ${n}`))):void(this.isChannelJoining&&[Y.Connected,Y.Reconnected].includes(n)&&(o(),e()))}));this.network.socket.observer.on("state",i)}))}performJoin(e){return r(this,void 0,void 0,(function*(){try{yield this.sendJoinChannelRequestWithRetry(e),this.app=e.appId,this.channel=e.channelId,yield this.initialize(),this.channelEventsHandler.subscribeToEvents(),this.mediaSoupEventsHandler.subscribeToEvents(),this.isJoined=!0,this.logger.debug("Successfully joined channel",{channelId:e.channelId})}catch(e){throw this.logger.error("performJoin()",{error:e}),e}}))}sendJoinChannelRequestWithRetry(e){return r(this,void 0,void 0,(function*(){return tc((()=>r(this,void 0,void 0,(function*(){return this.sendJoinChannelRequest(e)}))),{maxRetries:3,minBackoffDelayMs:300,actionName:"sendJoinChannelRequest",logger:new Be({namespace:"RetryJoin",logLevel:this.logLevel})})}))}sendJoinChannelRequest(e){return r(this,void 0,void 0,(function*(){return this.network.socket.request(b,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.clientEventEmitter.on(F,(e=>r(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.clientEventEmitter.on(N,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close(),this.media.deleteTrack(e)})),this.clientEventEmitter.on(B,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.pause()})),this.clientEventEmitter.on(U,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.resume()})),this.clientEventEmitter.on(q,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close()})),this.clientEventEmitter.on(W,(e=>r(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)}))))}createSelfPeerTrack(e){var t;return r(this,void 0,void 0,(function*(){const r=this.peersRepository.get(this.mySocketId);if(!r)return;yield null===(t=r.tracks.get(e.getLabel()))||void 0===t?void 0:t.close();const i=new Po({mediaStreamTrack:e.mediaStreamTrack,label:e.getLabel(),engine:this,muted:!1,paused:e.isPaused,peerEventEmitter:r.observer});r.tracks.set(i.label,i)}))}}var ic,sc,nc;function oc(){}function ac(){ac.init.call(this)}function cc(e){return void 0===e._maxListeners?ac.defaultMaxListeners:e._maxListeners}function dc(e,t,r){if(t)e.call(r);else for(var i=e.length,s=vc(e,i),n=0;n<i;++n)s[n].call(r)}function lc(e,t,r,i){if(t)e.call(r,i);else for(var s=e.length,n=vc(e,s),o=0;o<s;++o)n[o].call(r,i)}function pc(e,t,r,i,s){if(t)e.call(r,i,s);else for(var n=e.length,o=vc(e,n),a=0;a<n;++a)o[a].call(r,i,s)}function uc(e,t,r,i,s,n){if(t)e.call(r,i,s,n);else for(var o=e.length,a=vc(e,o),c=0;c<o;++c)a[c].call(r,i,s,n)}function hc(e,t,r,i){if(t)e.apply(r,i);else for(var s=e.length,n=vc(e,s),o=0;o<s;++o)n[o].apply(r,i)}function fc(e,t,r,i){var s,n,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((n=e._events)?(n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),o=n[t]):(n=e._events=new oc,e._eventsCount=0),o){if("function"==typeof o?o=n[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(s=cc(e))&&s>0&&o.length>s){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=n[t]=r,++e._eventsCount;return e}function mc(e,t,r){var i=!1;function s(){e.removeListener(t,s),i||(i=!0,r.apply(e,arguments))}return s.listener=r,s}function gc(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 vc(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}oc.prototype=Object.create(null),ac.EventEmitter=ac,ac.usingDomains=!1,ac.prototype.domain=void 0,ac.prototype._events=void 0,ac.prototype._maxListeners=void 0,ac.defaultMaxListeners=10,ac.init=function(){this.domain=null,ac.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new oc,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},ac.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},ac.prototype.getMaxListeners=function(){return cc(this)},ac.prototype.emit=function(e){var t,r,i,s,n,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(i=arguments.length){case 1:dc(r,l,this);break;case 2:lc(r,l,this,arguments[1]);break;case 3:pc(r,l,this,arguments[1],arguments[2]);break;case 4:uc(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(i-1),n=1;n<i;n++)s[n-1]=arguments[n];hc(r,l,this,s)}return!0},ac.prototype.addListener=function(e,t){return fc(this,e,t,!1)},ac.prototype.on=ac.prototype.addListener,ac.prototype.prependListener=function(e,t){return fc(this,e,t,!0)},ac.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,mc(this,e,t)),this},ac.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,mc(this,e,t)),this},ac.prototype.removeListener=function(e,t){var r,i,s,n,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new oc:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,n=r.length;n-- >0;)if(r[n]===t||r[n].listener&&r[n].listener===t){o=r[n].listener,s=n;break}if(s<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new oc,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,s=e.length;i<s;r+=1,i+=1)e[r]=e[i];e.pop()}(r,s);i.removeListener&&this.emit("removeListener",e,o||t)}return this},ac.prototype.off=function(e,t){return this.removeListener(e,t)},ac.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new oc,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new oc:delete r[e]),this;if(0===arguments.length){for(var i,s=Object.keys(r),n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new oc,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},ac.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):[]},ac.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):gc.call(e,t)},ac.prototype.listenerCount=gc,ac.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class yc extends ac{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(ic||(ic={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(sc||(sc={})),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"}(nc||(nc={}));class bc extends ac{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(bc.STATS_REPORTS_PARSED,{timeTaken:r}),t.forEach((e=>{this.emit(bc.STATS_REPORT_READY_EVENT,e)}))}}const wc=(()=>{const e=new Map;return t=>{const{taskId:r,delayMs:i,maxJitterMs:s,callback:n}=t,o=Math.ceil(Math.random()*(s||0)),a=e.get(r);a&&clearTimeout(a);const c=setTimeout((()=>{n(),e.delete(r)}),i+o);e.set(r,c)}})();class _c{#e={};calculate(e){const{connection:{id:t}}=e,r=this.calculateOutboundScore(e),i=this.calculateInboundScore(e);return this.#e[t]=e,wc({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:r,inbound:i}}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 i=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:s}=e.connection,n=r.connection.packetsSent,o=t.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}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=s-n,p=o.packetsLost-o.lastPacketsLost,u=l&&p?Math.round(100*p/(l+p)):0;return this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:u})}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 i=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:s}=e.connection,n=r.connection.packetsReceived,o=t.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}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=s-n,p=o.packetsLost-o.lastPacketsLost,u=l&&p?Math.round(100*p/(l+p)):0;return this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:u})}calculateMOS({avgJitter:e,rtt:t,packetsLoss:r}){const i=t+2*e+10;let s=i<160?93.2-i/40:93.2-i/120-10;return s-=2.5*r,1+.035*s+7e-6*s*(s-60)*(100-s)}}class Sc{#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)&&wc({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 kc extends Sc{#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 i=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),s=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!i&&!s)return t;const n={availableOutgoingBitrate:r,videoStreamsTotalBitrate:s,audioStreamsTotalTargetBitrate:i};return i>r||s>0&&r<this.#r?(t.push({statsSample:n,type:sc.Network,reason:nc.OutboundNetworkThroughput}),t):t}}class Rc extends Sc{#i;constructor(e={}){super(e),this.#i=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=[],i=this.getLastProcessedStats(e.connection.id)?.video.inbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesDropped===t.framesDropped)return;const s=e.framesReceived-t.framesReceived,n=e.framesDecoded-t.framesDecoded,o=e.framesDropped-t.framesDropped,a=o/s;if(0===s||0===n)return;const c={deltaFramesDropped:o,deltaFramesReceived:s,deltaFramesDecoded:n,framesDroppedPct:Math.round(100*a)};a>=this.#i&&r.push({statsSample:c,type:sc.CPU,reason:nc.DecoderCPUThrottling,ssrc:e.ssrc})})),r):r}}class Cc extends Sc{#s;constructor(e={}){super(e),this.#s=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=[],i=this.getLastProcessedStats(e.connection.id)?.video.outbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesEncoded===t.framesEncoded)return;const s=e.framesEncoded-t.framesEncoded,n=e.framesSent-t.framesSent,o=1-n/s;if(0===s)return;if(s===n)return;const a={deltaFramesSent:n,deltaFramesEncoded:s,missedFramesPct:Math.round(100*o)};o>=this.#s&&r.push({statsSample:a,type:sc.Network,reason:nc.OutboundNetworkThroughput,ssrc:e.ssrc})})),r):r}}class Pc extends Sc{highPacketLossThresholdPct;highJitterThreshold;highJitterBufferDelayThresholdMs;highRttThresholdMs;constructor(e={}){super(),this.highPacketLossThresholdPct=e.highPacketLossThresholdPct??5,this.highJitterThreshold=e.highJitterThreshold??200,this.highJitterBufferDelayThresholdMs=e.highJitterBufferDelayThresholdMs??500,this.highRttThresholdMs=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 i=this.getLastProcessedStats(e.connection.id);if(!i)return t;const s=[...i.video?.inbound,...i.audio?.inbound],{packetsReceived:n}=e.connection,o=i.connection.packetsReceived,a=r.reduce(((e,t)=>{const r=s.find((e=>e.ssrc===t.ssrc)),i=r?.jitterBufferDelay||0,n=r?.jitterBufferEmittedCount||0,o=t.jitterBufferDelay-i,a=t.jitterBufferEmittedCount-n,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,p=d/r.length,u=l/r.length,h=n-o,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.highPacketLossThresholdPct,v=p>=this.highJitterThreshold,y=c>=this.highRttThresholdMs,b=u>this.highJitterBufferDelayThresholdMs,w=y&&!v&&!g,_=g&&v,S=v&&b,k={rtt:c,packetLossPct:m,avgJitter:p,avgJitterBufferDelay:u};return(v||g)&&t.push({statsSample:k,type:sc.Network,reason:nc.InboundNetworkQuality,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:k,type:sc.Server,reason:nc.ServerIssue,iceCandidate:e.connection.remote.id}),_&&t.push({statsSample:k,type:sc.Network,reason:nc.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),S&&t.push({statsSample:k,type:sc.Network,reason:nc.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class Tc extends Sc{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=[],i=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;const s=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,n=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(s===n)return;const o=e.track.totalSamplesReceived-t.track.totalSamplesReceived,a=s-n,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>5&&r.push({statsSample:d,type:sc.Network,reason:nc.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class Ec extends Sc{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 i=this.getLastProcessedStats(e.connection.id);if(!i)return t;const s=[...i.remote?.audio.inbound||[],...i.remote?.video.inbound||[]],{packetsSent:n}=e.connection,o=i.connection.packetsSent,a=r.reduce(((e,t)=>{const r=s.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,p=n-o,u=a.packetsLost-a.lastPacketsLost,h=p&&u?Math.round(100*u/(p+u)):0,f=h>5,m=l>=200,g=!f&&m||m||f,v={rtt:c,avgJitter:l,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:sc.Network,reason:nc.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:sc.Network,reason:nc.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class Dc extends Sc{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=[],i=this.getLastProcessedStats(e.connection.id)?.video.outbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;const s={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&r.push({statsSample:s,type:sc.CPU,reason:nc.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:s,type:sc.Network,reason:nc.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class xc extends Sc{UNKNOWN_DECODER="unknown";#n={};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.#n[t],"function"==typeof r&&r()}})}processData(e){const t=[],{id:r}=e.connection,i=this.getLastProcessedStats(r)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:s,ssrc:n}=e,o=i?.find((e=>e.ssrc===n));if(o)if(s===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(r,n)){this.setLastDecoderWithIssue(r,n,this.UNKNOWN_DECODER);const i={mimeType:e.mimeType,decoderImplementation:s};t.push({ssrc:n,statsSample:i,type:sc.Stream,reason:nc.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,n,void 0)})),t}setLastDecoderWithIssue(e,t,r){const i=this.#n[e]??{};void 0===r?delete i[t]:i[t]=r,this.#n[e]=i}hadLastDecoderWithIssue(e,t){const r=this.#n[e];return(r&&r[t])===this.UNKNOWN_DECODER}}const Mc=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,Lc=(e,t,r)=>8*((e,t,r)=>{if(!t)return 0;const i=e[r],s=t[r];if(null==i||null==s)return 0;const n=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===n?0:(Number(i)-Number(s))/n*1e3})(e,t,r);class Oc{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(!Mc(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 Ic{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);logger;constructor(e){this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!Mc(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 i=Date.now(),s=await Promise.all(t.getReceivers().map((e=>e.getStats()))),n=await Promise.all(t.getSenders().map((e=>e.getStats())));return{id:r,stats:this.mapReportsStats([...s,...n],e),timeTaken:Date.now()-i}}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:i}=t,s=this.prevStats.get(i);return s&&this.propagateStatsWithRateValues(r,s.stats),this.prevStats.set(i,{stats:r,ts:Date.now()}),wc({taskId:i,delayMs:35e3,callback:()=>this.prevStats.delete(i)}),r}updateMappedStatsWithReportItemData(e,t,r){const i=e.type;if("candidate-pair"===i&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,r));const s=this.getMediaType(e);if(s)if("outbound-rtp"!==i)if("inbound-rtp"!==i)"remote-outbound-rtp"!==i?"remote-inbound-rtp"===i&&(this.mapConnectionStatsIfNecessary(t,e,r),t.remote[s].inbound.push({...e})):t.remote[s].outbound.push({...e});else{const i=r.get(e.trackId)||r.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,r);const n={...e,track:{...i}};t[s].inbound.push(n)}else{const i=r.get(e.trackId)||r.get(e.mediaSourceId)||{},n={...e,track:{...i}};t[s].outbound.push(n)}}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=Lc(e,r,"bytesReceived"),e.packetRate=Lc(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=Lc(e,r,"bytesSent"),e.packetRate=Lc(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=Lc(e,r,"bytesReceived"),e.packetRate=Lc(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=Lc(e,r,"bytesSent"),e.packetRate=Lc(e,r,"packetsSent")}))}mapConnectionStatsIfNecessary(e,t,r){if(e.connection.id||!t.transportId)return;const i=r.get(t.transportId);if(i&&i.selectedCandidatePairId){const t=r.get(i.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 Ac{eventEmitter;#o=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new yc,e.onIssues&&this.eventEmitter.on(ic.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(ic.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new Dc,new Rc,new Cc,new Pc,new Ec,new Tc,new kc,new xc],this.networkScoresCalculator=e.networkScoresCalculator??new _c,this.compositeStatsParser=e.compositeStatsParser??new Oc({statsParser:new Ic({logger:this.logger})}),this.statsReporter=e.statsReporter??new bc({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.wrapRTCPeerConnection(),this.statsReporter.on(bc.STATS_REPORT_READY_EVENT,(t=>{this.detectIssues({data:t.stats,ignoreSSRCList:e.ignoreSSRCList}),this.calculateNetworkScores(t.stats)})),this.statsReporter.on(bc.STATS_REPORTS_PARSED,(e=>{const t={timeTaken:e.timeTaken,ts:Date.now()};this.eventEmitter.emit(ic.StatsParsingFinished,t)}))}watchNewPeerConnections(){this.#o?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#o=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#o?(this.logger.info("Stop watching peer connections"),this.#o=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e){this.#o?(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(ic.Issue,e)}detectIssues({data:e,ignoreSSRCList:t}){let r=this.detectors.reduce(((t,r)=>[...t,...r.detect(e)]),[]);t?.length&&(r=r.filter((e=>!e.ssrc||!t.includes(e.ssrc)))),r.length>0&&this.emitIssues(r)}calculateNetworkScores(e){const t=this.networkScoresCalculator.calculate(e);this.eventEmitter.emit(ic.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 i=new e(r);return t(i),i}r.prototype=e.prototype,window.RTCPeerConnection=r}}class jc{constructor(e){const{socketClient:t,loadBalancerApiClient:r,onLogMessage:i}=e;this.socket=t,this.loadBalancerClient=r,this.logger=new Be({namespace:"Network",logLevel:e.logLevel,onLogMessage:i})}closeRemoteProducer(e){return r(this,void 0,void 0,(function*(){yield this.socket.request(ee,{peerId:this.socket.id,producerId:e})}))}closeSendTransport(){var e;return r(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=void 0):this.logger.warn("closeSendTransport()",{message:"No available send transport"})}))}closeReceiveTransport(){var e;return r(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=void 0):this.logger.warn("closeReceiveTransport()",{message:"No available receive transport"})}))}closeTransport(e){return r(this,void 0,void 0,(function*(){try{const{success:t}=yield this.socket.request(me,{transportId:e.id});return this.logger.debug("closeTransport()",{transport:e}),Boolean(t)}catch(e){return this.logger.error("closeTransport()",{error:e}),!1}finally{e.close()}}))}createSendTransport(e){return r(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(fe,{sctpCapabilities:e.sctpCapabilities,localDirection:"send"});this.sendTransport=e.createSendTransport(t),this.logger.debug("createSendTransport()",{transport:this.sendTransport}),this.sendTransport.on(_e,(({dtlsParameters:e},i,s)=>r(this,void 0,void 0,(function*(){var r,n;try{yield this.socket.request(ge,{transportId:null===(r=this.sendTransport)||void 0===r?void 0:r.id,dtlsParameters:e}),i(),this.logger.debug("sendTransport.connect()",{transportId:null===(n=this.sendTransport)||void 0===n?void 0:n.id,dtlsRole:e.role})}catch(r){this.logger.error("sendTransport.on(`connect`)",{dtlsParameters:e,sendTransportOptions:t,error:r}),s(r)}})))),this.sendTransport.on(Se,((e,t,i)=>r(this,void 0,void 0,(function*(){var r,s,n;try{const{id:i}=yield this.socket.request(ve,{transportId:null===(r=this.sendTransport)||void 0===r?void 0:r.id,kind:e.kind,rtpParameters:e.rtpParameters,appData:e.appData});t({id:i}),this.logger.debug("sendTransport.produce()",{producerId:i,transportId:null===(s=this.sendTransport)||void 0===s?void 0:s.id,kind:e.kind})}catch(t){this.logger.error("sendTransport.produce()",{error:t,transportId:null===(n=this.sendTransport)||void 0===n?void 0:n.id,kind:e.kind}),i(t)}})))),this.sendTransport.on(be,(e=>{var t;this.logger.debug("sendTransport.state",{state:e}),"failed"===e&&this.sendTransport&&(this.restartIce(this.sendTransport),this.logger.warn("sendTransport.restartIce()",{state:e,sendTransportId:null===(t=this.sendTransport)||void 0===t?void 0:t.id})),setTimeout((()=>{var e,t;"disconnected"===(null===(e=this.sendTransport)||void 0===e?void 0:e.connectionState)&&(null===(t=this.socket.connection)||void 0===t?void 0:t.connected)&&this.logger.warn("sendTransport is closed before websocket is closed",{sendTransportId:this.sendTransport.id})}),3e3)}))}))}createRecvTransport(e){return r(this,void 0,void 0,(function*(){if(this.receiveTransport)return void this.logger.warn("createRecvTransport()",{message:"Receive transport already exists"});const t=yield this.socket.request(fe,{localDirection:"receive"});this.receiveTransport=e.createRecvTransport(t),this.logger.debug("createRecvTransport()",{transport:this.receiveTransport}),this.receiveTransport.on(_e,(({dtlsParameters:e},t,i)=>r(this,void 0,void 0,(function*(){var r,s;try{yield this.socket.request(ge,{transportId:null===(r=this.receiveTransport)||void 0===r?void 0:r.id,dtlsParameters:e}),t(),this.logger.debug("receiveTransport.connect()",{transportId:null===(s=this.receiveTransport)||void 0===s?void 0:s.id,dtlsRole:e.role})}catch(e){this.logger.error("receiveTransport.on(`connect`)",{error:e}),i(e)}})))),this.receiveTransport.on(be,(e=>{this.logger.debug("receiveTransport.state",{state:e}),"failed"===e&&this.receiveTransport&&(this.restartIce(this.receiveTransport),this.logger.debug("receiveTransport.restartIce()",{recvTransportId:this.receiveTransport.id})),setTimeout((()=>{var e,t;"disconnected"===(null===(e=this.receiveTransport)||void 0===e?void 0:e.connectionState)&&(null===(t=this.socket.connection)||void 0===t?void 0:t.connected)&&this.logger.warn("receiveTransport is closed before websocket is closed",{recvTransportId:this.receiveTransport.id})}),3e3)}))}))}getIceParameters(e){return r(this,void 0,void 0,(function*(){const t=yield this.socket.request(we,{transportId:e.id}),{error:r}=t;if(r)throw new Error(r);return this.logger.debug("getIceParameters()",{iceParameters:t}),t}))}restartIce(e){return r(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),this.logger.debug("restartIce() completed",{iceParameters:t})}catch(e){this.logger.error("restartIce()",{error:e})}}))}createConsumer({producerId:e,rtpCapabilities:t,appId:i,channelId:s,producerPeerId:n}){return r(this,void 0,void 0,(function*(){const r=this.receiveTransport;if(!r)throw this.logger.error("createConsumer()",{reason:"missing receiveTransport"}),new Error("Client not initialized");this.logger.debug("createConsumer()",{producerId:e});const o=yield this.socket.request(oe,{producerId:e,transportId:r.id,rtpCapabilities:t,appData:{peerId:this.socket.id,appId:i,channelId:s},producerPeerId:n}),a=yield r.consume(o),{producerPaused:c}=o;return this.logger.debug("Consumer created",{consumer:a,isProducerPaused:c}),{consumer:a,isProducerPaused:c}}))}closeRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(ae,{peerId:this.socket.id,consumerId:e})}))}resumeRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(de,{consumerId:e})}))}pauseRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(ce,{consumerId:e})}))}updatePeerAppData({peerId:e,appData:t}){return r(this,void 0,void 0,(function*(){return this.socket.request(S,{peerId:e,appData:t})}))}getTransportsStateInfo(){return r(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}}))}getParsedTransportStats(e){return r(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)),i=t.find((e=>"remote-candidate"===e.type)),s=t.find((e=>"transport"===e.type));return{dtlsState:null==s?void 0:s.dtlsState,iceState:null==s?void 0:s.iceState,dtlsRole:null==s?void 0:s.dtlsRole,iceRole:null==s?void 0:s.iceRole,selectedCandidatePairChanges:null==s?void 0:s.selectedCandidatePairChanges,tlsVersion:null==s?void 0:s.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==i?void 0:i.ip,address:null==i?void 0:i.address,port:null==i?void 0:i.port,protocol:null==i?void 0:i.protocol,candidateType:null==i?void 0:i.candidateType}}}catch(e){return void this.logger.warn("getParsedTransportStats()",{error:e})}else this.logger.debug("getParsedTransportStats()",{message:"Transport is missing"})}))}}const Fc=e=>![h.NotFoundError,h.NotAllowedError,h.DeviceIsBusy].includes(e);class Nc{constructor(e){this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[];const{clientEventEmitter:t,logLevel:r,onLogMessage:i}=e;this.clientEventEmitter=t,this.logger=new Be({namespace:"System",logLevel:r,onLogMessage:i}),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 r(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(h.NotAllowedError);if("NotReadableError"===t.name)throw new Error(h.DeviceIsBusy);if("NotFoundError"===t.name)throw new Error(h.NotFoundError);throw new Error(h.RequestDevicesUnknownError)}}))}refreshAvailableMediaDevicesList(){return r(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 i=({label:e,kind:t})=>({label:e,kind:t});return this.logger.debug("Devices list updated",{videoDevices:t.map(i),audioDevices:r.map(i)}),e}))}detectDevices(){return r(this,void 0,void 0,(function*(){let e=[];if(this.isDevicesDetected)return;try{e=yield this.requestMediaDevicesAccess()}catch(e){if(Fc(e.message))throw e;e.message!==h.DeviceIsBusy&&(yield this.assertHasAccessToMediaDevices({audio:!0}),yield this.assertHasAccessToMediaDevices({video:!0}))}this.isDevicesDetected=!0;const t=yield this.refreshAvailableMediaDevicesList();e.forEach((e=>e.stop()));const r=t.some((e=>"audioinput"===e.kind)),i=t.some((e=>"videoinput"===e.kind));if(!r&&!i)throw new Error(h.NoDevices)}))}deviceChangeHandler(){return r(this,void 0,void 0,(function*(){this.isDevicesDetected&&(yield this.refreshAvailableMediaDevicesList(),this.clientEventEmitter.safeEmit(I,{audio:this.availableAudioDevices,video:this.availableVideoDevices}))}))}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}assertHasAccessToMediaDevices(e={video:!0,audio:!0}){return r(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess(e)).forEach((e=>e.stop()))}catch(e){if(Fc(e.message))throw e}}))}}class Bc{constructor(e){const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Be({logLevel:t.logLevel,namespace:"ChannelEvents",onLogMessage:r})}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");e.on(y,(e=>{this.engine.clientEventEmitter.safeEmit(T,e),this.logger.debug("New channel event",{event:e})})),e.on(b,(e=>{const t=this.engine.setPeer(e);this.engine.clientEventEmitter.safeEmit(E,t),this.logger.debug("Peer joined to the channel",{peer:t})})),e.on(_,(e=>{this.engine.removePeer(e),this.engine.clientEventEmitter.safeEmit(D,e),this.logger.debug("Peer left the channel",{peerId:e})})),e.on(C,(e=>{this.engine.clientEventEmitter.safeEmit(x,e),this.logger.info("Notify the channel that activity confirmation is required",e)})),e.on(P,(e=>{this.engine.clientEventEmitter.safeEmit(L,e),this.logger.info("Notify the channel that it has disconnected due to the activity confirmation expiring",e)})),e.on(R,(e=>{this.engine.clientEventEmitter.safeEmit(M,e),this.logger.info("Notify the channel that the activity has been acquired.",e)})),e.on(S,(({peerId:e,appData:t})=>{const r=this.engine.peers.find((t=>t.id===e));r&&r.observer.emit(S,t)}))}}class Uc{constructor(e){this.queue=new Co;const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Be({logLevel:t.logLevel,namespace:"MediasoupEvents",onLogMessage:r})}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");e.on(ee,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&!t.isMe&&t.observer.safeEmit(ee,e)})),e.on(Z,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&!t.isMe&&t.observer.safeEmit(Z,e)})),e.on(ae,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&r.observer.safeEmit(ae,e)})),e.on(de,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(de,e)})),e.on(ce,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(ce,e)})),e.on(pe,(({peerId:e,spatialLayer:t,temporalLayer:r,consumerId:i})=>{const s=this.engine.peers.find((t=>t.id===e));s&&!s.isMe&&s.observer.safeEmit(pe,{consumerId:i,spatialLayer:t,temporalLayer:r})})),e.on(le,(e=>{const{consumerPeerId:t}=e,r=this.engine.peers.find((e=>e.id===t));if(!r||r.isMe)return;r.observer.safeEmit(le,e);const i=this.engine.peers.find((e=>e.isMe));i&&i.observer.safeEmit(le,e)})),e.on(ie,(e=>{const t=this.engine.peers.find((e=>e.isMe));t&&t.observer.safeEmit(ie,e)})),e.on(ne,(({producerId:e,spatialLayer:t})=>r(this,void 0,void 0,(function*(){yield this.queue.push((()=>r(this,void 0,void 0,(function*(){yield this.handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t})}))),ne)})))),e.on(se,(({peerId:e,producerId:t,spatialLayer:i})=>r(this,void 0,void 0,(function*(){const r=this.engine.peers.find((t=>t.id===e));r&&!r.isMe&&r.observer.safeEmit(se,{peerId:e,producerId:t,spatialLayer:i})})))),e.on(ye,(({reason:e,transportId:t,direction:i,timeout:s})=>r(this,void 0,void 0,(function*(){const r=[this.engine.network.receiveTransport,this.engine.network.sendTransport].find((e=>(null==e?void 0:e.id)===t));r&&"connected"!==r.connectionState&&(this.logger.warn(ye,{reason:e,transportId:t,direction:i,timeout:s}),this.engine.clientEventEmitter.emit(A,{direction:i,reason:e}))}))))}handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t}){return r(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 wa))return void this.logger.warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const i=r.getMaxSpatialLayer();i!==t?(yield r.setMaxSpatialLayer(t),yield this.engine.network.socket.request(se,{producerId:e,maxSpatialLayer:t})):this.logger.debug("producerRequestMaxSpatialLayer()",{message:"Skip set max spatial layer",requestedSpatialLayer:t,currentMaxSpatialLayer:i})}))}}var qc=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Wc=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],Vc=function(e){var t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));for(var s,n,o=qc.exec(e||""),a={},c=14;c--;)a[Wc[c]]=o[c]||"";return-1!=r&&-1!=i&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(e,t){var r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.substr(0,1)&&0!==t.length||i.splice(0,1);"/"==t.substr(t.length-1,1)&&i.splice(i.length-1,1);return i}(0,a.path),a.queryKey=(s=a.query,n={},s.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,r){t&&(n[t]=r)})),n),a};var zc={exports:{}};try{zc.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){zc.exports=!1}var $c=zc.exports,Gc="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Hc(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||$c))return new XMLHttpRequest}catch(e){}if(!t)try{return new(Gc[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function Jc(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Kc=setTimeout,Qc=clearTimeout;function Xc(e,t){t.useNativeTimers?(e.setTimeoutFn=Kc.bind(Gc),e.clearTimeoutFn=Qc.bind(Gc)):(e.setTimeoutFn=setTimeout.bind(Gc),e.clearTimeoutFn=clearTimeout.bind(Gc))}var Yc=Zc;function Zc(e){if(e)return function(e){for(var t in Zc.prototype)e[t]=Zc.prototype[t];return e}(e)}Zc.prototype.on=Zc.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Zc.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},Zc.prototype.off=Zc.prototype.removeListener=Zc.prototype.removeAllListeners=Zc.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<i.length;s++)if((r=i[s])===t||r.fn===t){i.splice(s,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},Zc.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var s=(r=r.slice(0)).length;i<s;++i)r[i].apply(this,t)}return this},Zc.prototype.emitReserved=Zc.prototype.emit,Zc.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Zc.prototype.hasListeners=function(e){return!!this.listeners(e).length};const ed=Object.create(null);ed.open="0",ed.close="1",ed.ping="2",ed.pong="3",ed.message="4",ed.upgrade="5",ed.noop="6";const td=Object.create(null);Object.keys(ed).forEach((e=>{td[ed[e]]=e}));const rd={type:"error",data:"parser error"},id="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),sd="function"==typeof ArrayBuffer,nd=({type:e,data:t},r,i)=>{return id&&t instanceof Blob?r?i(t):od(t,i):sd&&(t instanceof ArrayBuffer||(s=t,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer))?r?i(t):od(new Blob([t]),i):i(ed[e]+(t||""));var s},od=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+e)},r.readAsDataURL(e)};for(var ad="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",cd="undefined"==typeof Uint8Array?[]:new Uint8Array(256),dd=0;dd<ad.length;dd++)cd[ad.charCodeAt(dd)]=dd;const ld="function"==typeof ArrayBuffer,pd=(e,t)=>{if("string"!=typeof e)return{type:"message",data:hd(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:ud(e.substring(1),t)};return td[r]?e.length>1?{type:td[r],data:e.substring(1)}:{type:td[r]}:rd},ud=(e,t)=>{if(ld){const r=function(e){var t,r,i,s,n,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);var d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=cd[e.charCodeAt(t)],i=cd[e.charCodeAt(t+1)],s=cd[e.charCodeAt(t+2)],n=cd[e.charCodeAt(t+3)],l[c++]=r<<2|i>>4,l[c++]=(15&i)<<4|s>>2,l[c++]=(3&s)<<6|63&n;return d}(e);return hd(r,t)}return{base64:!0,data:e}},hd=(e,t)=>"blob"===t&&e instanceof ArrayBuffer?new Blob([e]):e,fd=String.fromCharCode(30);class md extends Yc{constructor(e){super(),this.writable=!1,Xc(this,e),this.opts=e,this.query=e.query,this.readyState="",this.socket=e.socket}onError(e,t){const r=new Error(e);return r.type="TransportError",r.description=t,super.emit("error",r),this}open(){return"closed"!==this.readyState&&""!==this.readyState||(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.emit("open")}onData(e){const t=pd(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emit("packet",e)}onClose(){this.readyState="closed",super.emit("close")}}var gd,vd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),yd={},bd=0,wd=0;function _d(e){var t="";do{t=vd[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function Sd(){var e=_d(+new Date);return e!==gd?(bd=0,gd=e):e+"."+_d(bd++)}for(;wd<64;wd++)yd[vd[wd]]=wd;Sd.encode=_d,Sd.decode=function(e){var t=0;for(wd=0;wd<e.length;wd++)t=64*t+yd[e.charAt(wd)];return t};var kd=Sd,Rd={encode:function(e){var t="";for(var r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t},decode:function(e){for(var t={},r=e.split("&"),i=0,s=r.length;i<s;i++){var n=r[i].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}};class Cd extends md{constructor(){super(...arguments),this.polling=!1}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.emit("poll")}onData(e){((e,t)=>{const r=e.split(fd),i=[];for(let e=0;e<r.length;e++){const s=pd(r[e],t);if(i.push(s),"error"===s.type)break}return i})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose(),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("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,i=new Array(r);let s=0;e.forEach(((e,n)=>{nd(e,!1,(e=>{i[n]=e,++s===r&&t(i.join(fd))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emit("drain")}))}))}uri(){let e=this.query||{};const t=this.opts.secure?"https":"http";let r="";!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=kd()),this.supportsBinary||e.sid||(e.b64=1),this.opts.port&&("https"===t&&443!==Number(this.opts.port)||"http"===t&&80!==Number(this.opts.port))&&(r=":"+this.opts.port);const i=Rd.encode(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(i.length?"?"+i:"")}}function Pd(){}const Td=null!=new Hc({xdomain:!1}).responseType;class Ed extends Yc{constructor(e,t){super(),Xc(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.create()}create(){const e=Jc(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;const t=this.xhr=new Hc(e);try{t.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&t.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{t.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in t&&(t.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(t.timeout=this.opts.requestTimeout),t.onreadystatechange=()=>{4===t.readyState&&(200===t.status||1223===t.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof t.status?t.status:0)}),0))},t.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=Ed.requestsCount++,Ed.requests[this.index]=this)}onSuccess(){this.emit("success"),this.cleanup()}onData(e){this.emit("data",e),this.onSuccess()}onError(e){this.emit("error",e),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Pd,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Ed.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&this.onData(e)}abort(){this.cleanup()}}if(Ed.requestsCount=0,Ed.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Dd);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Gc?"pagehide":"unload",Dd,!1)}function Dd(){for(let e in Ed.requests)Ed.requests.hasOwnProperty(e)&&Ed.requests[e].abort()}const xd="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Md=Gc.WebSocket||Gc.MozWebSocket,Ld="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Od extends md{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=Ld?{}:Jc(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=Ld?new Md(e,t,r):t?new Md(e,t):new Md(e)}catch(e){return this.emit("error",e)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=this.onClose.bind(this),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],i=t===e.length-1;nd(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}i&&xd((()=>{this.writable=!0,this.emit("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let e=this.query||{};const t=this.opts.secure?"wss":"ws";let r="";this.opts.port&&("wss"===t&&443!==Number(this.opts.port)||"ws"===t&&80!==Number(this.opts.port))&&(r=":"+this.opts.port),this.opts.timestampRequests&&(e[this.opts.timestampParam]=kd()),this.supportsBinary||(e.b64=1);const i=Rd.encode(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(i.length?"?"+i:"")}check(){return!(!Md||"__initialize"in Md&&this.name===Od.prototype.name)}}const Id={websocket:Od,polling:class extends Cd{constructor(e){if(super(e),"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,this.xs=e.secure!==t}const t=e&&e.forceBase64;this.supportsBinary=Td&&!t}request(e={}){return Object.assign(e,{xd:this.xd,xs:this.xs},this.opts),new Ed(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e=>{this.onError("xhr post error",e)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e=>{this.onError("xhr poll error",e)})),this.pollXhr=e}}};class Ad extends Yc{constructor(e,t={}){super(),e&&"object"==typeof e&&(t=e,e=null),e?(e=Vc(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=Vc(t.host).host),Xc(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"],this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},t),this.opts.path=this.opts.path.replace(/\/$/,"")+"/","string"==typeof this.opts.query&&(this.opts.query=Rd.decode(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&addEventListener("beforeunload",(()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())}),!1),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close")},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=function(e){const t={};for(let r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}(this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new Id[e](r)}open(){let e;if(this.opts.rememberUpgrade&&Ad.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",(()=>{this.onClose("transport close")}))}probe(e){let t=this.createTransport(e),r=!1;Ad.priorWebsocketSuccess=!1;const i=()=>{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;Ad.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 s(){r||(r=!0,d(),t.close(),t=null)}const n=e=>{const r=new Error("probe error: "+e);r.transport=t.name,s(),this.emitReserved("upgradeError",r)};function o(){n("transport closed")}function a(){n("socket closed")}function c(e){t&&e.name!==t.name&&s()}const d=()=>{t.removeListener("open",i),t.removeListener("error",n),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",n),t.once("close",o),this.once("close",a),this.once("upgrading",c),t.open()}onOpen(){if(this.readyState="open",Ad.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause){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"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.resetPingTimeout(),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.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(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emitReserved("flush"))}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,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const s={type:e,data:t,options:r};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),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){Ad.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("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 i=e.length;for(;r<i;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}Ad.protocol=4,Ad.protocol;const jd="function"==typeof ArrayBuffer,Fd=Object.prototype.toString,Nd="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Fd.call(Blob),Bd="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Fd.call(File);function Ud(e){return jd&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Nd&&e instanceof Blob||Bd&&e instanceof File}function qd(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(qd(e[t]))return!0;return!1}if(Ud(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return qd(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&qd(e[t]))return!0;return!1}function Wd(e){const t=[],r=e.data,i=e;return i.data=Vd(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Vd(e,t){if(!e)return e;if(Ud(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 i=0;i<e.length;i++)r[i]=Vd(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)e.hasOwnProperty(i)&&(r[i]=Vd(e[i],t));return r}return e}function zd(e,t){return e.data=$d(e.data,t),e.attachments=void 0,e}function $d(e,t){if(!e)return e;if(e&&e._placeholder)return t[e.num];if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=$d(e[r],t);else if("object"==typeof e)for(const r in e)e.hasOwnProperty(r)&&(e[r]=$d(e[r],t));return e}var Gd;!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"}(Gd||(Gd={}));class Hd extends Yc{constructor(){super()}add(e){let t;if("string"==typeof e)t=this.decodeString(e),t.type===Gd.BINARY_EVENT||t.type===Gd.BINARY_ACK?(this.reconstructor=new Jd(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t);else{if(!Ud(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===Gd[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Gd.BINARY_EVENT||r.type===Gd.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(i,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(s)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=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(i,t+1))}if(e.charAt(++t)){const i=function(e){try{return JSON.parse(e)}catch(e){return!1}}(e.substr(t));if(!Hd.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}static isPayloadValid(e,t){switch(e){case Gd.CONNECT:return"object"==typeof t;case Gd.DISCONNECT:return void 0===t;case Gd.CONNECT_ERROR:return"string"==typeof t||"object"==typeof t;case Gd.EVENT:case Gd.BINARY_EVENT:return Array.isArray(t)&&t.length>0;case Gd.ACK:case Gd.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&this.reconstructor.finishedReconstruction()}}class Jd{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=zd(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Kd=Object.freeze({__proto__:null,protocol:5,get PacketType(){return Gd},Encoder:class{encode(e){return e.type!==Gd.EVENT&&e.type!==Gd.ACK||!qd(e)?[this.encodeAsString(e)]:(e.type=e.type===Gd.EVENT?Gd.BINARY_EVENT:Gd.BINARY_ACK,this.encodeAsBinary(e))}encodeAsString(e){let t=""+e.type;return e.type!==Gd.BINARY_EVENT&&e.type!==Gd.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)),t}encodeAsBinary(e){const t=Wd(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},Decoder:Hd});function Qd(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Xd=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Yd extends Yc{constructor(e,t,r){super(),this.connected=!1,this.disconnected=!0,this.receiveBuffer=[],this.sendBuffer=[],this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this.io._autoConnect&&this.open()}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Qd(e,"open",this.onopen.bind(this)),Qd(e,"packet",this.onpacket.bind(this)),Qd(e,"error",this.onerror.bind(this)),Qd(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(Xd.hasOwnProperty(e))throw new Error('"'+e+'" is a reserved event name');t.unshift(e);const r={type:Gd.EVENT,data:t,options:{}};r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]&&(this.acks[this.ids]=t.pop(),r.id=this.ids++);const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?this.packet(r):this.sendBuffer.push(r)),this.flags={},this}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this.packet({type:Gd.CONNECT,data:e})})):this.packet({type:Gd.CONNECT,data:this.auth})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e){this.connected=!1,this.disconnected=!0,delete this.id,this.emitReserved("disconnect",e)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Gd.CONNECT:if(e.data&&e.data.sid){const t=e.data.sid;this.onconnect(t)}else 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 Gd.EVENT:case Gd.BINARY_EVENT:this.onevent(e);break;case Gd.ACK:case Gd.BINARY_ACK:this.onack(e);break;case Gd.DISCONNECT:this.ondisconnect();break;case Gd.CONNECT_ERROR: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)}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Gd.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e){this.id=e,this.connected=!0,this.disconnected=!1,this.emitBuffered(),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((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:Gd.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}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||[]}}var Zd=el;function el(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}el.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)},el.prototype.reset=function(){this.attempts=0},el.prototype.setMin=function(e){this.ms=e},el.prototype.setMax=function(e){this.max=e},el.prototype.setJitter=function(e){this.jitter=e};class tl extends Yc{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,Xc(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 Zd({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Kd;this.encoder=new i.Encoder,this.decoder=new i.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 Ad(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=Qd(t,"open",(function(){r.onopen(),e&&e()})),s=Qd(t,"error",(t=>{r.cleanup(),r._readyState="closed",this.emitReserved("error",t),e?e(t):r.maybeReconnectOnOpen()}));if(!1!==this._timeout){const e=this._timeout;0===e&&i();const r=this.setTimeoutFn((()=>{i(),t.close(),t.emit("error",new Error("timeout"))}),e);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}return this.subs.push(i),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(Qd(e,"ping",this.onping.bind(this)),Qd(e,"data",this.ondata.bind(this)),Qd(e,"error",this.onerror.bind(this)),Qd(e,"close",this.onclose.bind(this)),Qd(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){this.decoder.add(e)}ondecoded(e){this.emitReserved("packet",e)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r||(r=new Yd(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,"opening"===this._readyState&&this.cleanup(),this.backoff.reset(),this._readyState="closed",this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e),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((function(){clearTimeout(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const rl={};function il(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=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),i=Vc(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const s=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+s+":"+i.port+t,i.href=i.protocol+"://"+s+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,s=r.id,n=r.path,o=rl[s]&&n in rl[s].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new tl(i,t):(rl[s]||(rl[s]=new tl(i,t)),a=rl[s]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}class sl{constructor(e){this.reconnectingAttempt=0,this.isConnected=!1,this._observer=new n,this.knownDisconnectReasonsCodes={"io server disconnect":"server.disconnect","io client disconnect":"client.disconnect","ping timeout":"ping.timeout","transport close":"transport.close","transport error":"transport.error"},this.logger=new Be({namespace:"Socket",logLevel:e.logLevel,onLogMessage:e.onLogMessage})}get observer(){return this._observer}get id(){var e;return null===(e=this.connection)||void 0===e?void 0:e.id}connect(e){const t=il(e,{transports:["polling","websocket"],upgrade:!0,rememberUpgrade:!1});this.connection=t,this.serverUrl=e,t.on("connect",(()=>{const e=this.reconnectingAttempt?Y.Reconnected:Y.Connected;this.isConnected=!0,this.setReconnectingAttempt(0),this.logger.debug("connection.on(`connect`)",{connectionId:t.id}),this.observer.safeEmit("state",{state:e})})),t.on("connect_error",(e=>{this.connectionError=e,this.logger.error("connection.on(`connect_error`)",{error:e}),this.observer.safeEmit("state",{state:Y.Error,error:e})})),t.on("disconnect",(e=>{this.isConnected=!1,this.setReconnectingAttempt(0),this.disconnectReason=e,this.logger.warn("connection.on(`disconnect`)",{reason:e}),this.observer.safeEmit("state",{state:Y.Disconnected,code:this.getDisconnectReasonCode(e)})})),t.io.on("reconnect_attempt",(e=>{this.setReconnectingAttempt(e),this.logger.warn("connection.on(`reconnect_attempt`)",{attempt:e}),this.observer.safeEmit("state",{state:Y.Reconnecting})})),t.io.on("reconnect",(()=>{this.logger.debug("connection.on(`reconnect`)",{connectionId:t.id}),this.observer.safeEmit("state",{state:Y.Reconnect})}))}disconnect(){this.connection&&(this.connection.offAny(),this.connection.volatile.offAny(),this.connection.disconnect(),this.setReconnectingAttempt(0))}request(e,t={}){return new Promise(((r,i)=>{if(!this.connection)return this.logger.error("request()",{type:e,data:t}),void i(new Error("Socket request: Socket connection is not initialized"));this.connection.emit(e,t,(s=>{s.error?(this.logger.error("request()",{event:e,payload:t,response:s}),i(s.error)):r(s)}))}))}getDisconnectReasonCode(e){const t=String(e).toLowerCase();return this.knownDisconnectReasonsCodes[t]||t}setReconnectingAttempt(e){this.reconnectingAttempt=e}}var nl={exports:{}},ol=function(e,t){return function(){for(var r=new Array(arguments.length),i=0;i<r.length;i++)r[i]=arguments[i];return e.apply(t,r)}},al=ol,cl=Object.prototype.toString;function dl(e){return"[object Array]"===cl.call(e)}function ll(e){return void 0===e}function pl(e){return null!==e&&"object"==typeof e}function ul(e){if("[object Object]"!==cl.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function hl(e){return"[object Function]"===cl.call(e)}function fl(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),dl(e))for(var r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.call(null,e[s],s,e)}var ml={isArray:dl,isArrayBuffer:function(e){return"[object ArrayBuffer]"===cl.call(e)},isBuffer:function(e){return null!==e&&!ll(e)&&null!==e.constructor&&!ll(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:pl,isPlainObject:ul,isUndefined:ll,isDate:function(e){return"[object Date]"===cl.call(e)},isFile:function(e){return"[object File]"===cl.call(e)},isBlob:function(e){return"[object Blob]"===cl.call(e)},isFunction:hl,isStream:function(e){return pl(e)&&hl(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:fl,merge:function e(){var t={};function r(r,i){ul(t[i])&&ul(r)?t[i]=e(t[i],r):ul(r)?t[i]=e({},r):dl(r)?t[i]=r.slice():t[i]=r}for(var i=0,s=arguments.length;i<s;i++)fl(arguments[i],r);return t},extend:function(e,t,r){return fl(t,(function(t,i){e[i]=r&&"function"==typeof t?al(t,r):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e}},gl=ml;function vl(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var yl=function(e,t,r){if(!t)return e;var i;if(r)i=r(t);else if(gl.isURLSearchParams(t))i=t.toString();else{var s=[];gl.forEach(t,(function(e,t){null!=e&&(gl.isArray(e)?t+="[]":e=[e],gl.forEach(e,(function(e){gl.isDate(e)?e=e.toISOString():gl.isObject(e)&&(e=JSON.stringify(e)),s.push(vl(t)+"="+vl(e))})))})),i=s.join("&")}if(i){var n=e.indexOf("#");-1!==n&&(e=e.slice(0,n)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e},bl=ml;function wl(){this.handlers=[]}wl.prototype.use=function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1},wl.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},wl.prototype.forEach=function(e){bl.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var _l=wl,Sl=ml,kl=function(e,t,r,i,s){return e.config=t,r&&(e.code=r),e.request=i,e.response=s,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},e},Rl=kl,Cl=function(e,t,r,i,s){var n=new Error(e);return Rl(n,t,r,i,s)},Pl=Cl,Tl=ml,El=Tl.isStandardBrowserEnv()?{write:function(e,t,r,i,s,n){var o=[];o.push(e+"="+encodeURIComponent(t)),Tl.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Tl.isString(i)&&o.push("path="+i),Tl.isString(s)&&o.push("domain="+s),!0===n&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},Dl=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)},xl=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},Ml=ml,Ll=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"],Ol=ml,Il=Ol.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function i(e){var i=e;return t&&(r.setAttribute("href",i),i=r.href),r.setAttribute("href",i),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=i(window.location.href),function(t){var r=Ol.isString(t)?i(t):t;return r.protocol===e.protocol&&r.host===e.host}}():function(){return!0},Al=ml,jl=function(e,t,r){var i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(Pl("Request failed with status code "+r.status,r.config,null,r.request,r)):e(r)},Fl=El,Nl=yl,Bl=function(e,t){return e&&!Dl(t)?xl(e,t):t},Ul=function(e){var t,r,i,s={};return e?(Ml.forEach(e.split("\n"),(function(e){if(i=e.indexOf(":"),t=Ml.trim(e.substr(0,i)).toLowerCase(),r=Ml.trim(e.substr(i+1)),t){if(s[t]&&Ll.indexOf(t)>=0)return;s[t]="set-cookie"===t?(s[t]?s[t]:[]).concat([r]):s[t]?s[t]+", "+r:r}})),s):s},ql=Il,Wl=Cl,Vl=function(e){return new Promise((function(t,r){var i=e.data,s=e.headers,n=e.responseType;Al.isFormData(i)&&delete s["Content-Type"];var o=new XMLHttpRequest;if(e.auth){var a=e.auth.username||"",c=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";s.Authorization="Basic "+btoa(a+":"+c)}var d=Bl(e.baseURL,e.url);function l(){if(o){var i="getAllResponseHeaders"in o?Ul(o.getAllResponseHeaders()):null,s={data:n&&"text"!==n&&"json"!==n?o.response:o.responseText,status:o.status,statusText:o.statusText,headers:i,config:e,request:o};jl(t,r,s),o=null}}if(o.open(e.method.toUpperCase(),Nl(d,e.params,e.paramsSerializer),!0),o.timeout=e.timeout,"onloadend"in o?o.onloadend=l:o.onreadystatechange=function(){o&&4===o.readyState&&(0!==o.status||o.responseURL&&0===o.responseURL.indexOf("file:"))&&setTimeout(l)},o.onabort=function(){o&&(r(Wl("Request aborted",e,"ECONNABORTED",o)),o=null)},o.onerror=function(){r(Wl("Network Error",e,null,o)),o=null},o.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(Wl(t,e,e.transitional&&e.transitional.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",o)),o=null},Al.isStandardBrowserEnv()){var p=(e.withCredentials||ql(d))&&e.xsrfCookieName?Fl.read(e.xsrfCookieName):void 0;p&&(s[e.xsrfHeaderName]=p)}"setRequestHeader"in o&&Al.forEach(s,(function(e,t){void 0===i&&"content-type"===t.toLowerCase()?delete s[t]:o.setRequestHeader(t,e)})),Al.isUndefined(e.withCredentials)||(o.withCredentials=!!e.withCredentials),n&&"json"!==n&&(o.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&o.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&o.upload&&o.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){o&&(o.abort(),r(e),o=null)})),i||(i=null),o.send(i)}))},zl=ml,$l=function(e,t){Sl.forEach(e,(function(r,i){i!==t&&i.toUpperCase()===t.toUpperCase()&&(e[t]=r,delete e[i])}))},Gl=kl,Hl={"Content-Type":"application/x-www-form-urlencoded"};function Jl(e,t){!zl.isUndefined(e)&&zl.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var Kl,Ql={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(Kl=Vl),Kl),transformRequest:[function(e,t){return $l(t,"Accept"),$l(t,"Content-Type"),zl.isFormData(e)||zl.isArrayBuffer(e)||zl.isBuffer(e)||zl.isStream(e)||zl.isFile(e)||zl.isBlob(e)?e:zl.isArrayBufferView(e)?e.buffer:zl.isURLSearchParams(e)?(Jl(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):zl.isObject(e)||t&&"application/json"===t["Content-Type"]?(Jl(t,"application/json"),function(e,t,r){if(zl.isString(e))try{return(t||JSON.parse)(e),zl.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional,r=t&&t.silentJSONParsing,i=t&&t.forcedJSONParsing,s=!r&&"json"===this.responseType;if(s||i&&zl.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(s){if("SyntaxError"===e.name)throw Gl(e,this,"E_JSON_PARSE");throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300}};Ql.headers={common:{Accept:"application/json, text/plain, */*"}},zl.forEach(["delete","get","head"],(function(e){Ql.headers[e]={}})),zl.forEach(["post","put","patch"],(function(e){Ql.headers[e]=zl.merge(Hl)}));var Xl=Ql,Yl=ml,Zl=Xl,ep=function(e){return!(!e||!e.__CANCEL__)},tp=ml,rp=function(e,t,r){var i=this||Zl;return Yl.forEach(r,(function(r){e=r.call(i,e,t)})),e},ip=ep,sp=Xl;function np(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var op=ml,ap=function(e,t){t=t||{};var r={},i=["url","method","data"],s=["headers","auth","proxy","params"],n=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],o=["validateStatus"];function a(e,t){return op.isPlainObject(e)&&op.isPlainObject(t)?op.merge(e,t):op.isPlainObject(t)?op.merge({},t):op.isArray(t)?t.slice():t}function c(i){op.isUndefined(t[i])?op.isUndefined(e[i])||(r[i]=a(void 0,e[i])):r[i]=a(e[i],t[i])}op.forEach(i,(function(e){op.isUndefined(t[e])||(r[e]=a(void 0,t[e]))})),op.forEach(s,c),op.forEach(n,(function(i){op.isUndefined(t[i])?op.isUndefined(e[i])||(r[i]=a(void 0,e[i])):r[i]=a(void 0,t[i])})),op.forEach(o,(function(i){i in t?r[i]=a(e[i],t[i]):i in e&&(r[i]=a(void 0,e[i]))}));var d=i.concat(s).concat(n).concat(o),l=Object.keys(e).concat(Object.keys(t)).filter((function(e){return-1===d.indexOf(e)}));return op.forEach(l,c),r},cp={name:"axios",version:"0.21.4",description:"Promise based HTTP client for the browser and node.js",main:"index.js",scripts:{test:"grunt test",start:"node ./sandbox/server.js",build:"NODE_ENV=production grunt build",preversion:"npm test",version:"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json",postversion:"git push && git push --tags",examples:"node ./examples/server.js",coveralls:"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",fix:"eslint --fix lib/**/*.js"},repository:{type:"git",url:"https://github.com/axios/axios.git"},keywords:["xhr","http","ajax","promise","node"],author:"Matt Zabriskie",license:"MIT",bugs:{url:"https://github.com/axios/axios/issues"},homepage:"https://axios-http.com",devDependencies:{coveralls:"^3.0.0","es6-promise":"^4.2.4",grunt:"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1",karma:"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2",minimist:"^1.2.0",mocha:"^8.2.1",sinon:"^4.5.0","terser-webpack-plugin":"^4.2.3",typescript:"^4.0.5","url-search-params":"^0.10.0",webpack:"^4.44.2","webpack-dev-server":"^3.11.0"},browser:{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},jsdelivr:"dist/axios.min.js",unpkg:"dist/axios.min.js",typings:"./index.d.ts",dependencies:{"follow-redirects":"^1.14.0"},bundlesize:[{path:"./dist/axios.min.js",threshold:"5kB"}]},dp={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){dp[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));var lp={},pp=cp.version.split(".");function up(e,t){for(var r=t?t.split("."):pp,i=e.split("."),s=0;s<3;s++){if(r[s]>i[s])return!0;if(r[s]<i[s])return!1}return!1}dp.transitional=function(e,t,r){var i=t&&up(t);function s(e,t){return"[Axios v"+cp.version+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,n,o){if(!1===e)throw new Error(s(n," has been removed in "+t));return i&&!lp[n]&&(lp[n]=!0,console.warn(s(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,o)}};var hp={isOlderVersion:up,assertOptions:function(e,t,r){if("object"!=typeof e)throw new TypeError("options must be an object");for(var i=Object.keys(e),s=i.length;s-- >0;){var n=i[s],o=t[n];if(o){var a=e[n],c=void 0===a||o(a,n,e);if(!0!==c)throw new TypeError("option "+n+" must be "+c)}else if(!0!==r)throw Error("Unknown option "+n)}},validators:dp},fp=ml,mp=yl,gp=_l,vp=function(e){return np(e),e.headers=e.headers||{},e.data=rp.call(e,e.data,e.headers,e.transformRequest),e.headers=tp.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),tp.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||sp.adapter)(e).then((function(t){return np(e),t.data=rp.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return ip(t)||(np(e),t&&t.response&&(t.response.data=rp.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},yp=ap,bp=hp,wp=bp.validators;function _p(e){this.defaults=e,this.interceptors={request:new gp,response:new gp}}_p.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=yp(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=e.transitional;void 0!==t&&bp.assertOptions(t,{silentJSONParsing:wp.transitional(wp.boolean,"1.0.0"),forcedJSONParsing:wp.transitional(wp.boolean,"1.0.0"),clarifyTimeoutError:wp.transitional(wp.boolean,"1.0.0")},!1);var r=[],i=!0;this.interceptors.request.forEach((function(t){"function"==typeof t.runWhen&&!1===t.runWhen(e)||(i=i&&t.synchronous,r.unshift(t.fulfilled,t.rejected))}));var s,n=[];if(this.interceptors.response.forEach((function(e){n.push(e.fulfilled,e.rejected)})),!i){var o=[vp,void 0];for(Array.prototype.unshift.apply(o,r),o=o.concat(n),s=Promise.resolve(e);o.length;)s=s.then(o.shift(),o.shift());return s}for(var a=e;r.length;){var c=r.shift(),d=r.shift();try{a=c(a)}catch(e){d(e);break}}try{s=vp(a)}catch(e){return Promise.reject(e)}for(;n.length;)s=s.then(n.shift(),n.shift());return s},_p.prototype.getUri=function(e){return e=yp(this.defaults,e),mp(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},fp.forEach(["delete","get","head","options"],(function(e){_p.prototype[e]=function(t,r){return this.request(yp(r||{},{method:e,url:t,data:(r||{}).data}))}})),fp.forEach(["post","put","patch"],(function(e){_p.prototype[e]=function(t,r,i){return this.request(yp(i||{},{method:e,url:t,data:r}))}}));var Sp=_p;function kp(e){this.message=e}kp.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},kp.prototype.__CANCEL__=!0;var Rp=kp,Cp=Rp;function Pp(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var r=this;e((function(e){r.reason||(r.reason=new Cp(e),t(r.reason))}))}Pp.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},Pp.source=function(){var e,t=new Pp((function(t){e=t}));return{token:t,cancel:e}};var Tp=Pp,Ep=ml,Dp=ol,xp=Sp,Mp=ap;function Lp(e){var t=new xp(e),r=Dp(xp.prototype.request,t);return Ep.extend(r,xp.prototype,t),Ep.extend(r,t),r}var Op=Lp(Xl);Op.Axios=xp,Op.create=function(e){return Lp(Mp(Op.defaults,e))},Op.Cancel=Rp,Op.CancelToken=Tp,Op.isCancel=ep,Op.all=function(e){return Promise.all(e)},Op.spread=function(e){return function(t){return e.apply(null,t)}},Op.isAxiosError=function(e){return"object"==typeof e&&!0===e.isAxiosError},nl.exports=Op,nl.exports.default=Op;var Ip=nl.exports,Ap="undefined"!=typeof Symbol&&Symbol,jp=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var s=Object.getOwnPropertyDescriptor(e,t);if(42!==s.value||!0!==s.enumerable)return!1}return!0},Fp="Function.prototype.bind called on incompatible ",Np=Array.prototype.slice,Bp=Object.prototype.toString,Up=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==Bp.call(t))throw new TypeError(Fp+t);for(var r,i=Np.call(arguments,1),s=function(){if(this instanceof r){var s=t.apply(this,i.concat(Np.call(arguments)));return Object(s)===s?s:this}return t.apply(e,i.concat(Np.call(arguments)))},n=Math.max(0,t.length-i.length),o=[],a=0;a<n;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(s),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},qp=Function.prototype.bind||Up,Wp=qp.call(Function.call,Object.prototype.hasOwnProperty),Vp=SyntaxError,zp=Function,$p=TypeError,Gp=function(e){try{return zp('"use strict"; return ('+e+").constructor;")()}catch(e){}},Hp=Object.getOwnPropertyDescriptor;if(Hp)try{Hp({},"")}catch(sc){Hp=null}var Jp=function(){throw new $p},Kp=Hp?function(){try{return Jp}catch(e){try{return Hp(arguments,"callee").get}catch(e){return Jp}}}():Jp,Qp="function"==typeof Ap&&"function"==typeof Symbol&&"symbol"==typeof Ap("foo")&&"symbol"==typeof Symbol("bar")&&jp(),Xp=Object.getPrototypeOf||function(e){return e.__proto__},Yp={},Zp="undefined"==typeof Uint8Array?undefined:Xp(Uint8Array),eu={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":Qp?Xp([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":Yp,"%AsyncGenerator%":Yp,"%AsyncGeneratorFunction%":Yp,"%AsyncIteratorPrototype%":Yp,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":zp,"%GeneratorFunction%":Yp,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Qp?Xp(Xp([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&Qp?Xp((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&Qp?Xp((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Qp?Xp(""[Symbol.iterator]()):undefined,"%Symbol%":Qp?Symbol:undefined,"%SyntaxError%":Vp,"%ThrowTypeError%":Kp,"%TypedArray%":Zp,"%TypeError%":$p,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet},tu=function e(t){var r;if("%AsyncFunction%"===t)r=Gp("async function () {}");else if("%GeneratorFunction%"===t)r=Gp("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=Gp("async function* () {}");else if("%AsyncGenerator%"===t){var i=e("%AsyncGeneratorFunction%");i&&(r=i.prototype)}else if("%AsyncIteratorPrototype%"===t){var s=e("%AsyncGenerator%");s&&(r=Xp(s.prototype))}return eu[t]=r,r},ru={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},iu=qp,su=Wp,nu=iu.call(Function.call,Array.prototype.concat),ou=iu.call(Function.apply,Array.prototype.splice),au=iu.call(Function.call,String.prototype.replace),cu=iu.call(Function.call,String.prototype.slice),du=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,lu=/\\(\\)?/g,pu=function(e){var t=cu(e,0,1),r=cu(e,-1);if("%"===t&&"%"!==r)throw new Vp("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new Vp("invalid intrinsic syntax, expected opening `%`");var i=[];return au(e,du,(function(e,t,r,s){i[i.length]=r?au(s,lu,"$1"):t||e})),i},uu=function(e,t){var r,i=e;if(su(ru,i)&&(i="%"+(r=ru[i])[0]+"%"),su(eu,i)){var s=eu[i];if(s===Yp&&(s=tu(i)),void 0===s&&!t)throw new $p("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:i,value:s}}throw new Vp("intrinsic "+e+" does not exist!")},hu=function(e,t){if("string"!=typeof e||0===e.length)throw new $p("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new $p('"allowMissing" argument must be a boolean');var r=pu(e),i=r.length>0?r[0]:"",s=uu("%"+i+"%",t),n=s.name,o=s.value,a=!1,c=s.alias;c&&(i=c[0],ou(r,nu([0,1],c)));for(var d=1,l=!0;d<r.length;d+=1){var p=r[d],u=cu(p,0,1),h=cu(p,-1);if(('"'===u||"'"===u||"`"===u||'"'===h||"'"===h||"`"===h)&&u!==h)throw new Vp("property names with quotes must have matching quotes");if("constructor"!==p&&l||(a=!0),su(eu,n="%"+(i+="."+p)+"%"))o=eu[n];else if(null!=o){if(!(p in o)){if(!t)throw new $p("base intrinsic for "+e+" exists, but the property is not available.");return}if(Hp&&d+1>=r.length){var f=Hp(o,p);o=(l=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:o[p]}else l=su(o,p),o=o[p];l&&!a&&(eu[n]=o)}}return o},fu={exports:{}};!function(e){var t=qp,r=hu,i=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),n=r("%Reflect.apply%",!0)||t.call(s,i),o=r("%Object.getOwnPropertyDescriptor%",!0),a=r("%Object.defineProperty%",!0),c=r("%Math.max%");if(a)try{a({},"a",{value:1})}catch(e){a=null}e.exports=function(e){var r=n(t,s,arguments);if(o&&a){var i=o(r,"length");i.configurable&&a(r,"length",{value:1+c(0,e.length-(arguments.length-1))})}return r};var d=function(){return n(t,i,arguments)};a?a(e.exports,"apply",{value:d}):e.exports.apply=d}(fu);var mu=hu,gu=fu.exports,vu=gu(mu("String.prototype.indexOf")),yu=c(Object.freeze({__proto__:null,default:{}})),bu="function"==typeof Map&&Map.prototype,wu=Object.getOwnPropertyDescriptor&&bu?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,_u=bu&&wu&&"function"==typeof wu.get?wu.get:null,Su=bu&&Map.prototype.forEach,ku="function"==typeof Set&&Set.prototype,Ru=Object.getOwnPropertyDescriptor&&ku?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,Cu=ku&&Ru&&"function"==typeof Ru.get?Ru.get:null,Pu=ku&&Set.prototype.forEach,Tu="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,Eu="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,Du="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,xu=Boolean.prototype.valueOf,Mu=Object.prototype.toString,Lu=Function.prototype.toString,Ou=String.prototype.match,Iu="function"==typeof BigInt?BigInt.prototype.valueOf:null,Au=Object.getOwnPropertySymbols,ju="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Fu="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Nu=Object.prototype.propertyIsEnumerable,Bu=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),Uu=yu.custom,qu=Uu&&Gu(Uu)?Uu:null,Wu="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function Vu(e,t,r){var i="double"===(r.quoteStyle||t)?'"':"'";return i+e+i}function zu(e){return String(e).replace(/"/g,"&quot;")}function $u(e){return!("[object Array]"!==Ku(e)||Wu&&"object"==typeof e&&Wu in e)}function Gu(e){if(Fu)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!ju)return!1;try{return ju.call(e),!0}catch(e){}return!1}var Hu=Object.prototype.hasOwnProperty||function(e){return e in this};function Ju(e,t){return Hu.call(e,t)}function Ku(e){return Mu.call(e)}function Qu(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,i=e.length;r<i;r++)if(e[r]===t)return r;return-1}function Xu(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,i="... "+r+" more character"+(r>1?"s":"");return Xu(e.slice(0,t.maxStringLength),t)+i}return Vu(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,Yu),"single",t)}function Yu(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+t.toString(16).toUpperCase()}function Zu(e){return"Object("+e+")"}function eh(e){return e+" { ? }"}function th(e,t,r,i){return e+" ("+t+") {"+(i?rh(r,i):r.join(", "))+"}"}function rh(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function ih(e,t){var r=$u(e),i=[];if(r){i.length=e.length;for(var s=0;s<e.length;s++)i[s]=Ju(e,s)?t(e[s],e):""}var n,o="function"==typeof Au?Au(e):[];if(Fu){n={};for(var a=0;a<o.length;a++)n["$"+o[a]]=o[a]}for(var c in e)Ju(e,c)&&(r&&String(Number(c))===c&&c<e.length||Fu&&n["$"+c]instanceof Symbol||(/[^\w$]/.test(c)?i.push(t(c,e)+": "+t(e[c],e)):i.push(c+": "+t(e[c],e))));if("function"==typeof Au)for(var d=0;d<o.length;d++)Nu.call(e,o[d])&&i.push("["+t(o[d])+"]: "+t(e[o[d]],e));return i}var sh=hu,nh=function(e,t){var r=mu(e,!!t);return"function"==typeof r&&vu(e,".prototype.")>-1?gu(r):r},oh=function e(t,r,i,s){var n=r||{};if(Ju(n,"quoteStyle")&&"single"!==n.quoteStyle&&"double"!==n.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Ju(n,"maxStringLength")&&("number"==typeof n.maxStringLength?n.maxStringLength<0&&n.maxStringLength!==1/0:null!==n.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=!Ju(n,"customInspect")||n.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Ju(n,"indent")&&null!==n.indent&&"\t"!==n.indent&&!(parseInt(n.indent,10)===n.indent&&n.indent>0))throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return Xu(t,n);if("number"==typeof t)return 0===t?1/0/t>0?"0":"-0":String(t);if("bigint"==typeof t)return String(t)+"n";var a=void 0===n.depth?5:n.depth;if(void 0===i&&(i=0),i>=a&&a>0&&"object"==typeof t)return $u(t)?"[Array]":"[Object]";var c=function(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=Array(e.indent+1).join(" ")}return{base:r,prev:Array(t+1).join(r)}}(n,i);if(void 0===s)s=[];else if(Qu(s,t)>=0)return"[Circular]";function d(t,r,o){if(r&&(s=s.slice()).push(r),o){var a={depth:n.depth};return Ju(n,"quoteStyle")&&(a.quoteStyle=n.quoteStyle),e(t,a,i+1,s)}return e(t,n,i+1,s)}if("function"==typeof t){var l=function(e){if(e.name)return e.name;var t=Ou.call(Lu.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),p=ih(t,d);return"[Function"+(l?": "+l:" (anonymous)")+"]"+(p.length>0?" { "+p.join(", ")+" }":"")}if(Gu(t)){var u=Fu?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):ju.call(t);return"object"!=typeof t||Fu?u:Zu(u)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var h="<"+String(t.nodeName).toLowerCase(),f=t.attributes||[],m=0;m<f.length;m++)h+=" "+f[m].name+"="+Vu(zu(f[m].value),"double",n);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if($u(t)){if(0===t.length)return"[]";var g=ih(t,d);return c&&!function(e){for(var t=0;t<e.length;t++)if(Qu(e[t],"\n")>=0)return!1;return!0}(g)?"["+rh(g,c)+"]":"[ "+g.join(", ")+" ]"}if(function(e){return!("[object Error]"!==Ku(e)||Wu&&"object"==typeof e&&Wu in e)}(t)){var v=ih(t,d);return 0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+v.join(", ")+" }"}if("object"==typeof t&&o){if(qu&&"function"==typeof t[qu])return t[qu]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!_u||!e||"object"!=typeof e)return!1;try{_u.call(e);try{Cu.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var y=[];return Su.call(t,(function(e,r){y.push(d(r,t,!0)+" => "+d(e,t))})),th("Map",_u.call(t),y,c)}if(function(e){if(!Cu||!e||"object"!=typeof e)return!1;try{Cu.call(e);try{_u.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var b=[];return Pu.call(t,(function(e){b.push(d(e,t))})),th("Set",Cu.call(t),b,c)}if(function(e){if(!Tu||!e||"object"!=typeof e)return!1;try{Tu.call(e,Tu);try{Eu.call(e,Eu)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return eh("WeakMap");if(function(e){if(!Eu||!e||"object"!=typeof e)return!1;try{Eu.call(e,Eu);try{Tu.call(e,Tu)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return eh("WeakSet");if(function(e){if(!Du||!e||"object"!=typeof e)return!1;try{return Du.call(e),!0}catch(e){}return!1}(t))return eh("WeakRef");if(function(e){return!("[object Number]"!==Ku(e)||Wu&&"object"==typeof e&&Wu in e)}(t))return Zu(d(Number(t)));if(function(e){if(!e||"object"!=typeof e||!Iu)return!1;try{return Iu.call(e),!0}catch(e){}return!1}(t))return Zu(d(Iu.call(t)));if(function(e){return!("[object Boolean]"!==Ku(e)||Wu&&"object"==typeof e&&Wu in e)}(t))return Zu(xu.call(t));if(function(e){return!("[object String]"!==Ku(e)||Wu&&"object"==typeof e&&Wu in e)}(t))return Zu(d(String(t)));if(!function(e){return!("[object Date]"!==Ku(e)||Wu&&"object"==typeof e&&Wu in e)}(t)&&!function(e){return!("[object RegExp]"!==Ku(e)||Wu&&"object"==typeof e&&Wu in e)}(t)){var w=ih(t,d),_=Bu?Bu(t)===Object.prototype:t instanceof Object||t.constructor===Object,S=t instanceof Object?"":"null prototype",k=!_&&Wu&&Object(t)===t&&Wu in t?Ku(t).slice(8,-1):S?"Object":"",R=(_||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(k||S?"["+[].concat(k||[],S||[]).join(": ")+"] ":"");return 0===w.length?R+"{}":c?R+"{"+rh(w,c)+"}":R+"{ "+w.join(", ")+" }"}return String(t)},ah=sh("%TypeError%"),ch=sh("%WeakMap%",!0),dh=sh("%Map%",!0),lh=nh("WeakMap.prototype.get",!0),ph=nh("WeakMap.prototype.set",!0),uh=nh("WeakMap.prototype.has",!0),hh=nh("Map.prototype.get",!0),fh=nh("Map.prototype.set",!0),mh=nh("Map.prototype.has",!0),gh=function(e,t){for(var r,i=e;null!==(r=i.next);i=r)if(r.key===t)return i.next=r.next,r.next=e.next,e.next=r,r},vh=String.prototype.replace,yh=/%20/g,bh="RFC3986",wh={default:bh,formatters:{RFC1738:function(e){return vh.call(e,yh,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:bh},_h=wh,Sh=Object.prototype.hasOwnProperty,kh=Array.isArray,Rh=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),Ch=function(e,t){for(var r=t&&t.plainObjects?Object.create(null):{},i=0;i<e.length;++i)void 0!==e[i]&&(r[i]=e[i]);return r},Ph={arrayToObject:Ch,assign:function(e,t){return Object.keys(t).reduce((function(e,r){return e[r]=t[r],e}),e)},combine:function(e,t){return[].concat(e,t)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],r=[],i=0;i<t.length;++i)for(var s=t[i],n=s.obj[s.prop],o=Object.keys(n),a=0;a<o.length;++a){var c=o[a],d=n[c];"object"==typeof d&&null!==d&&-1===r.indexOf(d)&&(t.push({obj:n,prop:c}),r.push(d))}return function(e){for(;e.length>1;){var t=e.pop(),r=t.obj[t.prop];if(kh(r)){for(var i=[],s=0;s<r.length;++s)void 0!==r[s]&&i.push(r[s]);t.obj[t.prop]=i}}}(t),e},decode:function(e,t,r){var i=e.replace(/\+/g," ");if("iso-8859-1"===r)return i.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(i)}catch(e){return i}},encode:function(e,t,r,i,s){if(0===e.length)return e;var n=e;if("symbol"==typeof e?n=Symbol.prototype.toString.call(e):"string"!=typeof e&&(n=String(e)),"iso-8859-1"===r)return escape(n).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var o="",a=0;a<n.length;++a){var c=n.charCodeAt(a);45===c||46===c||95===c||126===c||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===_h.RFC1738&&(40===c||41===c)?o+=n.charAt(a):c<128?o+=Rh[c]:c<2048?o+=Rh[192|c>>6]+Rh[128|63&c]:c<55296||c>=57344?o+=Rh[224|c>>12]+Rh[128|c>>6&63]+Rh[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&n.charCodeAt(a)),o+=Rh[240|c>>18]+Rh[128|c>>12&63]+Rh[128|c>>6&63]+Rh[128|63&c])}return o},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(kh(e)){for(var r=[],i=0;i<e.length;i+=1)r.push(t(e[i]));return r}return t(e)},merge:function e(t,r,i){if(!r)return t;if("object"!=typeof r){if(kh(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(i&&(i.plainObjects||i.allowPrototypes)||!Sh.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var s=t;return kh(t)&&!kh(r)&&(s=Ch(t,i)),kh(t)&&kh(r)?(r.forEach((function(r,s){if(Sh.call(t,s)){var n=t[s];n&&"object"==typeof n&&r&&"object"==typeof r?t[s]=e(n,r,i):t.push(r)}else t[s]=r})),t):Object.keys(r).reduce((function(t,s){var n=r[s];return Sh.call(t,s)?t[s]=e(t[s],n,i):t[s]=n,t}),s)}},Th=function(){var e,t,r,i={assert:function(e){if(!i.has(e))throw new ah("Side channel does not contain "+oh(e))},get:function(i){if(ch&&i&&("object"==typeof i||"function"==typeof i)){if(e)return lh(e,i)}else if(dh){if(t)return hh(t,i)}else if(r)return function(e,t){var r=gh(e,t);return r&&r.value}(r,i)},has:function(i){if(ch&&i&&("object"==typeof i||"function"==typeof i)){if(e)return uh(e,i)}else if(dh){if(t)return mh(t,i)}else if(r)return function(e,t){return!!gh(e,t)}(r,i);return!1},set:function(i,s){ch&&i&&("object"==typeof i||"function"==typeof i)?(e||(e=new ch),ph(e,i,s)):dh?(t||(t=new dh),fh(t,i,s)):(r||(r={key:{},next:null}),function(e,t,r){var i=gh(e,t);i?i.value=r:e.next={key:t,next:e.next,value:r}}(r,i,s))}};return i},Eh=Ph,Dh=wh,xh=Object.prototype.hasOwnProperty,Mh={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},Lh=Array.isArray,Oh=String.prototype.split,Ih=Array.prototype.push,Ah=function(e,t){Ih.apply(e,Lh(t)?t:[t])},jh=Date.prototype.toISOString,Fh=Dh.default,Nh={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Eh.encode,encodeValuesOnly:!1,format:Fh,formatter:Dh.formatters[Fh],indices:!1,serializeDate:function(e){return jh.call(e)},skipNulls:!1,strictNullHandling:!1},Bh={},Uh=function e(t,r,i,s,n,o,a,c,d,l,p,u,h,f,m,g){for(var v=t,y=g,b=0,w=!1;void 0!==(y=y.get(Bh))&&!w;){var _=y.get(t);if(b+=1,void 0!==_){if(_===b)throw new RangeError("Cyclic object value");w=!0}void 0===y.get(Bh)&&(b=0)}if("function"==typeof c?v=c(r,v):v instanceof Date?v=p(v):"comma"===i&&Lh(v)&&(v=Eh.maybeMap(v,(function(e){return e instanceof Date?p(e):e}))),null===v){if(n)return a&&!f?a(r,Nh.encoder,m,"key",u):r;v=""}if(function(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}(v)||Eh.isBuffer(v)){if(a){var S=f?r:a(r,Nh.encoder,m,"key",u);if("comma"===i&&f){for(var k=Oh.call(String(v),","),R="",C=0;C<k.length;++C)R+=(0===C?"":",")+h(a(k[C],Nh.encoder,m,"value",u));return[h(S)+(s&&Lh(v)&&1===k.length?"[]":"")+"="+R]}return[h(S)+"="+h(a(v,Nh.encoder,m,"value",u))]}return[h(r)+"="+h(String(v))]}var P,T=[];if(void 0===v)return T;if("comma"===i&&Lh(v))P=[{value:v.length>0?v.join(",")||null:void 0}];else if(Lh(c))P=c;else{var E=Object.keys(v);P=d?E.sort(d):E}for(var D=s&&Lh(v)&&1===v.length?r+"[]":r,x=0;x<P.length;++x){var M=P[x],L="object"==typeof M&&void 0!==M.value?M.value:v[M];if(!o||null!==L){var O=Lh(v)?"function"==typeof i?i(D,M):D:D+(l?"."+M:"["+M+"]");g.set(t,b);var I=Th();I.set(Bh,g),Ah(T,e(L,O,i,s,n,o,a,c,d,l,p,u,h,f,m,I))}}return T},qh=Ph,Wh=Object.prototype.hasOwnProperty,Vh=Array.isArray,zh={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:qh.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},$h=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},Gh=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},Hh=function(e,t,r,i){if(e){var s=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,n=/(\[[^[\]]*])/g,o=r.depth>0&&/(\[[^[\]]*])/.exec(s),a=o?s.slice(0,o.index):s,c=[];if(a){if(!r.plainObjects&&Wh.call(Object.prototype,a)&&!r.allowPrototypes)return;c.push(a)}for(var d=0;r.depth>0&&null!==(o=n.exec(s))&&d<r.depth;){if(d+=1,!r.plainObjects&&Wh.call(Object.prototype,o[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(o[1])}return o&&c.push("["+s.slice(o.index)+"]"),function(e,t,r,i){for(var s=i?t:Gh(t,r),n=e.length-1;n>=0;--n){var o,a=e[n];if("[]"===a&&r.parseArrays)o=[].concat(s);else{o=r.plainObjects?Object.create(null):{};var c="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,d=parseInt(c,10);r.parseArrays||""!==c?!isNaN(d)&&a!==c&&String(d)===c&&d>=0&&r.parseArrays&&d<=r.arrayLimit?(o=[])[d]=s:"__proto__"!==c&&(o[c]=s):o={0:s}}s=o}return s}(c,t,r,i)}},Jh=function(e,t){var r,i=e,s=function(e){if(!e)return Nh;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||Nh.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var r=Dh.default;if(void 0!==e.format){if(!xh.call(Dh.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var i=Dh.formatters[r],s=Nh.filter;return("function"==typeof e.filter||Lh(e.filter))&&(s=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Nh.addQueryPrefix,allowDots:void 0===e.allowDots?Nh.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Nh.charsetSentinel,delimiter:void 0===e.delimiter?Nh.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Nh.encode,encoder:"function"==typeof e.encoder?e.encoder:Nh.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Nh.encodeValuesOnly,filter:s,format:r,formatter:i,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Nh.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Nh.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Nh.strictNullHandling}}(t);"function"==typeof s.filter?i=(0,s.filter)("",i):Lh(s.filter)&&(r=s.filter);var n,o=[];if("object"!=typeof i||null===i)return"";n=t&&t.arrayFormat in Mh?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=Mh[n];if(t&&"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var c="comma"===a&&t&&t.commaRoundTrip;r||(r=Object.keys(i)),s.sort&&r.sort(s.sort);for(var d=Th(),l=0;l<r.length;++l){var p=r[l];s.skipNulls&&null===i[p]||Ah(o,Uh(i[p],p,a,c,s.strictNullHandling,s.skipNulls,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,d))}var u=o.join(s.delimiter),h=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""},Kh=function(e,t){var r=function(e){if(!e)return zh;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?zh.charset:e.charset;return{allowDots:void 0===e.allowDots?zh.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:zh.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:zh.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:zh.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:zh.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:zh.comma,decoder:"function"==typeof e.decoder?e.decoder:zh.decoder,delimiter:"string"==typeof e.delimiter||qh.isRegExp(e.delimiter)?e.delimiter:zh.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:zh.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:zh.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:zh.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:zh.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:zh.strictNullHandling}}(t);if(""===e||null==e)return r.plainObjects?Object.create(null):{};for(var i="string"==typeof e?function(e,t){var r,i={},s=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,n=t.parameterLimit===1/0?void 0:t.parameterLimit,o=s.split(t.delimiter,n),a=-1,c=t.charset;if(t.charsetSentinel)for(r=0;r<o.length;++r)0===o[r].indexOf("utf8=")&&("utf8=%E2%9C%93"===o[r]?c="utf-8":"utf8=%26%2310003%3B"===o[r]&&(c="iso-8859-1"),a=r,r=o.length);for(r=0;r<o.length;++r)if(r!==a){var d,l,p=o[r],u=p.indexOf("]="),h=-1===u?p.indexOf("="):u+1;-1===h?(d=t.decoder(p,zh.decoder,c,"key"),l=t.strictNullHandling?null:""):(d=t.decoder(p.slice(0,h),zh.decoder,c,"key"),l=qh.maybeMap(Gh(p.slice(h+1),t),(function(e){return t.decoder(e,zh.decoder,c,"value")}))),l&&t.interpretNumericEntities&&"iso-8859-1"===c&&(l=$h(l)),p.indexOf("[]=")>-1&&(l=Vh(l)?[l]:l),Wh.call(i,d)?i[d]=qh.combine(i[d],l):i[d]=l}return i}(e,r):e,s=r.plainObjects?Object.create(null):{},n=Object.keys(i),o=0;o<n.length;++o){var a=n[o],c=Hh(a,i[a],r,"string"==typeof e);s=qh.merge(s,c,r)}return!0===r.allowSparse?s:qh.compact(s)},Qh={formats:wh,parse:Kh,stringify:Jh};class Xh{constructor(e){const{baseURL:t,timeout:r,customNode:i}=e;this.api=Ip.create({baseURL:t||"https://lb.livedigital.space/v1",timeout:r||5e3,withCredentials:!1,paramsSerializer:e=>Qh.stringify(e)}),this.customNode=i}getNode(e){return r(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 Yh{createSystem(e){return new Nc(e)}createMedia(e){return new Za(e)}createNetwork(e){const{loadbalancer:t,logLevel:r,onLogMessage:i}=e,s=new sl({logLevel:r,onLogMessage:i}),n=new Xh(t);return new jc({logLevel:r,socketClient:s,loadBalancerApiClient:n,onLogMessage:i})}createChannelEventHandler(e){return new Bc(e)}createMediaSoupEventHandler(e){return new Uc(e)}createIssueDetector(e){var t,r;const i=null!==(t=e.logger)&&void 0!==t?t:console,s=new Oc({statsParser:new Ic({logger:null!==(r=e.logger)&&void 0!==r?r:console})});return new Ac({issueEmitter:new yc,networkScoresCalculator:new _c,detectors:[new Dc,new Rc,new Cc,new Pc,new Ec,new Tc,new kc,new xc],statsReporter:new bc({compositeStatsParser:s,getStatsInterval:5e3}),onIssues:e.onIssues,onNetworkScoresUpdated:e.onNetworkScoresUpdated,ignoreSSRCList:e.ignoreSSRCList,compositeStatsParser:s,logger:i})}}class Zh{constructor(e){var t,r;const{observer:i,network:s,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:c,logLevel:d,disableWid:l}=e;this._observer=null!=i?i:new n;const p=new Yh;this.engine=new rc({dependenciesFactory:p,clientEventEmitter:this.observer,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:d,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:c,disableWid:l})}get observer(){return this._observer}get id(){return this.engine.mySocketId}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}detectDevices(){return r(this,void 0,void 0,(function*(){return yield this.engine.system.detectDevices(),{video:this.engine.system.availableVideoDevices,audio:this.engine.system.availableAudioDevices}}))}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 r(this,void 0,void 0,(function*(){return this.engine.network.getTransportsStateInfo()}))}}export{Zh as default};