@plaso-infi/whiteboard-sdk 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("./index-f6e4fa80.js");function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var i,n={exports:{}};i=n,e.commonjsGlobal,i.exports=function(){function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}let i=!0,n=!0;function r(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function s(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function o(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(i=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function a(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(n=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function c(){if("object"==typeof window){if(i)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function d(e,t){n&&console.warn(e+" is deprecated, please use "+t+" instead.")}function l(e){return"[object Object]"===Object.prototype.toString.call(e)}function h(e){return l(e)?Object.keys(e).reduce((function(t,i){const n=l(e[i]),r=n?h(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function u(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?u(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{u(e,e.get(t),i)}))})))}function p(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&u(e,i,r)}))})),r}const _=c;function E(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),_("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return _("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function m(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function f(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else s(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function g(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function S(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(s(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(r(t)))},i])})).then(i,n)}}function T(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>p(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),s(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>p(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function R(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function C(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return R(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function v(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function I(e,t){s(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var y=Object.freeze({__proto__:null,fixNegotiationNeeded:I,shimAddTrackRemoveTrack:C,shimAddTrackRemoveTrackWithNative:R,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:g,shimGetStats:S,shimGetUserMedia:E,shimMediaStream:m,shimOnTrack:f,shimPeerConnection:v,shimSenderReceiverGetStats:T});function A(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){d("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function b(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function w(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,s)}}function O(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function N(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),s(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function D(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){d("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function P(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function L(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function k(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function M(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function U(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var x=Object.freeze({__proto__:null,shimAddTransceiver:L,shimCreateAnswer:U,shimCreateOffer:M,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:k,shimGetUserMedia:A,shimOnTrack:b,shimPeerConnection:w,shimRTCDataChannel:P,shimReceiverGetStats:N,shimRemoveStream:D,shimSenderGetStats:O});function V(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function F(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function B(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function j(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(G(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function G(e){return e&&void 0!==e.video?Object.assign({},e,{video:h(e.video)}):e}function W(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];!n.hasOwnProperty("urls")&&n.hasOwnProperty("url")?(d("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function H(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function K(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Y(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var q=Object.freeze({__proto__:null,shimAudioContext:Y,shimCallbacksAPI:B,shimConstraints:G,shimCreateOfferLegacy:K,shimGetUserMedia:j,shimLocalStreamsAPI:V,shimRTCIceServerUrls:W,shimRemoteStreamsAPI:F,shimTrackEventTransceiver:H}),J="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==e.commonjsGlobal?e.commonjsGlobal:"undefined"!=typeof self?self:{};function z(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var X={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;return r=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(X);var Q=X.exports,Z=z(Q),$=t({__proto__:null,default:Z},[Q]);function ee(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Z.parseCandidate(e.candidate),r=Object.assign(i,n);return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,s(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function te(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||s(e,"icecandidate",(e=>{if(e.candidate){const t=Z.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function ie(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=function(e){if(!e||!e.sdp)return!1;const t=Z.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Z.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},n=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},s=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=Z.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){const e=n(arguments[0]),t=r(e),i=s(arguments[0],e);let o;o=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>o}),this._sctp=a}return o.apply(this,arguments)}}function ne(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},s(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function re(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function se(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function oe(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ae(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var ce=Object.freeze({__proto__:null,removeExtmapAllowMixed:se,shimAddIceCandidateNullOrEmpty:oe,shimConnectionState:re,shimMaxMessageSize:ie,shimParameterlessSetLocalDescription:ae,shimRTCIceCandidate:ee,shimRTCIceCandidateRelayProtocol:te,shimSendThrowTypeError:ne});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=c,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=r(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=r(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=r(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:n,commonShim:ce,extractVersion:r,disableLog:o,disableWarnings:a,sdp:$};switch(n.browser){case"chrome":if(!y||!v||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=y,oe(e,n),ae(e),E(e,n),m(e),v(e,n),f(e),C(e,n),g(e),S(e),T(e),I(e,n),ee(e),te(e),re(e),ie(e,n),ne(e),se(e,n);break;case"firefox":if(!x||!w||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=x,oe(e,n),ae(e),A(e,n),w(e,n),b(e),D(e),O(e),N(e),P(e),L(e),k(e),M(e),U(e),ee(e),re(e),ie(e,n),ne(e);break;case"safari":if(!q||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=q,oe(e,n),ae(e),W(e),K(e),B(e),V(e),F(e),H(e),j(e),Y(e),ee(e),te(e),ie(e,n),ne(e),se(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var de=function(e){try{return!!e()}catch(e){return!0}},le=!de((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),he=le,ue=Function.prototype,pe=ue.call,_e=he&&ue.bind.bind(pe,pe),Ee=he?_e:function(e){return function(){return pe.apply(e,arguments)}},me=Ee({}.isPrototypeOf),fe=function(e){return e&&e.Math==Math&&e},ge=fe("object"==typeof globalThis&&globalThis)||fe("object"==typeof window&&window)||fe("object"==typeof self&&self)||fe("object"==typeof J&&J)||function(){return this}()||J||Function("return this")(),Se=le,Te=Function.prototype,Re=Te.apply,Ce=Te.call,ve="object"==typeof Reflect&&Reflect.apply||(Se?Ce.bind(Re):function(){return Ce.apply(Re,arguments)}),Ie=Ee,ye=Ie({}.toString),Ae=Ie("".slice),be=function(e){return Ae(ye(e),8,-1)},we=be,Oe=Ee,Ne=function(e){if("Function"===we(e))return Oe(e)},De="object"==typeof document&&document.all,Pe={all:De,IS_HTMLDDA:void 0===De&&void 0!==De},Le=Pe.all,ke=Pe.IS_HTMLDDA?function(e){return"function"==typeof e||e===Le}:function(e){return"function"==typeof e},Me={},Ue=!de((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),xe=le,Ve=Function.prototype.call,Fe=xe?Ve.bind(Ve):function(){return Ve.apply(Ve,arguments)},Be={},je={}.propertyIsEnumerable,Ge=Object.getOwnPropertyDescriptor,We=Ge&&!je.call({1:2},1);Be.f=We?function(e){var t=Ge(this,e);return!!t&&t.enumerable}:je;var He,Ke,Ye=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},qe=de,Je=be,ze=Object,Xe=Ee("".split),Qe=qe((function(){return!ze("z").propertyIsEnumerable(0)}))?function(e){return"String"==Je(e)?Xe(e,""):ze(e)}:ze,Ze=function(e){return null==e},$e=Ze,et=TypeError,tt=function(e){if($e(e))throw et("Can't call method on "+e);return e},it=Qe,nt=tt,rt=function(e){return it(nt(e))},st=ke,ot=Pe.all,at=Pe.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:st(e)||e===ot}:function(e){return"object"==typeof e?null!==e:st(e)},ct={},dt=ct,lt=ge,ht=ke,ut=function(e){return ht(e)?e:void 0},pt=function(e,t){return arguments.length<2?ut(dt[e])||ut(lt[e]):dt[e]&&dt[e][t]||lt[e]&&lt[e][t]},_t="undefined"!=typeof navigator&&String(navigator.userAgent)||"",Et=ge,mt=_t,ft=Et.process,gt=Et.Deno,St=ft&&ft.versions||gt&&gt.version,Tt=St&&St.v8;Tt&&(Ke=(He=Tt.split("."))[0]>0&&He[0]<4?1:+(He[0]+He[1])),!Ke&&mt&&(!(He=mt.match(/Edge\/(\d+)/))||He[1]>=74)&&(He=mt.match(/Chrome\/(\d+)/))&&(Ke=+He[1]);var Rt=Ke,Ct=Rt,vt=de,It=ge.String,yt=!!Object.getOwnPropertySymbols&&!vt((function(){var e=Symbol();return!It(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Ct&&Ct<41})),At=yt&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,bt=pt,wt=ke,Ot=me,Nt=Object,Dt=At?function(e){return"symbol"==typeof e}:function(e){var t=bt("Symbol");return wt(t)&&Ot(t.prototype,Nt(e))},Pt=String,Lt=function(e){try{return Pt(e)}catch(e){return"Object"}},kt=ke,Mt=Lt,Ut=TypeError,xt=function(e){if(kt(e))return e;throw Ut(Mt(e)+" is not a function")},Vt=xt,Ft=Ze,Bt=function(e,t){var i=e[t];return Ft(i)?void 0:Vt(i)},jt=Fe,Gt=ke,Wt=at,Ht=TypeError,Kt={exports:{}},Yt=ge,qt=Object.defineProperty,Jt=function(e,t){try{qt(Yt,e,{value:t,configurable:!0,writable:!0})}catch(i){Yt[e]=t}return t},zt="__core-js_shared__",Xt=ge[zt]||Jt(zt,{}),Qt=Xt;(Kt.exports=function(e,t){return Qt[e]||(Qt[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Zt=Kt.exports,$t=tt,ei=Object,ti=function(e){return ei($t(e))},ii=ti,ni=Ee({}.hasOwnProperty),ri=Object.hasOwn||function(e,t){return ni(ii(e),t)},si=Ee,oi=0,ai=Math.random(),ci=si(1..toString),di=function(e){return"Symbol("+(void 0===e?"":e)+")_"+ci(++oi+ai,36)},li=Zt,hi=ri,ui=di,pi=yt,_i=At,Ei=ge.Symbol,mi=li("wks"),fi=_i?Ei.for||Ei:Ei&&Ei.withoutSetter||ui,gi=function(e){return hi(mi,e)||(mi[e]=pi&&hi(Ei,e)?Ei[e]:fi("Symbol."+e)),mi[e]},Si=Fe,Ti=at,Ri=Dt,Ci=Bt,vi=function(e,t){var i,n;if("string"===t&&Gt(i=e.toString)&&!Wt(n=jt(i,e)))return n;if(Gt(i=e.valueOf)&&!Wt(n=jt(i,e)))return n;if("string"!==t&&Gt(i=e.toString)&&!Wt(n=jt(i,e)))return n;throw Ht("Can't convert object to primitive value")},Ii=TypeError,yi=gi("toPrimitive"),Ai=function(e,t){if(!Ti(e)||Ri(e))return e;var i,n=Ci(e,yi);if(n){if(void 0===t&&(t="default"),i=Si(n,e,t),!Ti(i)||Ri(i))return i;throw Ii("Can't convert object to primitive value")}return void 0===t&&(t="number"),vi(e,t)},bi=Dt,wi=function(e){var t=Ai(e,"string");return bi(t)?t:t+""},Oi=at,Ni=ge.document,Di=Oi(Ni)&&Oi(Ni.createElement),Pi=function(e){return Di?Ni.createElement(e):{}},Li=Pi,ki=!Ue&&!de((function(){return 7!=Object.defineProperty(Li("div"),"a",{get:function(){return 7}}).a})),Mi=Ue,Ui=Fe,xi=Be,Vi=Ye,Fi=rt,Bi=wi,ji=ri,Gi=ki,Wi=Object.getOwnPropertyDescriptor;Me.f=Mi?Wi:function(e,t){if(e=Fi(e),t=Bi(t),Gi)try{return Wi(e,t)}catch(e){}if(ji(e,t))return Vi(!Ui(xi.f,e,t),e[t])};var Hi=de,Ki=ke,Yi=/#|\.prototype\./,qi=function(e,t){var i=zi[Ji(e)];return i==Qi||i!=Xi&&(Ki(t)?Hi(t):!!t)},Ji=qi.normalize=function(e){return String(e).replace(Yi,".").toLowerCase()},zi=qi.data={},Xi=qi.NATIVE="N",Qi=qi.POLYFILL="P",Zi=qi,$i=xt,en=le,tn=Ne(Ne.bind),nn=function(e,t){return $i(e),void 0===t?e:en?tn(e,t):function(){return e.apply(t,arguments)}},rn={},sn=Ue&&de((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),on=at,an=String,cn=TypeError,dn=function(e){if(on(e))return e;throw cn(an(e)+" is not an object")},ln=Ue,hn=ki,un=sn,pn=dn,_n=wi,En=TypeError,mn=Object.defineProperty,fn=Object.getOwnPropertyDescriptor,gn="enumerable",Sn="configurable",Tn="writable";rn.f=ln?un?function(e,t,i){if(pn(e),t=_n(t),pn(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Tn in i&&!i[Tn]){var n=fn(e,t);n&&n[Tn]&&(e[t]=i.value,i={configurable:Sn in i?i[Sn]:n[Sn],enumerable:gn in i?i[gn]:n[gn],writable:!1})}return mn(e,t,i)}:mn:function(e,t,i){if(pn(e),t=_n(t),pn(i),hn)try{return mn(e,t,i)}catch(e){}if("get"in i||"set"in i)throw En("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Rn=rn,Cn=Ye,vn=Ue?function(e,t,i){return Rn.f(e,t,Cn(1,i))}:function(e,t,i){return e[t]=i,e},In=ge,yn=ve,An=Ne,bn=ke,wn=Me.f,On=Zi,Nn=ct,Dn=nn,Pn=vn,Ln=ri,kn=function(e){var t=function(i,n,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(i);case 2:return new e(i,n)}return new e(i,n,r)}return yn(e,this,arguments)};return t.prototype=e.prototype,t},Mn=function(e,t){var i,n,r,s,o,a,c,d,l,h=e.target,u=e.global,p=e.stat,_=e.proto,E=u?In:p?In[h]:(In[h]||{}).prototype,m=u?Nn:Nn[h]||Pn(Nn,h,{})[h],f=m.prototype;for(s in t)n=!(i=On(u?s:h+(p?".":"#")+s,e.forced))&&E&&Ln(E,s),a=m[s],n&&(c=e.dontCallGetSet?(l=wn(E,s))&&l.value:E[s]),o=n&&c?c:t[s],n&&typeof a==typeof o||(d=e.bind&&n?Dn(o,In):e.wrap&&n?kn(o):_&&bn(o)?An(o):o,(e.sham||o&&o.sham||a&&a.sham)&&Pn(d,"sham",!0),Pn(m,s,d),_&&(Ln(Nn,r=h+"Prototype")||Pn(Nn,r,{}),Pn(Nn[r],s,o),e.real&&f&&(i||!f[s])&&Pn(f,s,o)))},Un=Math.ceil,xn=Math.floor,Vn=Math.trunc||function(e){var t=+e;return(t>0?xn:Un)(t)},Fn=function(e){var t=+e;return t!=t||0===t?0:Vn(t)},Bn=Fn,jn=Math.max,Gn=Math.min,Wn=function(e,t){var i=Bn(e);return i<0?jn(i+t,0):Gn(i,t)},Hn=Fn,Kn=Math.min,Yn=function(e){return e>0?Kn(Hn(e),9007199254740991):0},qn=function(e){return Yn(e.length)},Jn=rt,zn=Wn,Xn=qn,Qn=function(e){return function(t,i,n){var r,s=Jn(t),o=Xn(s),a=zn(n,o);if(e&&i!=i){for(;o>a;)if((r=s[a++])!=r)return!0}else for(;o>a;a++)if((e||a in s)&&s[a]===i)return e||a||0;return!e&&-1}},Zn={includes:Qn(!0),indexOf:Qn(!1)},$n=Zn.includes;Mn({target:"Array",proto:!0,forced:de((function(){return!Array(1).includes()}))},{includes:function(e){return $n(this,e,arguments.length>1?arguments[1]:void 0)}});var er=ct,tr=function(e){return er[e+"Prototype"]},ir=tr("Array").includes,nr=at,rr=be,sr=gi("match"),or=function(e){var t;return nr(e)&&(void 0!==(t=e[sr])?!!t:"RegExp"==rr(e))},ar=TypeError,cr={};cr[gi("toStringTag")]="z";var dr="[object z]"===String(cr),lr=dr,hr=ke,ur=be,pr=gi("toStringTag"),_r=Object,Er="Arguments"==ur(function(){return arguments}()),mr=lr?ur:function(e){var t,i,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=_r(e),pr))?i:Er?ur(t):"Object"==(n=ur(t))&&hr(t.callee)?"Arguments":n},fr=mr,gr=String,Sr=function(e){if("Symbol"===fr(e))throw TypeError("Cannot convert a Symbol value to a string");return gr(e)},Tr=gi("match"),Rr=Mn,Cr=function(e){if(or(e))throw ar("The method doesn't accept regular expressions");return e},vr=tt,Ir=Sr,yr=function(e){var t=/./;try{"/./"[e](t)}catch(i){try{return t[Tr]=!1,"/./"[e](t)}catch(e){}}return!1},Ar=Ee("".indexOf);Rr({target:"String",proto:!0,forced:!yr("includes")},{includes:function(e){return!!~Ar(Ir(vr(this)),Ir(Cr(e)),arguments.length>1?arguments[1]:void 0)}});var br=tr("String").includes,wr=me,Or=ir,Nr=br,Dr=Array.prototype,Pr=String.prototype,Lr=z((function(e){var t=e.includes;return e===Dr||wr(Dr,e)&&t===Dr.includes?Or:"string"==typeof e||e===Pr||wr(Pr,e)&&t===Pr.includes?Nr:t})),kr={exports:{}},Mr=Mn,Ur=Ue,xr=rn.f;Mr({target:"Object",stat:!0,forced:Object.defineProperty!==xr,sham:!Ur},{defineProperty:xr});var Vr=ct.Object,Fr=kr.exports=function(e,t,i){return Vr.defineProperty(e,t,i)};Vr.defineProperty.sham&&(Fr.sham=!0);var Br=z(kr.exports),jr=be,Gr=Array.isArray||function(e){return"Array"==jr(e)},Wr=TypeError,Hr=wi,Kr=rn,Yr=Ye,qr=function(e,t,i){var n=Hr(t);n in e?Kr.f(e,n,Yr(0,i)):e[n]=i},Jr=ke,zr=Xt,Xr=Ee(Function.toString);Jr(zr.inspectSource)||(zr.inspectSource=function(e){return Xr(e)});var Qr=zr.inspectSource,Zr=Ee,$r=de,es=ke,ts=mr,is=Qr,ns=function(){},rs=[],ss=pt("Reflect","construct"),os=/^\s*(?:class|function)\b/,as=Zr(os.exec),cs=!os.exec(ns),ds=function(e){if(!es(e))return!1;try{return ss(ns,rs,e),!0}catch(e){return!1}},ls=function(e){if(!es(e))return!1;switch(ts(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return cs||!!as(os,is(e))}catch(e){return!0}};ls.sham=!0;var hs=!ss||$r((function(){var e;return ds(ds.call)||!ds(Object)||!ds((function(){e=!0}))||e}))?ls:ds,us=Gr,ps=hs,_s=at,Es=gi("species"),ms=Array,fs=function(e){var t;return us(e)&&(t=e.constructor,(ps(t)&&(t===ms||us(t.prototype))||_s(t)&&null===(t=t[Es]))&&(t=void 0)),void 0===t?ms:t},gs=function(e,t){return new(fs(e))(0===t?0:t)},Ss=de,Ts=Rt,Rs=gi("species"),Cs=Mn,vs=de,Is=Gr,ys=at,As=ti,bs=qn,ws=function(e){if(e>9007199254740991)throw Wr("Maximum allowed index exceeded");return e},Os=qr,Ns=gs,Ds=function(e){return Ts>=51||!Ss((function(){var t=[];return(t.constructor={})[Rs]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},Ps=Rt,Ls=gi("isConcatSpreadable"),ks=Ps>=51||!vs((function(){var e=[];return e[Ls]=!1,e.concat()[0]!==e})),Ms=function(e){if(!ys(e))return!1;var t=e[Ls];return void 0!==t?!!t:Is(e)};Cs({target:"Array",proto:!0,arity:1,forced:!ks||!Ds("concat")},{concat:function(e){var t,i,n,r,s,o=As(this),a=Ns(o,0),c=0;for(t=-1,n=arguments.length;t<n;t++)if(Ms(s=-1===t?o:arguments[t]))for(r=bs(s),ws(c+r),i=0;i<r;i++,c++)i in s&&Os(a,c,s[i]);else ws(c+1),Os(a,c++,s);return a.length=c,a}});var Us={},xs={},Vs=ri,Fs=rt,Bs=Zn.indexOf,js=xs,Gs=Ee([].push),Ws=function(e,t){var i,n=Fs(e),r=0,s=[];for(i in n)!Vs(js,i)&&Vs(n,i)&&Gs(s,i);for(;t.length>r;)Vs(n,i=t[r++])&&(~Bs(s,i)||Gs(s,i));return s},Hs=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ks=Ws,Ys=Hs,qs=Object.keys||function(e){return Ks(e,Ys)},Js=Ue,zs=sn,Xs=rn,Qs=dn,Zs=rt,$s=qs;Us.f=Js&&!zs?Object.defineProperties:function(e,t){Qs(e);for(var i,n=Zs(t),r=$s(t),s=r.length,o=0;s>o;)Xs.f(e,i=r[o++],n[i]);return e};var eo,to=pt("document","documentElement"),io=di,no=Zt("keys"),ro=function(e){return no[e]||(no[e]=io(e))},so=dn,oo=Us,ao=Hs,co=xs,lo=to,ho=Pi,uo="prototype",po="script",_o=ro("IE_PROTO"),Eo=function(){},mo=function(e){return"<"+po+">"+e+"</"+po+">"},fo=function(e){e.write(mo("")),e.close();var t=e.parentWindow.Object;return e=null,t},go=function(){try{eo=new ActiveXObject("htmlfile")}catch(e){}var e,t,i;go="undefined"!=typeof document?document.domain&&eo?fo(eo):(t=ho("iframe"),i="java"+po+":",t.style.display="none",lo.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(mo("document.F=Object")),e.close(),e.F):fo(eo);for(var n=ao.length;n--;)delete go[uo][ao[n]];return go()};co[_o]=!0;var So=Object.create||function(e,t){var i;return null!==e?(Eo[uo]=so(e),i=new Eo,Eo[uo]=null,i[_o]=e):i=go(),void 0===t?i:oo.f(i,t)},To={},Ro=Ws,Co=Hs.concat("length","prototype");To.f=Object.getOwnPropertyNames||function(e){return Ro(e,Co)};var vo={},Io=Wn,yo=qn,Ao=qr,bo=Array,wo=Math.max,Oo=function(e,t,i){for(var n=yo(e),r=Io(t,n),s=Io(void 0===i?n:i,n),o=bo(wo(s-r,0)),a=0;r<s;r++,a++)Ao(o,a,e[r]);return o.length=a,o},No=be,Do=rt,Po=To.f,Lo=Oo,ko="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];vo.f=function(e){return ko&&"Window"==No(e)?function(e){try{return Po(e)}catch(e){return Lo(ko)}}(e):Po(Do(e))};var Mo={};Mo.f=Object.getOwnPropertySymbols;var Uo=vn,xo=function(e,t,i,n){return n&&n.enumerable?e[t]=i:Uo(e,t,i),e},Vo=rn,Fo=function(e,t,i){return Vo.f(e,t,i)},Bo={},jo=gi;Bo.f=jo;var Go,Wo,Ho,Ko=ct,Yo=ri,qo=Bo,Jo=rn.f,zo=function(e){var t=Ko.Symbol||(Ko.Symbol={});Yo(t,e)||Jo(t,e,{value:qo.f(e)})},Xo=Fe,Qo=pt,Zo=gi,$o=xo,ea=function(){var e=Qo("Symbol"),t=e&&e.prototype,i=t&&t.valueOf,n=Zo("toPrimitive");t&&!t[n]&&$o(t,n,(function(e){return Xo(i,this)}),{arity:1})},ta=mr,ia=dr?{}.toString:function(){return"[object "+ta(this)+"]"},na=dr,ra=rn.f,sa=vn,oa=ri,aa=ia,ca=gi("toStringTag"),da=function(e,t,i,n){if(e){var r=i?e:e.prototype;oa(r,ca)||ra(r,ca,{configurable:!0,value:t}),n&&!na&&sa(r,"toString",aa)}},la=ke,ha=ge.WeakMap,ua=la(ha)&&/native code/.test(String(ha)),pa=ge,_a=at,Ea=vn,ma=ri,fa=Xt,ga=ro,Sa=xs,Ta="Object already initialized",Ra=pa.TypeError,Ca=pa.WeakMap;if(ua||fa.state){var va=fa.state||(fa.state=new Ca);va.get=va.get,va.has=va.has,va.set=va.set,Go=function(e,t){if(va.has(e))throw Ra(Ta);return t.facade=e,va.set(e,t),t},Wo=function(e){return va.get(e)||{}},Ho=function(e){return va.has(e)}}else{var Ia=ga("state");Sa[Ia]=!0,Go=function(e,t){if(ma(e,Ia))throw Ra(Ta);return t.facade=e,Ea(e,Ia,t),t},Wo=function(e){return ma(e,Ia)?e[Ia]:{}},Ho=function(e){return ma(e,Ia)}}var ya={set:Go,get:Wo,has:Ho,enforce:function(e){return Ho(e)?Wo(e):Go(e,{})},getterFor:function(e){return function(t){var i;if(!_a(t)||(i=Wo(t)).type!==e)throw Ra("Incompatible receiver, "+e+" required");return i}}},Aa=nn,ba=Qe,wa=ti,Oa=qn,Na=gs,Da=Ee([].push),Pa=function(e){var t=1==e,i=2==e,n=3==e,r=4==e,s=6==e,o=7==e,a=5==e||s;return function(c,d,l,h){for(var u,p,_=wa(c),E=ba(_),m=Aa(d,l),f=Oa(E),g=0,S=h||Na,T=t?S(c,f):i||o?S(c,0):void 0;f>g;g++)if((a||g in E)&&(p=m(u=E[g],g,_),e))if(t)T[g]=p;else if(p)switch(e){case 3:return!0;case 5:return u;case 6:return g;case 2:Da(T,u)}else switch(e){case 4:return!1;case 7:Da(T,u)}return s?-1:n||r?r:T}},La={forEach:Pa(0),map:Pa(1),filter:Pa(2),some:Pa(3),every:Pa(4),find:Pa(5),findIndex:Pa(6),filterReject:Pa(7)},ka=Mn,Ma=ge,Ua=Fe,xa=Ee,Va=Ue,Fa=yt,Ba=de,ja=ri,Ga=me,Wa=dn,Ha=rt,Ka=wi,Ya=Sr,qa=Ye,Ja=So,za=qs,Xa=To,Qa=vo,Za=Mo,$a=Me,ec=rn,tc=Us,ic=Be,nc=xo,rc=Fo,sc=Zt,oc=xs,ac=di,cc=gi,dc=Bo,lc=zo,hc=ea,uc=da,pc=ya,_c=La.forEach,Ec=ro("hidden"),mc="Symbol",fc="prototype",gc=pc.set,Sc=pc.getterFor(mc),Tc=Object[fc],Rc=Ma.Symbol,Cc=Rc&&Rc[fc],vc=Ma.TypeError,Ic=Ma.QObject,yc=$a.f,Ac=ec.f,bc=Qa.f,wc=ic.f,Oc=xa([].push),Nc=sc("symbols"),Dc=sc("op-symbols"),Pc=sc("wks"),Lc=!Ic||!Ic[fc]||!Ic[fc].findChild,kc=Va&&Ba((function(){return 7!=Ja(Ac({},"a",{get:function(){return Ac(this,"a",{value:7}).a}})).a}))?function(e,t,i){var n=yc(Tc,t);n&&delete Tc[t],Ac(e,t,i),n&&e!==Tc&&Ac(Tc,t,n)}:Ac,Mc=function(e,t){var i=Nc[e]=Ja(Cc);return gc(i,{type:mc,tag:e,description:t}),Va||(i.description=t),i},Uc=function(e,t,i){e===Tc&&Uc(Dc,t,i),Wa(e);var n=Ka(t);return Wa(i),ja(Nc,n)?(i.enumerable?(ja(e,Ec)&&e[Ec][n]&&(e[Ec][n]=!1),i=Ja(i,{enumerable:qa(0,!1)})):(ja(e,Ec)||Ac(e,Ec,qa(1,{})),e[Ec][n]=!0),kc(e,n,i)):Ac(e,n,i)},xc=function(e,t){Wa(e);var i=Ha(t),n=za(i).concat(jc(i));return _c(n,(function(t){Va&&!Ua(Vc,i,t)||Uc(e,t,i[t])})),e},Vc=function(e){var t=Ka(e),i=Ua(wc,this,t);return!(this===Tc&&ja(Nc,t)&&!ja(Dc,t))&&(!(i||!ja(this,t)||!ja(Nc,t)||ja(this,Ec)&&this[Ec][t])||i)},Fc=function(e,t){var i=Ha(e),n=Ka(t);if(i!==Tc||!ja(Nc,n)||ja(Dc,n)){var r=yc(i,n);return!r||!ja(Nc,n)||ja(i,Ec)&&i[Ec][n]||(r.enumerable=!0),r}},Bc=function(e){var t=bc(Ha(e)),i=[];return _c(t,(function(e){ja(Nc,e)||ja(oc,e)||Oc(i,e)})),i},jc=function(e){var t=e===Tc,i=bc(t?Dc:Ha(e)),n=[];return _c(i,(function(e){!ja(Nc,e)||t&&!ja(Tc,e)||Oc(n,Nc[e])})),n};Fa||(Rc=function(){if(Ga(Cc,this))throw vc("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?Ya(arguments[0]):void 0,t=ac(e),i=function(e){this===Tc&&Ua(i,Dc,e),ja(this,Ec)&&ja(this[Ec],t)&&(this[Ec][t]=!1),kc(this,t,qa(1,e))};return Va&&Lc&&kc(Tc,t,{configurable:!0,set:i}),Mc(t,e)},nc(Cc=Rc[fc],"toString",(function(){return Sc(this).tag})),nc(Rc,"withoutSetter",(function(e){return Mc(ac(e),e)})),ic.f=Vc,ec.f=Uc,tc.f=xc,$a.f=Fc,Xa.f=Qa.f=Bc,Za.f=jc,dc.f=function(e){return Mc(cc(e),e)},Va&&rc(Cc,"description",{configurable:!0,get:function(){return Sc(this).description}})),ka({global:!0,constructor:!0,wrap:!0,forced:!Fa,sham:!Fa},{Symbol:Rc}),_c(za(Pc),(function(e){lc(e)})),ka({target:mc,stat:!0,forced:!Fa},{useSetter:function(){Lc=!0},useSimple:function(){Lc=!1}}),ka({target:"Object",stat:!0,forced:!Fa,sham:!Va},{create:function(e,t){return void 0===t?Ja(e):xc(Ja(e),t)},defineProperty:Uc,defineProperties:xc,getOwnPropertyDescriptor:Fc}),ka({target:"Object",stat:!0,forced:!Fa},{getOwnPropertyNames:Bc}),hc(),uc(Rc,mc),oc[Ec]=!0;var Gc=yt&&!!Symbol.for&&!!Symbol.keyFor,Wc=Mn,Hc=pt,Kc=ri,Yc=Sr,qc=Zt,Jc=Gc,zc=qc("string-to-symbol-registry"),Xc=qc("symbol-to-string-registry");Wc({target:"Symbol",stat:!0,forced:!Jc},{for:function(e){var t=Yc(e);if(Kc(zc,t))return zc[t];var i=Hc("Symbol")(t);return zc[t]=i,Xc[i]=t,i}});var Qc=Mn,Zc=ri,$c=Dt,ed=Lt,td=Gc,id=Zt("symbol-to-string-registry");Qc({target:"Symbol",stat:!0,forced:!td},{keyFor:function(e){if(!$c(e))throw TypeError(ed(e)+" is not a symbol");if(Zc(id,e))return id[e]}});var nd=Ee([].slice),rd=Gr,sd=ke,od=be,ad=Sr,cd=Ee([].push),dd=Mn,ld=pt,hd=ve,ud=Fe,pd=Ee,_d=de,Ed=ke,md=Dt,fd=nd,gd=function(e){if(sd(e))return e;if(rd(e)){for(var t=e.length,i=[],n=0;n<t;n++){var r=e[n];"string"==typeof r?cd(i,r):"number"!=typeof r&&"Number"!=od(r)&&"String"!=od(r)||cd(i,ad(r))}var s=i.length,o=!0;return function(e,t){if(o)return o=!1,t;if(rd(this))return t;for(var n=0;n<s;n++)if(i[n]===e)return t}}},Sd=yt,Td=String,Rd=ld("JSON","stringify"),Cd=pd(/./.exec),vd=pd("".charAt),Id=pd("".charCodeAt),yd=pd("".replace),Ad=pd(1..toString),bd=/[\uD800-\uDFFF]/g,wd=/^[\uD800-\uDBFF]$/,Od=/^[\uDC00-\uDFFF]$/,Nd=!Sd||_d((function(){var e=ld("Symbol")();return"[null]"!=Rd([e])||"{}"!=Rd({a:e})||"{}"!=Rd(Object(e))})),Dd=_d((function(){return'"\\udf06\\ud834"'!==Rd("\udf06\ud834")||'"\\udead"'!==Rd("\udead")})),Pd=function(e,t){var i=fd(arguments),n=gd(t);if(Ed(n)||void 0!==e&&!md(e))return i[1]=function(e,t){if(Ed(n)&&(t=ud(n,this,Td(e),t)),!md(t))return t},hd(Rd,null,i)},Ld=function(e,t,i){var n=vd(i,t-1),r=vd(i,t+1);return Cd(wd,e)&&!Cd(Od,r)||Cd(Od,e)&&!Cd(wd,n)?"\\u"+Ad(Id(e,0),16):e};Rd&&dd({target:"JSON",stat:!0,arity:3,forced:Nd||Dd},{stringify:function(e,t,i){var n=fd(arguments),r=hd(Nd?Pd:Rd,null,n);return Dd&&"string"==typeof r?yd(r,bd,Ld):r}});var kd=Mo,Md=ti;Mn({target:"Object",stat:!0,forced:!yt||de((function(){kd.f(1)}))},{getOwnPropertySymbols:function(e){var t=kd.f;return t?t(Md(e)):[]}}),zo("asyncIterator"),zo("hasInstance"),zo("isConcatSpreadable"),zo("iterator"),zo("match"),zo("matchAll"),zo("replace"),zo("search"),zo("species"),zo("split");var Ud=ea;zo("toPrimitive"),Ud();var xd=pt,Vd=da;zo("toStringTag"),Vd(xd("Symbol"),"Symbol"),zo("unscopables"),da(ge.JSON,"JSON",!0);var Fd,Bd,jd,Gd=ct.Symbol,Wd={},Hd=Ue,Kd=ri,Yd=Function.prototype,qd=Hd&&Object.getOwnPropertyDescriptor,Jd=Kd(Yd,"name"),zd={EXISTS:Jd,PROPER:Jd&&"something"===function(){}.name,CONFIGURABLE:Jd&&(!Hd||Hd&&qd(Yd,"name").configurable)},Xd=!de((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Qd=ri,Zd=ke,$d=ti,el=Xd,tl=ro("IE_PROTO"),il=Object,nl=il.prototype,rl=el?il.getPrototypeOf:function(e){var t=$d(e);if(Qd(t,tl))return t[tl];var i=t.constructor;return Zd(i)&&t instanceof i?i.prototype:t instanceof il?nl:null},sl=de,ol=ke,al=at,cl=So,dl=rl,ll=xo,hl=gi("iterator"),ul=!1;[].keys&&("next"in(jd=[].keys())?(Bd=dl(dl(jd)))!==Object.prototype&&(Fd=Bd):ul=!0);var pl=!al(Fd)||sl((function(){var e={};return Fd[hl].call(e)!==e}));ol((Fd=pl?{}:cl(Fd))[hl])||ll(Fd,hl,(function(){return this}));var _l={IteratorPrototype:Fd,BUGGY_SAFARI_ITERATORS:ul},El=_l.IteratorPrototype,ml=So,fl=Ye,gl=da,Sl=Wd,Tl=function(){return this},Rl=Ee,Cl=xt,vl=ke,Il=String,yl=TypeError,Al=function(e,t,i){try{return Rl(Cl(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(e){}},bl=dn,wl=function(e){if("object"==typeof e||vl(e))return e;throw yl("Can't set "+Il(e)+" as a prototype")},Ol=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Al(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(e){}return function(i,n){return bl(i),wl(n),t?e(i,n):i.__proto__=n,i}}():void 0),Nl=Mn,Dl=Fe,Pl=function(e,t,i,n){var r=t+" Iterator";return e.prototype=ml(El,{next:fl(+!n,i)}),gl(e,r,!1,!0),Sl[r]=Tl,e},Ll=rl,kl=da,Ml=xo,Ul=Wd,xl=_l,Vl=zd.PROPER,Fl=xl.BUGGY_SAFARI_ITERATORS,Bl=gi("iterator"),jl="keys",Gl="values",Wl="entries",Hl=function(){return this},Kl=function(e,t,i,n,r,s,o){Pl(i,t,n);var a,c,d,l=function(e){if(e===r&&E)return E;if(!Fl&&e in p)return p[e];switch(e){case jl:case Gl:case Wl:return function(){return new i(this,e)}}return function(){return new i(this)}},h=t+" Iterator",u=!1,p=e.prototype,_=p[Bl]||p["@@iterator"]||r&&p[r],E=!Fl&&_||l(r),m="Array"==t&&p.entries||_;if(m&&(a=Ll(m.call(new e)))!==Object.prototype&&a.next&&(kl(a,h,!0,!0),Ul[h]=Hl),Vl&&r==Gl&&_&&_.name!==Gl&&(u=!0,E=function(){return Dl(_,this)}),r)if(c={values:l(Gl),keys:s?E:l(jl),entries:l(Wl)},o)for(d in c)(Fl||u||!(d in p))&&Ml(p,d,c[d]);else Nl({target:t,proto:!0,forced:Fl||u},c);return o&&p[Bl]!==E&&Ml(p,Bl,E,{name:r}),Ul[t]=E,c},Yl=function(e,t){return{value:e,done:t}},ql=rt,Jl=Wd,zl=ya;rn.f;var Xl=Kl,Ql=Yl,Zl="Array Iterator",$l=zl.set,eh=zl.getterFor(Zl);Xl(Array,"Array",(function(e,t){$l(this,{type:Zl,target:ql(e),index:0,kind:t})}),(function(){var e=eh(this),t=e.target,i=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,Ql(void 0,!0)):Ql("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1)}),"values"),Jl.Arguments=Jl.Array;var th={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},ih=ge,nh=mr,rh=vn,sh=Wd,oh=gi("toStringTag");for(var ah in th){var ch=ih[ah],dh=ch&&ch.prototype;dh&&nh(dh)!==oh&&rh(dh,oh,ah),sh[ah]=sh.Array}var lh=Gd,hh=gi,uh=rn.f,ph=hh("metadata"),_h=Function.prototype;void 0===_h[ph]&&uh(_h,ph,{value:null}),zo("dispose"),zo("metadata");var Eh=lh;zo("asyncDispose");var mh=Ee,fh=pt("Symbol"),gh=fh.keyFor,Sh=mh(fh.prototype.valueOf),Th=fh.isRegisteredSymbol||function(e){try{return void 0!==gh(Sh(e))}catch(e){return!1}};Mn({target:"Symbol",stat:!0},{isRegisteredSymbol:Th});for(var Rh=Zt,Ch=pt,vh=Ee,Ih=Dt,yh=gi,Ah=Ch("Symbol"),bh=Ah.isWellKnownSymbol,wh=Ch("Object","getOwnPropertyNames"),Oh=vh(Ah.prototype.valueOf),Nh=Rh("wks"),Dh=0,Ph=wh(Ah),Lh=Ph.length;Dh<Lh;Dh++)try{var kh=Ph[Dh];Ih(Ah[kh])&&yh(kh)}catch(t){}var Mh=function(e){if(bh&&bh(e))return!0;try{for(var t=Oh(e),i=0,n=wh(Nh),r=n.length;i<r;i++)if(Nh[n[i]]==t)return!0}catch(e){}return!1};Mn({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:Mh}),zo("matcher"),zo("observable"),Mn({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:Th}),Mn({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:Mh}),zo("metadataKey"),zo("patternMatch"),zo("replaceAll");var Uh=z(Eh),xh=Ee,Vh=Fn,Fh=Sr,Bh=tt,jh=xh("".charAt),Gh=xh("".charCodeAt),Wh=xh("".slice),Hh=function(e){return function(t,i){var n,r,s=Fh(Bh(t)),o=Vh(i),a=s.length;return o<0||o>=a?e?"":void 0:(n=Gh(s,o))<55296||n>56319||o+1===a||(r=Gh(s,o+1))<56320||r>57343?e?jh(s,o):n:e?Wh(s,o,o+2):r-56320+(n-55296<<10)+65536}},Kh=(Hh(!1),Hh(!0)),Yh=Sr,qh=ya,Jh=Kl,zh=Yl,Xh="String Iterator",Qh=qh.set,Zh=qh.getterFor(Xh);Jh(String,"String",(function(e){Qh(this,{type:Xh,string:Yh(e),index:0})}),(function(){var e,t=Zh(this),i=t.string,n=t.index;return n>=i.length?zh(void 0,!0):(e=Kh(i,n),t.index+=e.length,zh(e,!1))}));var $h=z(Bo.f("iterator"));function eu(e){return eu="function"==typeof Uh&&"symbol"==typeof $h?function(e){return typeof e}:function(e){return e&&"function"==typeof Uh&&e.constructor===Uh&&e!==Uh.prototype?"symbol":typeof e},eu(e)}var tu=z(Bo.f("toPrimitive"));function iu(e){var t=function(e,t){if("object"!==eu(e)||null===e)return e;var i=e[tu];if(void 0!==i){var n=i.call(e,t||"default");if("object"!==eu(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===eu(t)?t:String(t)}function nu(e,t,i){return(t=iu(t))in e?Br(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var ru=tr("Array").keys,su=mr,ou=ri,au=me,cu=ru,du=Array.prototype,lu={DOMTokenList:!0,NodeList:!0},hu=z((function(e){var t=e.keys;return e===du||au(du,e)&&t===du.keys||ou(lu,su(e))?cu:t})),uu=Lt,pu=TypeError,_u=Oo,Eu=Math.floor,mu=function(e,t){var i=e.length,n=Eu(i/2);return i<8?fu(e,t):gu(e,mu(_u(e,0,n),t),mu(_u(e,n),t),t)},fu=function(e,t){for(var i,n,r=e.length,s=1;s<r;){for(n=s,i=e[s];n&&t(e[n-1],i)>0;)e[n]=e[--n];n!==s++&&(e[n]=i)}return e},gu=function(e,t,i,n){for(var r=t.length,s=i.length,o=0,a=0;o<r||a<s;)e[o+a]=o<r&&a<s?n(t[o],i[a])<=0?t[o++]:i[a++]:o<r?t[o++]:i[a++];return e},Su=mu,Tu=de,Ru=function(e,t){var i=[][e];return!!i&&Tu((function(){i.call(null,t||function(){return 1},1)}))},Cu=_t.match(/firefox\/(\d+)/i),vu=!!Cu&&+Cu[1],Iu=/MSIE|Trident/.test(_t),yu=_t.match(/AppleWebKit\/(\d+)\./),Au=!!yu&&+yu[1],bu=Mn,wu=Ee,Ou=xt,Nu=ti,Du=qn,Pu=function(e,t){if(!delete e[t])throw pu("Cannot delete property "+uu(t)+" of "+uu(e))},Lu=Sr,ku=de,Mu=Su,Uu=Ru,xu=vu,Vu=Iu,Fu=Rt,Bu=Au,ju=[],Gu=wu(ju.sort),Wu=wu(ju.push),Hu=ku((function(){ju.sort(void 0)})),Ku=ku((function(){ju.sort(null)})),Yu=Uu("sort"),qu=!ku((function(){if(Fu)return Fu<70;if(!(xu&&xu>3)){if(Vu)return!0;if(Bu)return Bu<603;var e,t,i,n,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(n=0;n<47;n++)ju.push({k:t+n,v:i})}for(ju.sort((function(e,t){return t.v-e.v})),n=0;n<ju.length;n++)t=ju[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));bu({target:"Array",proto:!0,forced:Hu||!Ku||!Yu||!qu},{sort:function(e){void 0!==e&&Ou(e);var t=Nu(this);if(qu)return void 0===e?Gu(t):Gu(t,e);var i,n,r=[],s=Du(t);for(n=0;n<s;n++)n in t&&Wu(r,t[n]);for(Mu(r,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Lu(t)>Lu(i)?1:-1}}(e)),i=Du(r),n=0;n<i;)t[n]=r[n++];for(;n<s;)Pu(t,n++);return t}});var Ju=tr("Array").sort,zu=me,Xu=Ju,Qu=Array.prototype,Zu=z((function(e){var t=e.sort;return e===Qu||zu(Qu,e)&&t===Qu.sort?Xu:t})),$u=pt,ep=To,tp=Mo,ip=dn,np=Ee([].concat),rp=$u("Reflect","ownKeys")||function(e){var t=ep.f(ip(e)),i=tp.f;return i?np(t,i(e)):t},sp=ri,op=rp,ap=Me,cp=rn,dp=at,lp=vn,hp=Error,up=Ee("".replace),pp=String(hp("zxcasd").stack),_p=/\n\s*at [^:]*:[^\n]*/,Ep=_p.test(pp),mp=Ye,fp=!de((function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",mp(1,7)),7!==e.stack)})),gp=vn,Sp=function(e,t){if(Ep&&"string"==typeof e&&!hp.prepareStackTrace)for(;t--;)e=up(e,_p,"");return e},Tp=fp,Rp=Error.captureStackTrace,Cp=Wd,vp=gi("iterator"),Ip=Array.prototype,yp=mr,Ap=Bt,bp=Ze,wp=Wd,Op=gi("iterator"),Np=function(e){if(!bp(e))return Ap(e,Op)||Ap(e,"@@iterator")||wp[yp(e)]},Dp=Fe,Pp=xt,Lp=dn,kp=Lt,Mp=Np,Up=TypeError,xp=Fe,Vp=dn,Fp=Bt,Bp=nn,jp=Fe,Gp=dn,Wp=Lt,Hp=function(e){return void 0!==e&&(Cp.Array===e||Ip[vp]===e)},Kp=qn,Yp=me,qp=function(e,t){var i=arguments.length<2?Mp(e):t;if(Pp(i))return Lp(Dp(i,e));throw Up(kp(e)+" is not iterable")},Jp=Np,zp=function(e,t,i){var n,r;Vp(e);try{if(!(n=Fp(e,"return"))){if("throw"===t)throw i;return i}n=xp(n,e)}catch(e){r=!0,n=e}if("throw"===t)throw i;if(r)throw n;return Vp(n),i},Xp=TypeError,Qp=function(e,t){this.stopped=e,this.result=t},Zp=Qp.prototype,$p=function(e,t,i){var n,r,s,o,a,c,d,l=i&&i.that,h=!(!i||!i.AS_ENTRIES),u=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),_=!(!i||!i.INTERRUPTED),E=Bp(t,l),m=function(e){return n&&zp(n,"normal",e),new Qp(!0,e)},f=function(e){return h?(Gp(e),_?E(e[0],e[1],m):E(e[0],e[1])):_?E(e,m):E(e)};if(u)n=e.iterator;else if(p)n=e;else{if(!(r=Jp(e)))throw Xp(Wp(e)+" is not iterable");if(Hp(r)){for(s=0,o=Kp(e);o>s;s++)if((a=f(e[s]))&&Yp(Zp,a))return a;return new Qp(!1)}n=qp(e,r)}for(c=u?e.next:n.next;!(d=jp(c,n)).done;){try{a=f(d.value)}catch(e){zp(n,"throw",e)}if("object"==typeof a&&a&&Yp(Zp,a))return a}return new Qp(!1)},e_=Sr,t_=Mn,i_=me,n_=rl,r_=Ol,s_=function(e,t,i){for(var n=op(t),r=cp.f,s=ap.f,o=0;o<n.length;o++){var a=n[o];sp(e,a)||i&&sp(i,a)||r(e,a,s(t,a))}},o_=So,a_=vn,c_=Ye,d_=function(e,t){dp(t)&&"cause"in t&&lp(e,"cause",t.cause)},l_=function(e,t,i,n){Tp&&(Rp?Rp(e,t):gp(e,"stack",Sp(i,n)))},h_=$p,u_=function(e,t){return void 0===e?arguments.length<2?"":t:e_(e)},p_=gi("toStringTag"),__=Error,E_=[].push,m_=function(e,t){var i,n=i_(f_,this);r_?i=r_(__(),n?n_(this):f_):(i=n?this:o_(f_),a_(i,p_,"Error")),void 0!==t&&a_(i,"message",u_(t)),l_(i,m_,i.stack,1),arguments.length>2&&d_(i,arguments[2]);var r=[];return h_(e,E_,{that:r}),a_(i,"errors",r),i};r_?r_(m_,__):s_(m_,__,{name:!0});var f_=m_.prototype=o_(__.prototype,{constructor:c_(1,m_),message:c_(1,""),name:c_(1,"AggregateError")});t_({global:!0,constructor:!0,arity:2},{AggregateError:m_});var g_,S_,T_,R_,C_="undefined"!=typeof process&&"process"==be(process),v_=pt,I_=Fo,y_=Ue,A_=gi("species"),b_=me,w_=TypeError,O_=hs,N_=Lt,D_=TypeError,P_=dn,L_=function(e){if(O_(e))return e;throw D_(N_(e)+" is not a constructor")},k_=Ze,M_=gi("species"),U_=function(e,t){var i,n=P_(e).constructor;return void 0===n||k_(i=P_(n)[M_])?t:L_(i)},x_=TypeError,V_=/(?:ipad|iphone|ipod).*applewebkit/i.test(_t),F_=ge,B_=ve,j_=nn,G_=ke,W_=ri,H_=de,K_=to,Y_=nd,q_=Pi,J_=function(e,t){if(e<t)throw x_("Not enough arguments");return e},z_=V_,X_=C_,Q_=F_.setImmediate,Z_=F_.clearImmediate,$_=F_.process,eE=F_.Dispatch,tE=F_.Function,iE=F_.MessageChannel,nE=F_.String,rE=0,sE={},oE="onreadystatechange";H_((function(){g_=F_.location}));var aE=function(e){if(W_(sE,e)){var t=sE[e];delete sE[e],t()}},cE=function(e){return function(){aE(e)}},dE=function(e){aE(e.data)},lE=function(e){F_.postMessage(nE(e),g_.protocol+"//"+g_.host)};Q_&&Z_||(Q_=function(e){J_(arguments.length,1);var t=G_(e)?e:tE(e),i=Y_(arguments,1);return sE[++rE]=function(){B_(t,void 0,i)},S_(rE),rE},Z_=function(e){delete sE[e]},X_?S_=function(e){$_.nextTick(cE(e))}:eE&&eE.now?S_=function(e){eE.now(cE(e))}:iE&&!z_?(R_=(T_=new iE).port2,T_.port1.onmessage=dE,S_=j_(R_.postMessage,R_)):F_.addEventListener&&G_(F_.postMessage)&&!F_.importScripts&&g_&&"file:"!==g_.protocol&&!H_(lE)?(S_=lE,F_.addEventListener("message",dE,!1)):S_=oE in q_("script")?function(e){K_.appendChild(q_("script"))[oE]=function(){K_.removeChild(this),aE(e)}}:function(e){setTimeout(cE(e),0)});var hE={set:Q_,clear:Z_},uE=function(){this.head=null,this.tail=null};uE.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var pE,_E,EE,mE,fE,gE=uE,SE=/ipad|iphone|ipod/i.test(_t)&&"undefined"!=typeof Pebble,TE=/web0s(?!.*chrome)/i.test(_t),RE=ge,CE=nn,vE=Me.f,IE=hE.set,yE=gE,AE=V_,bE=SE,wE=TE,OE=C_,NE=RE.MutationObserver||RE.WebKitMutationObserver,DE=RE.document,PE=RE.process,LE=RE.Promise,kE=vE(RE,"queueMicrotask"),ME=kE&&kE.value;if(!ME){var UE=new yE,xE=function(){var e,t;for(OE&&(e=PE.domain)&&e.exit();t=UE.get();)try{t()}catch(e){throw UE.head&&pE(),e}e&&e.enter()};AE||OE||wE||!NE||!DE?!bE&&LE&&LE.resolve?((mE=LE.resolve(void 0)).constructor=LE,fE=CE(mE.then,mE),pE=function(){fE(xE)}):OE?pE=function(){PE.nextTick(xE)}:(IE=CE(IE,RE),pE=function(){IE(xE)}):(_E=!0,EE=DE.createTextNode(""),new NE(xE).observe(EE,{characterData:!0}),pE=function(){EE.data=_E=!_E}),ME=function(e){UE.head||pE(),UE.add(e)}}var VE=ME,FE=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},BE=ge.Promise,jE="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,GE=!jE&&!C_&&"object"==typeof window&&"object"==typeof document,WE=ge,HE=BE,KE=ke,YE=Zi,qE=Qr,JE=gi,zE=GE,XE=jE,QE=Rt,ZE=HE&&HE.prototype,$E=JE("species"),em=!1,tm=KE(WE.PromiseRejectionEvent),im=YE("Promise",(function(){var e=qE(HE),t=e!==String(HE);if(!t&&66===QE)return!0;if(!ZE.catch||!ZE.finally)return!0;if(!QE||QE<51||!/native code/.test(e)){var i=new HE((function(e){e(1)})),n=function(e){e((function(){}),(function(){}))};if((i.constructor={})[$E]=n,!(em=i.then((function(){}))instanceof n))return!0}return!t&&(zE||XE)&&!tm})),nm={CONSTRUCTOR:im,REJECTION_EVENT:tm,SUBCLASSING:em},rm={},sm=xt,om=TypeError,am=function(e){var t,i;this.promise=new e((function(e,n){if(void 0!==t||void 0!==i)throw om("Bad Promise constructor");t=e,i=n})),this.resolve=sm(t),this.reject=sm(i)};rm.f=function(e){return new am(e)};var cm,dm,lm=Mn,hm=C_,um=ge,pm=Fe,_m=xo,Em=da,mm=function(e){var t=v_(e);y_&&t&&!t[A_]&&I_(t,A_,{configurable:!0,get:function(){return this}})},fm=xt,gm=ke,Sm=at,Tm=function(e,t){if(b_(t,e))return e;throw w_("Incorrect invocation")},Rm=U_,Cm=hE.set,vm=VE,Im=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(e){}},ym=FE,Am=gE,bm=ya,wm=BE,Om=nm,Nm=rm,Dm="Promise",Pm=Om.CONSTRUCTOR,Lm=Om.REJECTION_EVENT,km=bm.getterFor(Dm),Mm=bm.set,Um=wm&&wm.prototype,xm=wm,Vm=Um,Fm=um.TypeError,Bm=um.document,jm=um.process,Gm=Nm.f,Wm=Gm,Hm=!!(Bm&&Bm.createEvent&&um.dispatchEvent),Km="unhandledrejection",Ym=function(e){var t;return!(!Sm(e)||!gm(t=e.then))&&t},qm=function(e,t){var i,n,r,s=t.value,o=1==t.state,a=o?e.ok:e.fail,c=e.resolve,d=e.reject,l=e.domain;try{a?(o||(2===t.rejection&&Zm(t),t.rejection=1),!0===a?i=s:(l&&l.enter(),i=a(s),l&&(l.exit(),r=!0)),i===e.promise?d(Fm("Promise-chain cycle")):(n=Ym(i))?pm(n,i,c,d):c(i)):d(s)}catch(e){l&&!r&&l.exit(),d(e)}},Jm=function(e,t){e.notified||(e.notified=!0,vm((function(){for(var i,n=e.reactions;i=n.get();)qm(i,e);e.notified=!1,t&&!e.rejection&&Xm(e)})))},zm=function(e,t,i){var n,r;Hm?((n=Bm.createEvent("Event")).promise=t,n.reason=i,n.initEvent(e,!1,!0),um.dispatchEvent(n)):n={promise:t,reason:i},!Lm&&(r=um["on"+e])?r(n):e===Km&&Im("Unhandled promise rejection",i)},Xm=function(e){pm(Cm,um,(function(){var t,i=e.facade,n=e.value;if(Qm(e)&&(t=ym((function(){hm?jm.emit("unhandledRejection",n,i):zm(Km,i,n)})),e.rejection=hm||Qm(e)?2:1,t.error))throw t.value}))},Qm=function(e){return 1!==e.rejection&&!e.parent},Zm=function(e){pm(Cm,um,(function(){var t=e.facade;hm?jm.emit("rejectionHandled",t):zm("rejectionhandled",t,e.value)}))},$m=function(e,t,i){return function(n){e(t,n,i)}},ef=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Jm(e,!0))},tf=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw Fm("Promise can't be resolved itself");var n=Ym(t);n?vm((function(){var i={done:!1};try{pm(n,t,$m(tf,i,e),$m(ef,i,e))}catch(t){ef(i,t,e)}})):(e.value=t,e.state=1,Jm(e,!1))}catch(t){ef({done:!1},t,e)}}};Pm&&(Vm=(xm=function(e){Tm(this,Vm),fm(e),pm(cm,this);var t=km(this);try{e($m(tf,t),$m(ef,t))}catch(e){ef(t,e)}}).prototype,(cm=function(e){Mm(this,{type:Dm,done:!1,notified:!1,parent:!1,reactions:new Am,rejection:!1,state:0,value:void 0})}).prototype=_m(Vm,"then",(function(e,t){var i=km(this),n=Gm(Rm(this,xm));return i.parent=!0,n.ok=!gm(e)||e,n.fail=gm(t)&&t,n.domain=hm?jm.domain:void 0,0==i.state?i.reactions.add(n):vm((function(){qm(n,i)})),n.promise})),dm=function(){var e=new cm,t=km(e);this.promise=e,this.resolve=$m(tf,t),this.reject=$m(ef,t)},Nm.f=Gm=function(e){return e===xm||void 0===e?new dm(e):Wm(e)}),lm({global:!0,constructor:!0,wrap:!0,forced:Pm},{Promise:xm}),Em(xm,Dm,!1,!0),mm(Dm);var nf=gi("iterator"),rf=!1;try{var sf=0,of={next:function(){return{done:!!sf++}},return:function(){rf=!0}};of[nf]=function(){return this},Array.from(of,(function(){throw 2}))}catch(t){}var af=BE,cf=function(e,t){if(!t&&!rf)return!1;var i=!1;try{var n={};n[nf]=function(){return{next:function(){return{done:i=!0}}}},e(n)}catch(e){}return i},df=nm.CONSTRUCTOR||!cf((function(e){af.all(e).then(void 0,(function(){}))})),lf=Fe,hf=xt,uf=rm,pf=FE,_f=$p;Mn({target:"Promise",stat:!0,forced:df},{all:function(e){var t=this,i=uf.f(t),n=i.resolve,r=i.reject,s=pf((function(){var i=hf(t.resolve),s=[],o=0,a=1;_f(e,(function(e){var c=o++,d=!1;a++,lf(i,t,e).then((function(e){d||(d=!0,s[c]=e,--a||n(s))}),r)})),--a||n(s)}));return s.error&&r(s.value),i.promise}});var Ef=Mn,mf=nm.CONSTRUCTOR;BE&&BE.prototype,Ef({target:"Promise",proto:!0,forced:mf,real:!0},{catch:function(e){return this.then(void 0,e)}});var ff=Fe,gf=xt,Sf=rm,Tf=FE,Rf=$p;Mn({target:"Promise",stat:!0,forced:df},{race:function(e){var t=this,i=Sf.f(t),n=i.reject,r=Tf((function(){var r=gf(t.resolve);Rf(e,(function(e){ff(r,t,e).then(i.resolve,n)}))}));return r.error&&n(r.value),i.promise}});var Cf=Fe,vf=rm;Mn({target:"Promise",stat:!0,forced:nm.CONSTRUCTOR},{reject:function(e){var t=vf.f(this);return Cf(t.reject,void 0,e),t.promise}});var If=dn,yf=at,Af=rm,bf=function(e,t){if(If(e),yf(t)&&t.constructor===e)return t;var i=Af.f(e);return(0,i.resolve)(t),i.promise},wf=Mn,Of=BE,Nf=nm.CONSTRUCTOR,Df=bf,Pf=pt("Promise"),Lf=!Nf;wf({target:"Promise",stat:!0,forced:!0},{resolve:function(e){return Df(Lf&&this===Pf?Of:this,e)}});var kf=Fe,Mf=xt,Uf=rm,xf=FE,Vf=$p;Mn({target:"Promise",stat:!0,forced:df},{allSettled:function(e){var t=this,i=Uf.f(t),n=i.resolve,r=i.reject,s=xf((function(){var i=Mf(t.resolve),r=[],s=0,o=1;Vf(e,(function(e){var a=s++,c=!1;o++,kf(i,t,e).then((function(e){c||(c=!0,r[a]={status:"fulfilled",value:e},--o||n(r))}),(function(e){c||(c=!0,r[a]={status:"rejected",reason:e},--o||n(r))}))})),--o||n(r)}));return s.error&&r(s.value),i.promise}});var Ff=Fe,Bf=xt,jf=pt,Gf=rm,Wf=FE,Hf=$p,Kf="No one promise resolved";Mn({target:"Promise",stat:!0,forced:df},{any:function(e){var t=this,i=jf("AggregateError"),n=Gf.f(t),r=n.resolve,s=n.reject,o=Wf((function(){var n=Bf(t.resolve),o=[],a=0,c=1,d=!1;Hf(e,(function(e){var l=a++,h=!1;c++,Ff(n,t,e).then((function(e){h||d||(d=!0,r(e))}),(function(e){h||d||(h=!0,o[l]=e,--c||s(new i(o,Kf)))}))})),--c||s(new i(o,Kf))}));return o.error&&s(o.value),n.promise}});var Yf=Mn,qf=BE,Jf=de,zf=pt,Xf=ke,Qf=U_,Zf=bf,$f=qf&&qf.prototype;Yf({target:"Promise",proto:!0,real:!0,forced:!!qf&&Jf((function(){$f.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Qf(this,zf("Promise")),i=Xf(e);return this.then(i?function(i){return Zf(t,e()).then((function(){return i}))}:e,i?function(i){return Zf(t,e()).then((function(){throw i}))}:e)}});var eg=ct.Promise,tg=z(eg);const ig=()=>{};function ng(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:ig};return e.promise=new tg(((t,i)=>{e.resolve=i=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(i),e.value=i)},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,i(t))}})),e}const rg=new Map,sg=new Map,og=new Map;var ag,cg;!function(e){e.WIN_10="Windows 10",e.WIN_81="Windows 8.1",e.WIN_8="Windows 8",e.WIN_7="Windows 7",e.WIN_VISTA="Windows Vista",e.WIN_SERVER_2003="Windows Server 2003",e.WIN_XP="Windows XP",e.WIN_2000="Windows 2000",e.ANDROID="Android",e.HARMONY_OS="HarmonyOS",e.OPEN_BSD="Open BSD",e.SUN_OS="Sun OS",e.LINUX="Linux",e.IOS="iOS",e.MAC_OS="Mac OS",e.QNX="QNX",e.UNIX="UNIX",e.BEOS="BeOS",e.OS_2="OS/2",e.SEARCH_BOT="Search Bot"}(ag||(ag={})),function(e){e.CHROME="Chrome",e.SAFARI="Safari",e.EDGE="Edge",e.FIREFOX="Firefox",e.OPERA="OPR",e.QQ="QQBrowser",e.WECHAT="MicroMessenger"}(cg||(cg={}));var dg={exports:{}};!function(e,t){!function(i,n){var r="function",s="undefined",o="object",a="string",c="major",d="model",l="name",h="type",u="vendor",p="version",_="architecture",E="console",m="mobile",f="tablet",g="smarttv",S="wearable",T="embedded",R="Amazon",C="Apple",v="ASUS",I="BlackBerry",y="Browser",A="Chrome",b="Firefox",w="Google",O="Huawei",N="LG",D="Microsoft",P="Motorola",L="Opera",k="Samsung",M="Sharp",U="Sony",x="Xiaomi",V="Zebra",F="Facebook",B="Chromium OS",j="Mac OS",G=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},W=function(e,t){return typeof e===a&&-1!==H(t).indexOf(H(e))},H=function(e){return e.toLowerCase()},K=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===s?e:e.substring(0,350)},Y=function(e,t){for(var i,s,a,c,d,l,h=0;h<t.length&&!d;){var u=t[h],p=t[h+1];for(i=s=0;i<u.length&&!d&&u[i];)if(d=u[i++].exec(e))for(a=0;a<p.length;a++)l=d[++s],typeof(c=p[a])===o&&c.length>0?2===c.length?typeof c[1]==r?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==r||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):n:this[c[0]]=l?c[1].call(this,l,c[2]):n:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):n):this[c]=l||n;h+=2}},q=function(e,t){for(var i in t)if(typeof t[i]===o&&t[i].length>0){for(var r=0;r<t[i].length;r++)if(W(t[i][r],e))return"?"===i?n:i}else if(W(t[i],e))return"?"===i?n:i;return e},J={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},z={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,p],[/opios[\/ ]+([\w\.]+)/i],[p,[l,L+" Mini"]],[/\bopr\/([\w\.]+)/i],[p,[l,L]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[l,p],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[l,"UC"+y]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[p,[l,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[p,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[l,"IE"]],[/yabrowser\/([\w\.]+)/i],[p,[l,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+y],p],[/\bfocus\/([\w\.]+)/i],[p,[l,b+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[l,L+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[l,L+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[l,"MIUI "+y]],[/fxios\/([-\w\.]+)/i],[p,[l,b]],[/\bqihu|(qi?ho?o?|360)browser/i],[[l,"360 "+y]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1 "+y],p],[/(comodo_dragon)\/([\w\.]+)/i],[[l,/_/g," "],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[l,p],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,F],p],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[l,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[l,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[l,A+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,A+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[l,"Android "+y]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[p,q,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[l,b+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[l,p],[/(cobalt)\/([\w\.]+)/i],[l,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[_,"amd64"]],[/(ia32(?=;))/i],[[_,H]],[/((?:i[346]|x)86)[;\)]/i],[[_,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[_,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[_,"armhf"]],[/windows (ce|mobile); ppc;/i],[[_,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[_,/ower/,"",H]],[/(sun4\w)[;\)]/i],[[_,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[_,H]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[u,k],[h,f]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[d,[u,k],[h,m]],[/\((ip(?:hone|od)[\w ]*);/i],[d,[u,C],[h,m]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[u,C],[h,f]],[/(macintosh);/i],[d,[u,C]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[u,M],[h,m]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[u,O],[h,f]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[u,O],[h,m]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[d,/_/g," "],[u,x],[h,m]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[u,x],[h,f]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[u,"OPPO"],[h,m]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[u,"Vivo"],[h,m]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[d,[u,"Realme"],[h,m]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[u,P],[h,m]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[u,P],[h,f]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[u,N],[h,f]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[u,N],[h,m]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[u,"Lenovo"],[h,f]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[u,"Nokia"],[h,m]],[/(pixel c)\b/i],[d,[u,w],[h,f]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[u,w],[h,m]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[u,U],[h,m]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[u,U],[h,f]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[u,"OnePlus"],[h,m]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[u,R],[h,f]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[u,R],[h,m]],[/(playbook);[-\w\),; ]+(rim)/i],[d,u,[h,f]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[u,I],[h,m]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[u,v],[h,f]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[u,v],[h,m]],[/(nexus 9)/i],[d,[u,"HTC"],[h,f]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[u,[d,/_/g," "],[h,m]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[u,"Acer"],[h,f]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[u,"Meizu"],[h,m]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[u,d,[h,m]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[u,d,[h,f]],[/(surface duo)/i],[d,[u,D],[h,f]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[u,"Fairphone"],[h,m]],[/(u304aa)/i],[d,[u,"AT&T"],[h,m]],[/\bsie-(\w*)/i],[d,[u,"Siemens"],[h,m]],[/\b(rct\w+) b/i],[d,[u,"RCA"],[h,f]],[/\b(venue[\d ]{2,7}) b/i],[d,[u,"Dell"],[h,f]],[/\b(q(?:mv|ta)\w+) b/i],[d,[u,"Verizon"],[h,f]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[u,"Barnes & Noble"],[h,f]],[/\b(tm\d{3}\w+) b/i],[d,[u,"NuVision"],[h,f]],[/\b(k88) b/i],[d,[u,"ZTE"],[h,f]],[/\b(nx\d{3}j) b/i],[d,[u,"ZTE"],[h,m]],[/\b(gen\d{3}) b.+49h/i],[d,[u,"Swiss"],[h,m]],[/\b(zur\d{3}) b/i],[d,[u,"Swiss"],[h,f]],[/\b((zeki)?tb.*\b) b/i],[d,[u,"Zeki"],[h,f]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[u,"Dragon Touch"],d,[h,f]],[/\b(ns-?\w{0,9}) b/i],[d,[u,"Insignia"],[h,f]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[u,"NextBook"],[h,f]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[u,"Voice"],d,[h,m]],[/\b(lvtel\-)?(v1[12]) b/i],[[u,"LvTel"],d,[h,m]],[/\b(ph-1) /i],[d,[u,"Essential"],[h,m]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[u,"Envizen"],[h,f]],[/\b(trio[-\w\. ]+) b/i],[d,[u,"MachSpeed"],[h,f]],[/\btu_(1491) b/i],[d,[u,"Rotor"],[h,f]],[/(shield[\w ]+) b/i],[d,[u,"Nvidia"],[h,f]],[/(sprint) (\w+)/i],[u,d,[h,m]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[u,D],[h,m]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[u,V],[h,f]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[u,V],[h,m]],[/smart-tv.+(samsung)/i],[u,[h,g]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[u,k],[h,g]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[u,N],[h,g]],[/(apple) ?tv/i],[u,[d,C+" TV"],[h,g]],[/crkey/i],[[d,A+"cast"],[u,w],[h,g]],[/droid.+aft(\w)( bui|\))/i],[d,[u,R],[h,g]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[u,M],[h,g]],[/(bravia[\w ]+)( bui|\))/i],[d,[u,U],[h,g]],[/(mitv-\w{5}) bui/i],[d,[u,x],[h,g]],[/Hbbtv.*(technisat) (.*);/i],[u,d,[h,g]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[u,K],[d,K],[h,g]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,g]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[u,d,[h,E]],[/droid.+; (shield) bui/i],[d,[u,"Nvidia"],[h,E]],[/(playstation [345portablevi]+)/i],[d,[u,U],[h,E]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[u,D],[h,E]],[/((pebble))app/i],[u,d,[h,S]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[u,C],[h,S]],[/droid.+; (glass) \d/i],[d,[u,w],[h,S]],[/droid.+; (wt63?0{2,3})\)/i],[d,[u,V],[h,S]],[/(quest( 2| pro)?)/i],[d,[u,F],[h,S]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[u,[h,T]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[d,[h,m]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[h,f]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,f]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,m]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[u,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[l,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[l,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,p],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[l,[p,q,J]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[l,"Windows"],[p,q,J]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,j],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,p],[/\(bb(10);/i],[p,[l,I]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[l,b+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[l,A+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,B],p],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,p],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[l,p]]},X=function(e,t){if(typeof e===o&&(t=e,e=n),!(this instanceof X))return new X(e,t).getResult();var E=typeof i!==s&&i.navigator?i.navigator:n,g=e||(E&&E.userAgent?E.userAgent:""),S=E&&E.userAgentData?E.userAgentData:n,T=t?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(z,t):z;return this.getBrowser=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,T.browser),e[c]=function(e){return typeof e===a?e.replace(/[^\d\.]/g,"").split(".")[0]:n}(e[p]),E&&E.brave&&typeof E.brave.isBrave==r&&(e[l]="Brave"),e},this.getCPU=function(){var e={};return e[_]=n,Y.call(e,g,T.cpu),e},this.getDevice=function(){var e={};return e[u]=n,e[d]=n,e[h]=n,Y.call(e,g,T.device),!e[h]&&S&&S.mobile&&(e[h]=m),"Macintosh"==e[d]&&E&&typeof E.standalone!==s&&E.maxTouchPoints&&E.maxTouchPoints>2&&(e[d]="iPad",e[h]=f),e},this.getEngine=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,T.engine),e},this.getOS=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,T.os),!e[l]&&S&&"Unknown"!=S.platform&&(e[l]=S.platform.replace(/chrome os/i,B).replace(/macos/i,j)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return g},this.setUA=function(e){return g=typeof e===a&&e.length>350?K(e,350):e,this},this.setUA(g),this};X.VERSION="0.7.34",X.BROWSER=G([l,p,c]),X.CPU=G([_]),X.DEVICE=G([d,u,h,E,m,g,f,S,T]),X.ENGINE=X.OS=G([l,p]),e.exports&&(t=e.exports=X),t.UAParser=X;var Q=typeof i!==s&&(i.jQuery||i.Zepto);if(Q&&!Q.ua){var Z=new X;Q.ua=Z.getResult(),Q.ua.get=function(){return Z.getUA()},Q.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)Q.ua[i]=t[i]}}}("object"==typeof window?window:J)}(dg,dg.exports);const lg=new(z(dg.exports));let hg=lg.getResult(),ug=null;function pg(e){if(!ug){e&&lg.setUA(e),hg=lg.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return cg.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return cg.CHROME;case"Safari":case"Mobile Safari":return cg.SAFARI;case"Edge":return cg.EDGE;case"Firefox":return cg.FIREFOX;case"QQBrowser":return cg.QQ;case"Opera":return cg.OPERA;case"WeChat":return cg.WECHAT;default:return e.browser.name||""}}(hg),i=function(e){let t;return t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"",t.split(".")[0]}(hg),n=function(e){return"Windows"===e.os.name?e.os.version?e.os.name+" "+e.os.version:e.os.name:e.os.name||""}(hg),r=hg.os.version;if(!(t&&i&&n&&r))return{name:t,version:i,os:n,osVersion:r};ug={name:t,version:i,os:n,osVersion:r}}return ug}function _g(){return pg().os}function Eg(){const e=pg();return"".concat(e.os," ").concat(e.osVersion)}function mg(){const e=pg();return!!("WebKit"===hg.engine.name&&e.os===ag.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==cg.SAFARI||Cg()&&e.name!==cg.SAFARI)}function fg(){const e=pg();if(mg()){if(e.os===ag.MAC_OS)return!0;if(e.os===ag.IOS){const e=hg.os.version&&hg.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3)return!0;if(e&&Number(e[0])>14)return!0}}return!1}function gg(){return"WebKit"===hg.engine.name}function Sg(){return pg().name===cg.CHROME}function Tg(){return pg().name===cg.SAFARI}function Rg(){return pg().name===cg.FIREFOX}function Cg(){return pg().os===ag.IOS}function vg(e){const t=pg();return!(t.name!==cg.CHROME||!t.osVersion)&&Number(t.version)>=e}function Ig(e){const t=pg();return!(t.name!==cg.EDGE||!t.osVersion)&&Number(t.version)>=e}function yg(e){const t=pg();return!(t.name!==cg.OPERA||!t.osVersion)&&Number(t.version)>=e}function Ag(){const e=pg();return!(e.name!==cg.CHROME||!e.osVersion)&&Number(e.version)<=90}function bg(){const e=pg();if(e.os!==ag.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function wg(){const e=pg();if(e.os!==ag.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function Og(){const e=pg();if(e.os!==ag.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 16===Number(t[0])}function Ng(){const e=pg();if(e.os!==ag.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function Dg(){return Tg()&&navigator.maxTouchPoints>0}function Pg(){return pg().name===cg.WECHAT}function Lg(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function kg(){const e=pg();return e.name!==cg.EDGE&&e.name!==cg.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function Mg(){return _g()===ag.ANDROID}function Ug(){const e=pg();return Mg()&&(e.name===cg.CHROME||e.name===cg.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}var xg;!function(e){e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.TIMEOUT="TIMEOUT",e.INVALID_PARAMS="INVALID_PARAMS",e.NOT_READABLE="NOT_READABLE",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INVALID_OPERATION="INVALID_OPERATION",e.OPERATION_ABORTED="OPERATION_ABORTED",e.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",e.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",e.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",e.DATACHANNEL_FAILED="DATACHANNEL_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.NETWORK_TIMEOUT="NETWORK_TIMEOUT",e.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",e.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",e.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.ELECTRON_IS_NULL="ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",e.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",e.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",e.TRACK_IS_DISABLED="TRACK_IS_DISABLED",e.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",e.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",e.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",e.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",e.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",e.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",e.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",e.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",e.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",e.UID_CONFLICT="UID_CONFLICT",e.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",e.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",e.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",e.INVALID_TRACK="INVALID_TRACK",e.SENDER_NOT_FOUND="SENDER_NOT_FOUND",e.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",e.SET_ANSWER_FAILED="SET_ANSWER_FAILED",e.ICE_FAILED="ICE_FAILED",e.PC_CLOSED="PC_CLOSED",e.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",e.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",e.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",e.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",e.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",e.INVALID_REMOTE_USER="INVALID_REMOTE_USER",e.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",e.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",e.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",e.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",e.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",e.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",e.WS_ABORT="WS_ABORT",e.WS_DISCONNECT="WS_DISCONNECT",e.WS_ERR="WS_ERR",e.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",e.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",e.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",e.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",e.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",e.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",e.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",e.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",e.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",e.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",e.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",e.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",e.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",e.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",e.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",e.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",e.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",e.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",e.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",e.INVALID_PLUGIN="INVALID_PLUGIN",e.DISCONNECT_P2P="DISCONNECT_P2P",e.INIT_WEBSOCKET_TIMEOUT="INIT_WEBSOCKET_TIMEOUT",e.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",e.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",e.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",e.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",e.PROHIBITED_OPERATION="PROHIBITED_OPERATION",e.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED"}(xg||(xg={}));let Vg=class extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(t),nu(this,"code",void 0),nu(this,"message",void 0),nu(this,"data",void 0),nu(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=i}toString(){return this.data?"data: ".concat(JSON.stringify(this.data),"\n").concat(this.stack):"".concat(this.stack)}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error",t=arguments.length>1?arguments[1]:void 0;return"error"===e&&(t||console).error(this.toString()),"warning"===e&&(t||console).warn(this.toString()),this}throw(e){throw this.print("error",e),this}};function Fg(e,t){if("boolean"!=typeof e)throw new Vg(xg.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function Bg(e,t,i){if(!Lr(i).call(i,e))throw new Vg(xg.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)))}function jg(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(e<i||e>n||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return"number"==typeof e&&e%1==0}(e))throw new Vg(xg.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(n,"]. integer only"))}function Gg(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new Vg(xg.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&jg(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&jg(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&jg(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&jg(e.ideal,"".concat(t,".ideal"),1,1/0)}else jg(e,t,1,1/0)}function Wg(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new Vg(xg.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!Yg(e,i,n,r))throw new Vg(xg.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""))}function Hg(e,t){if(!Array.isArray(e))throw new Vg(xg.INVALID_PARAMS,"".concat(t," should be an array"))}function Kg(e){return null==e}function Yg(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return"string"==typeof e&&e.length<=i&&e.length>=t&&(!n||function(e){if("string"!=typeof e)return!1;for(let t=0;t<e.length;t+=1){const i=e.charCodeAt(t);if(i<0||i>255)return!1}return!0}(e))}function qg(e,t,i){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,i);const n=e.getUint32(t,i),r=e.getUint32(t+4,i),s=Number(!!i),o=Number(!i);return BigInt(n*o+r*s)<<BigInt(32)|BigInt(n*s+r*o)}function Jg(e,t,i,n){if("setBigUint64"in DataView.prototype)return e.setBigUint64(t,i,n);const r=Number(i>>BigInt(32)),s=Number(i&BigInt(4294967295));n?(e.setUint32(t+4,r,n),e.setUint32(t,s,n)):(e.setUint32(t,r,n),e.setUint32(t+4,s,n))}var zg,Xg;!function(e){e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE"}(zg||(zg={})),function(e){e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT"}(Xg||(Xg={}));const Qg=new class{constructor(){nu(this,"_clientSize",null),nu(this,"getClientWidth",(()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth)),nu(this,"getClientHeight",(()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight)),nu(this,"getStyle",(e=>window.getComputedStyle(e,null))),nu(this,"checkCssVisibleProperty",(e=>{var t;let i=!0;const n=this.getStyle(e),{display:r,visibility:s,opacity:o,filter:a}=n;return("none"===r||Lr(t=["hidden","collapse"]).call(t,s)||Number(o)<.1)&&(i=!1),!!i&&(a&&a.split(" ").filter((e=>{var t;const i=e.split("(")[0];return Lr(t=["brightness","blur","opacity"]).call(t,i)})).map((e=>{const[t,i]=e.split(/\(|\)/);return[t,Number(i.match(/^[0-9\.]+/))]})).forEach((e=>{const[t,n]=e;switch(t){case"brightness":(n<.1||n>3)&&(i=!1);break;case"blur":n>3&&(i=!1);break;case"opacity":n<.1&&(i=!1)}})),i)})),nu(this,"checkPropertyUpToAllParentNodes",((e,t)=>{let i=!0,n=!0;const r=e=>t(e);let s=e;for(;s&&n;)r(s)||(i=!1,n=!1),s=s.parentElement,s||(n=!1);return i})),nu(this,"checkActualCssVisibleIncludeInherit",(e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty))),nu(this,"getSizeAboutClient",(e=>{const{width:t,height:i,left:n,right:r,top:s,bottom:o}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return{width:t,height:i,left:n,right:r,top:s,bottom:o,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)}})),nu(this,"checkActualSize",(()=>{const{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i)})),nu(this,"elementFromPoint",((e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null)),nu(this,"checkCoverForAPoint",((e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i})),nu(this,"getPointPositionList",(()=>{const{width:e,height:t,left:i,top:n}=this._clientSize,r=e/6,s=t/6,o=[],a=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const c=(i*a+(0===e?.1:4===e?(r*e*a-1e5)/a:r*e)*a)/a,d=(n*a+(0===t?.1:4===t?(s*t*a-1e5)/a:s*t)*a)/a;o.push({x:c,y:d})}return[...o]})),nu(this,"checkElementCover",(e=>this.getPointPositionList().map((t=>this.checkCoverForAPoint(t.x,t.y,e))).filter((e=>!!e)).length>6)),nu(this,"checkSizeIsVisible",((e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10))),nu(this,"checkSizeOfPartInClient",(()=>{const{left:e,right:t,top:i,bottom:n,clientHeight:r,clientWidth:s,clientMin:o}=this._clientSize;let a,c,d,l;if(e<0)a=0;else{if(!(e<s))return!1;a=e}if(t<0)return!1;if(c=t<s?t:s,i<0)d=0;else{if(!(i<r))return!1;d=i}if(n<0)return!1;l=n<r?n:r;const h=c-a,u=l-d;return this.checkSizeIsVisible(h,u,o)})),nu(this,"returnHiddenResult",(e=>(this._clientSize=null,{visible:!1,reason:e}))),nu(this,"checkOneElementVisible",(e=>{if(e instanceof HTMLElement){if(this.checkElementIsMountedOnDom(e)){if(this.checkActualCssVisibleIncludeInherit(e)){if(this._clientSize=this.getSizeAboutClient(e),this.checkElementCover(e))return this.returnHiddenResult(zg.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(zg.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(zg.SIZE)}}return this.returnHiddenResult(zg.STYLE)}return this.returnHiddenResult(Xg.UNMOUNTED)}return this.returnHiddenResult(Xg.INVALID_HTML_ELEMENT)})),nu(this,"checkElementIsMountedOnDom",(e=>this.checkPropertyUpToAllParentNodes(e,(e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))))}};function Zg(e){return(new TextEncoder).encode(e)}const $g=function(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i},eS=async e=>{const t=function(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i}("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),i=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),n=Zg(e),r=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},i,n);return function(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}(new Uint8Array(r))},tS=async e=>function(e,t){let i="";return new Uint8Array(e).forEach((e=>{i+=e.toString(t).padStart(2,"0")})),i}(await crypto.subtle.digest("SHA-256",Zg(e)),16);class iS{constructor(){nu(this,"_events",{}),nu(this,"addListener",this.on)}getListeners(e){return this._events[e]?this._events[e].map((e=>e.listener)):[]}on(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const i=this._events[e],n=this._indexOfListener(i,t);-1!==n&&i.splice(n,1),0===this._events[e].length&&delete this._events[e]}removeAllListeners(e){e?delete this._events[e]:this._events={}}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map((e=>e));for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];for(let i=0;i<t.length;i+=1){const r=t[i];r.once&&this.off(e,r.listener),r.listener.apply(this,n||[])}}safeEmit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];[...this._events[e]||[]].forEach((t=>{t.once&&this.off(e,t.listener);try{t.listener.apply(this,i)}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()))}}))}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return-1}}let nS=null;function rS(){if(nS)return nS;if(window.electron)return nS=window.electron;if(!window.require)return null;try{return nS=window.require("electron"),nS}catch(e){return null}}var sS,oS,aS,cS,dS,lS,hS,uS;function pS(e){return jg(e.timeout,"config.timeout",0,1e5),jg(e.timeoutFactor,"config.timeoutFactor",0,100,!1),jg(e.maxRetryCount,"config.maxRetryConfig",0,1/0),jg(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}function _S(e){if(!Array.isArray(e)||e.length<1)return!1;try{e.forEach((e=>{if(!e.urls)throw Error()}))}catch(e){return!1}return!0}function ES(e){return Wg(e.turnServerURL,"turnServerURL"),Wg(e.username,"username"),Wg(e.password,"password"),e.udpport&&jg(e.udpport,"udpport",1,99999,!0),e.forceturn&&Fg(e.forceturn,"forceturn"),e.security&&Fg(e.security,"security"),e.tcpport&&jg(e.tcpport,"tcpport",1,99999,!0),!0}function mS(e){return void 0!==e.level&&Bg(e.level,"level",[1,2,3]),void 0!==e.delay&&jg(e.delay,"delay",0,3e3,!0),!0}function fS(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return 0===e.getListeners(t).length?tg.reject(new Vg(xg.UNEXPECTED_ERROR,"can not emit promise")):new tg(((i,r)=>{e.emit(t,...n,i,r)}))}function gS(e,t){if(0===e.getListeners(t).length)return tg.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return fS(e,t,...n)}function SS(e,t){if(0===e.getListeners(t).length)return null;for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return TS(e,t,...n)}function TS(e,t){let i=null,n=null;for(var r=arguments.length,s=new Array(r>2?r-2:0),o=2;o<r;o++)s[o-2]=arguments[o];if(e.emit(t,...s,(e=>{i=e}),(e=>{n=e})),null!==n)throw n;if(null===i)throw new Vg(xg.UNEXPECTED_ERROR,"handler is not sync");return i}!function(e){e.CREATE_CLIENT="createClient",e.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",e.SET_AREA="setArea",e.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",e.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",e.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",e.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",e.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",e.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",e.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",e.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",e.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",e.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",e.START_PROXY_SERVER="Client.startProxyServer",e.STOP_PROXY_SERVER="Client.stopProxyServer",e.SET_PROXY_SERVER="Client.setProxyServer",e.SET_TURN_SERVER="Client.setTurnServer",e.SET_CLIENT_ROLE="Client.setClientRole",e.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",e.ENABLE_DUAL_STREAM="Client.enableDualStream",e.DISABLE_DUAL_STREAM="Client.disableDualStream",e.JOIN="Client.join",e.LEAVE="Client.leave",e.PUBLISH="Client.publish",e.UNPUBLISH="Client.unpublish",e.SUBSCRIBE="Client.subscribe",e.MASS_SUBSCRIBE="Client.massSubscribe",e.MASS_UNSUBSCRIBE="Client.massUnsubscribe",e.UNSUBSCRIBE="Client.unsubscribe",e.RENEW_TOKEN="Client.renewToken",e.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",e.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",e.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",e.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",e.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",e.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",e.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",e.DATACHANNEL_FAILBACK="Client._datachannelFailback",e.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",e.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",e.START_LIVE_STREAMING="Client.startLiveStreaming",e.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",e.STOP_LIVE_STREAMING="Client.stopLiveStreaming",e.ADD_INJECT_STREAM_URL="Client.addInjectStreamUrl",e.REMOVE_INJECT_STREAM_URL="Client.removeInjectStreamUrl",e.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",e.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",e.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",e.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",e.SET_CONFIG_DISTRIBUTE="_configDistribute",e.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",e.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",e.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",e.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",e.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",e.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",e.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",e.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",e.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",e.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",e.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",e.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",e.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",e.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",e.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",e.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",e.STREAM_TYPE_CHANGE="streamTypeChange",e.CONNECTION_STATE_CHANGE="connectionStateChange",e.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",e.IMAGE_MODERATION_UPLOAD="imageModerationUpload"}(sS||(sS={})),function(e){e.TRACER="tracer"}(oS||(oS={})),function(e){e[e.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",e[e.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",e[e.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY"}(aS||(aS={})),function(e){e.LEAVE="LEAVE",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.UID_BANNED="UID_BANNED",e.IP_BANNED="IP_BANNED",e.CHANNEL_BANNED="CHANNEL_BANNED",e.FALLBACK="FALLBACK",e.LICENSE_MISSING="LICENSE_MISSING",e.LICENSE_EXPIRED="LICENSE_EXPIRED",e.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",e.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",e.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",e.LICENSE_ILLEGAL="LICENSE_ILLEGAL",e.TOKEN_EXPIRE="TOKEN_EXPIRE"}(cS||(cS={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.MEDIA_RECONNECT_START="media-reconnect-start",e.MEDIA_RECONNECT_END="media-reconnect-end",e.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",e.USER_JOINED="user-joined",e.USER_LEAVED="user-left",e.USER_PUBLISHED="user-published",e.USER_UNPUBLISHED="user-unpublished",e.USER_INFO_UPDATED="user-info-updated",e.CLIENT_BANNED="client-banned",e.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",e.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",e.VOLUME_INDICATOR="volume-indicator",e.CRYPT_ERROR="crypt-error",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGED="stream-type-changed",e.STREAM_FALLBACK="stream-fallback",e.RECEIVE_METADATA="receive-metadata",e.STREAM_MESSAGE="stream-message",e.LIVE_STREAMING_ERROR="live-streaming-error",e.LIVE_STREAMING_WARNING="live-streaming-warning",e.INJECT_STREAM_STATUS="stream-inject-status",e.EXCEPTION="exception",e.ERROR="error",e.P2P_LOST="p2p_lost",e.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",e.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",e.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",e.PUBLISHED_USER_LIST="published-user-list",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",e.CONTENT_INSPECT_ERROR="content-inspect-error",e.CONTENT_INSPECT_RESULT="content-inspect-result",e.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change"}(dS||(dS={})),function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK"}(lS||(lS={})),function(e){e.ONLINE="ONLINE",e.OFFLINE="OFFLINE"}(hS||(hS={})),function(e){e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE"}(uS||(uS={}));const RS=new class extends iS{set networkState(e){this.emit(uS.NETWORK_STATE_CHANGE,e,this._networkState),e===hS.ONLINE?this.emit(uS.ONLINE):e===hS.OFFLINE&&(this.onlineWaiter=new tg((e=>{this.once(uS.ONLINE,(()=>{this.onlineWaiter=void 0,e(hS.ONLINE)}))})),this.emit(uS.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===hS.ONLINE}constructor(){super(),nu(this,"_moduleName","network-indicator"),nu(this,"_networkState",hS.ONLINE),nu(this,"onlineWaiter",void 0),window.addEventListener("online",(()=>{this.networkState=hS.ONLINE})),window.addEventListener("offline",(()=>{this.networkState=hS.OFFLINE}))}};function CS(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function vS(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?CS(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):CS(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function IS(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1)}function yS(e){const t=[];return e.forEach((e=>{-1===t.indexOf(e)&&t.push(e)})),t}function AS(e){void 0!==tg?tg.resolve().then(e):setTimeout(e,0)}function bS(e){return JSON.parse(JSON.stringify(e))}function wS(e){try{return bS(e)}catch(t){return e}}const OS={};function NS(e,t){OS[t]||(OS[t]=!0,e())}function DS(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i}function PS(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}function LS(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function kS(e){let t=0;return/DingTalk/i.test(navigator.userAgent)&&e.realFormData&&(e=e.realFormData),e.forEach((e=>{t+="string"==typeof e?LS(e):e.size})),t+138}function MS(e){const t=new Vg(xg.TIMEOUT,"timeout");return new tg(((i,n)=>{window.setTimeout((()=>n(t)),e)}))}function US(e){return new tg((t=>{window.setTimeout(t,e)}))}function xS(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const i=Math.random().toString(16).substr(2,e).toLowerCase();return i.length===e?"".concat(t).concat(i):"".concat(t).concat(i)+xS(e-i.length,"")}function VS(){return xS(32,"").toUpperCase()}const FS=()=>{},BS=new class{constructor(){nu(this,"fnMap",new Map)}throttleByKey(e,t,i,n){for(var r=arguments.length,s=new Array(r>4?r-4:0),o=4;o<r;o++)s[o-4]=arguments[o];if(this.fnMap.has(t)){const r=this.fnMap.get(t);if(r.threshold!==i){r.fn(...r.args),clearTimeout(r.timer);const o=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:o,args:s,skipFn:n})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,vS(vS({},r),{},{fn:e,args:s,skipFn:n}))}else{const r=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:r,args:s,skipFn:n})}}},jS=BS.throttleByKey.bind(BS);function GS(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}function WS(e,t){if(!GS(e)||!GS(t))return t;if(Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const i=[...e];for(let n=0;n<t.length;n++)i[n]=WS(e[n],t[n]);return i}{const i=vS({},e);for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(Object.prototype.hasOwnProperty.call(e,n)?i[n]=WS(e[n],t[n]):i[n]=t[n]);return i}}let HS=1,KS=console;class YS{static setLogger(e){KS=e}constructor(e){nu(this,"lockingPromise",tg.resolve()),nu(this,"locks",0),nu(this,"name",""),nu(this,"lockId",void 0),this.lockId=HS++,e&&(this.name=e),KS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is created."))}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,KS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:""));const i=new tg((i=>{t=()=>{this.locks-=1,KS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is not locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:"")),i()}})),n=this.lockingPromise.then((()=>t));return this.lockingPromise=this.lockingPromise.then((()=>i)),n}}function qS(e,t){return function(i,n,r){const s=r.value;if("function"!=typeof s)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const i=this[t];if(!i)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await i.lock("From ".concat(e,".").concat(n));try{for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return await s.apply(this,a)}finally{r()}},r}}const JS={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function zS(e,t){const i=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,i)}function XS(e,t,i,n){const r=Object.assign({},JS,n);let s=r.timeout;const o=async()=>{await function(e){return new tg((t=>{window.setTimeout(t,e)}))}(s),s*=r.timeoutFactor,s=Math.min(r.maxRetryTimeout,s)};let a=!1;const c=new tg((async(n,s)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;c<r.maxRetryCount;c+=1){if(a)return s(new Vg(xg.OPERATION_ABORTED));try{const i=await e();if(!t(i,c))return n(i);if(c+1===r.maxRetryCount)return n(i);await o()}catch(e){if(!i(e,c))return s(e);if(c+1===r.maxRetryCount)return s(e);await o()}}}));return c.cancel=()=>a=!0,c}var QS=xt,ZS=ti,$S=Qe,eT=qn,tT=TypeError,iT=function(e){return function(t,i,n,r){QS(i);var s=ZS(t),o=$S(s),a=eT(s),c=e?a-1:0,d=e?-1:1;if(n<2)for(;;){if(c in o){r=o[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw tT("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=d)c in o&&(r=i(r,o[c],c,s));return r}},nT=[iT(!1),iT(!0)][0];Mn({target:"Array",proto:!0,forced:!C_&&Rt>79&&Rt<83||!Ru("reduce")},{reduce:function(e){var t=arguments.length;return nT(this,e,t,t>1?arguments[1]:void 0)}});var rT=tr("Array").reduce,sT=me,oT=rT,aT=Array.prototype,cT=z((function(e){var t=e.reduce;return e===aT||sT(aT,e)&&t===aT.reduce?oT:t}));let dT=class{constructor(e){nu(this,"input",[]),nu(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}mean(){var e;return 0===this.input.length?0:cT(e=this.input).call(e,((e,t)=>e+t))/this.input.length}};var lT,hT={exports:{}},uT=function(e,t){return function(){for(var i=new Array(arguments.length),n=0;n<i.length;n++)i[n]=arguments[n];return e.apply(t,i)}},pT=uT,_T=Object.prototype.toString,ET=(lT=Object.create(null),function(e){var t=_T.call(e);return lT[t]||(lT[t]=t.slice(8,-1).toLowerCase())});function mT(e){return e=e.toLowerCase(),function(t){return ET(t)===e}}function fT(e){return Array.isArray(e)}function gT(e){return void 0===e}var ST=mT("ArrayBuffer");function TT(e){return null!==e&&"object"==typeof e}function RT(e){if("object"!==ET(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var CT=mT("Date"),vT=mT("File"),IT=mT("Blob"),yT=mT("FileList");function AT(e){return"[object Function]"===_T.call(e)}var bT=mT("URLSearchParams");function wT(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),fT(e))for(var i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.call(null,e[r],r,e)}var OT,NT=(OT="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return OT&&e instanceof OT}),DT={isArray:fT,isArrayBuffer:ST,isBuffer:function(e){return null!==e&&!gT(e)&&null!==e.constructor&&!gT(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){var t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||_T.call(e)===t||AT(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&ST(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:TT,isPlainObject:RT,isUndefined:gT,isDate:CT,isFile:vT,isBlob:IT,isFunction:AT,isStream:function(e){return TT(e)&&AT(e.pipe)},isURLSearchParams:bT,isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:wT,merge:function e(){var t={};function i(i,n){RT(t[n])&&RT(i)?t[n]=e(t[n],i):RT(i)?t[n]=e({},i):fT(i)?t[n]=i.slice():t[n]=i}for(var n=0,r=arguments.length;n<r;n++)wT(arguments[n],i);return t},extend:function(e,t,i){return wT(t,(function(t,n){e[n]=i&&"function"==typeof t?pT(t,i):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},inherits:function(e,t,i,n){e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,i&&Object.assign(e.prototype,i)},toFlatObject:function(e,t,i){var n,r,s,o={};t=t||{};do{for(r=(n=Object.getOwnPropertyNames(e)).length;r-- >0;)o[s=n[r]]||(t[s]=e[s],o[s]=!0);e=Object.getPrototypeOf(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:ET,kindOfTest:mT,endsWith:function(e,t,i){e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;var n=e.indexOf(t,i);return-1!==n&&n===i},toArray:function(e){if(!e)return null;var t=e.length;if(gT(t))return null;for(var i=new Array(t);t-- >0;)i[t]=e[t];return i},isTypedArray:NT,isFileList:yT},PT=DT;function LT(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var kT=function(e,t,i){if(!t)return e;var n;if(i)n=i(t);else if(PT.isURLSearchParams(t))n=t.toString();else{var r=[];PT.forEach(t,(function(e,t){null!=e&&(PT.isArray(e)?t+="[]":e=[e],PT.forEach(e,(function(e){PT.isDate(e)?e=e.toISOString():PT.isObject(e)&&(e=JSON.stringify(e)),r.push(LT(t)+"="+LT(e))})))})),n=r.join("&")}if(n){var s=e.indexOf("#");-1!==s&&(e=e.slice(0,s)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e},MT=DT;function UT(){this.handlers=[]}UT.prototype.use=function(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1},UT.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},UT.prototype.forEach=function(e){MT.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var xT,VT,FT=UT,BT=DT;function jT(){if(VT)return xT;VT=1;var e=DT;function t(e,t,i,n,r){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r)}e.inherits(t,Error,{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,status:this.response&&this.response.status?this.response.status:null}}});var i=t.prototype,n={};return["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach((function(e){n[e]={value:e}})),Object.defineProperties(t,n),Object.defineProperty(i,"isAxiosError",{value:!0}),t.from=function(n,r,s,o,a,c){var d=Object.create(i);return e.toFlatObject(n,d,(function(e){return e!==Error.prototype})),t.call(d,n.message,r,s,o,a),d.name=n.name,c&&Object.assign(d,c),d},xT=t}var GT,WT,HT,KT,YT,qT,JT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};function zT(){if(WT)return GT;WT=1;var e=DT;return GT=function(t,i){i=i||new FormData;var n=[];function r(t){return null===t?"":e.isDate(t)?t.toISOString():e.isArrayBuffer(t)||e.isTypedArray(t)?"function"==typeof Blob?new Blob([t]):Buffer.from(t):t}return function t(s,o){if(e.isPlainObject(s)||e.isArray(s)){if(-1!==n.indexOf(s))throw Error("Circular reference detected in "+o);n.push(s),e.forEach(s,(function(n,s){if(!e.isUndefined(n)){var a,c=o?o+"."+s:s;if(n&&!o&&"object"==typeof n)if(e.endsWith(s,"{}"))n=JSON.stringify(n);else if(e.endsWith(s,"[]")&&(a=e.toArray(n)))return void a.forEach((function(t){!e.isUndefined(t)&&i.append(c,r(t))}));t(n,c)}})),n.pop()}else i.append(o,r(s))}(t),i},GT}function XT(){if(KT)return HT;KT=1;var e=jT();return HT=function(t,i,n){var r=n.config.validateStatus;n.status&&r&&!r(n.status)?i(new e("Request failed with status code "+n.status,[e.ERR_BAD_REQUEST,e.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):t(n)}}function QT(){if(qT)return YT;qT=1;var e=DT;return YT=e.isStandardBrowserEnv()?{write:function(t,i,n,r,s,o){var a=[];a.push(t+"="+encodeURIComponent(i)),e.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),e.isString(r)&&a.push("path="+r),e.isString(s)&&a.push("domain="+s),!0===o&&a.push("secure"),document.cookie=a.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(){}},YT}var ZT,$T,eR,tR,iR,nR,rR,sR,oR,aR,cR,dR,lR=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},hR=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},uR=function(e,t){return e&&!lR(t)?hR(e,t):t};function pR(){if($T)return ZT;$T=1;var e=DT,t=["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"];return ZT=function(i){var n,r,s,o={};return i?(e.forEach(i.split("\n"),(function(i){if(s=i.indexOf(":"),n=e.trim(i.substr(0,s)).toLowerCase(),r=e.trim(i.substr(s+1)),n){if(o[n]&&t.indexOf(n)>=0)return;o[n]="set-cookie"===n?(o[n]?o[n]:[]).concat([r]):o[n]?o[n]+", "+r:r}})),o):o},ZT}function _R(){if(tR)return eR;tR=1;var e=DT;return eR=e.isStandardBrowserEnv()?function(){var t,i=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function r(e){var t=e;return i&&(n.setAttribute("href",t),t=n.href),n.setAttribute("href",t),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return t=r(window.location.href),function(i){var n=e.isString(i)?r(i):i;return n.protocol===t.protocol&&n.host===t.host}}():function(){return!0}}function ER(){if(nR)return iR;nR=1;var e=jT();function t(t){e.call(this,null==t?"canceled":t,e.ERR_CANCELED),this.name="CanceledError"}return DT.inherits(t,e,{__CANCEL__:!0}),iR=t}function mR(){return sR||(sR=1,rR=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}),rR}function fR(){if(aR)return oR;aR=1;var e=DT,t=XT(),i=QT(),n=kT,r=uR,s=pR(),o=_R(),a=JT,c=jT(),d=ER(),l=mR();return oR=function(h){return new Promise((function(u,p){var _,E=h.data,m=h.headers,f=h.responseType;function g(){h.cancelToken&&h.cancelToken.unsubscribe(_),h.signal&&h.signal.removeEventListener("abort",_)}e.isFormData(E)&&e.isStandardBrowserEnv()&&delete m["Content-Type"];var S=new XMLHttpRequest;if(h.auth){var T=h.auth.username||"",R=h.auth.password?unescape(encodeURIComponent(h.auth.password)):"";m.Authorization="Basic "+btoa(T+":"+R)}var C=r(h.baseURL,h.url);function v(){if(S){var e="getAllResponseHeaders"in S?s(S.getAllResponseHeaders()):null,i={data:f&&"text"!==f&&"json"!==f?S.response:S.responseText,status:S.status,statusText:S.statusText,headers:e,config:h,request:S};t((function(e){u(e),g()}),(function(e){p(e),g()}),i),S=null}}if(S.open(h.method.toUpperCase(),n(C,h.params,h.paramsSerializer),!0),S.timeout=h.timeout,"onloadend"in S?S.onloadend=v:S.onreadystatechange=function(){S&&4===S.readyState&&(0!==S.status||S.responseURL&&0===S.responseURL.indexOf("file:"))&&setTimeout(v)},S.onabort=function(){S&&(p(new c("Request aborted",c.ECONNABORTED,h,S)),S=null)},S.onerror=function(){p(new c("Network Error",c.ERR_NETWORK,h,S,S)),S=null},S.ontimeout=function(){var e=h.timeout?"timeout of "+h.timeout+"ms exceeded":"timeout exceeded",t=h.transitional||a;h.timeoutErrorMessage&&(e=h.timeoutErrorMessage),p(new c(e,t.clarifyTimeoutError?c.ETIMEDOUT:c.ECONNABORTED,h,S)),S=null},e.isStandardBrowserEnv()){var I=(h.withCredentials||o(C))&&h.xsrfCookieName?i.read(h.xsrfCookieName):void 0;I&&(m[h.xsrfHeaderName]=I)}"setRequestHeader"in S&&e.forEach(m,(function(e,t){void 0===E&&"content-type"===t.toLowerCase()?delete m[t]:S.setRequestHeader(t,e)})),e.isUndefined(h.withCredentials)||(S.withCredentials=!!h.withCredentials),f&&"json"!==f&&(S.responseType=h.responseType),"function"==typeof h.onDownloadProgress&&S.addEventListener("progress",h.onDownloadProgress),"function"==typeof h.onUploadProgress&&S.upload&&S.upload.addEventListener("progress",h.onUploadProgress),(h.cancelToken||h.signal)&&(_=function(e){S&&(p(!e||e&&e.type?new d:e),S.abort(),S=null)},h.cancelToken&&h.cancelToken.subscribe(_),h.signal&&(h.signal.aborted?_():h.signal.addEventListener("abort",_))),E||(E=null);var y=l(C);y&&-1===["http","https","file"].indexOf(y)?p(new c("Unsupported protocol "+y+":",c.ERR_BAD_REQUEST,h)):S.send(E)}))},oR}var gR=DT,SR=function(e,t){BT.forEach(e,(function(i,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=i,delete e[n])}))},TR=jT(),RR=JT,CR=zT(),vR={"Content-Type":"application/x-www-form-urlencoded"};function IR(e,t){!gR.isUndefined(e)&&gR.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var yR,AR={transitional:RR,adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(yR=fR()),yR),transformRequest:[function(e,t){if(SR(t,"Accept"),SR(t,"Content-Type"),gR.isFormData(e)||gR.isArrayBuffer(e)||gR.isBuffer(e)||gR.isStream(e)||gR.isFile(e)||gR.isBlob(e))return e;if(gR.isArrayBufferView(e))return e.buffer;if(gR.isURLSearchParams(e))return IR(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var i,n=gR.isObject(e),r=t&&t["Content-Type"];if((i=gR.isFileList(e))||n&&"multipart/form-data"===r){var s=this.env&&this.env.FormData;return CR(i?{"files[]":e}:e,s&&new s)}return n||"application/json"===r?(IR(t,"application/json"),function(e,t,i){if(gR.isString(e))try{return(t||JSON.parse)(e),gR.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||AR.transitional,i=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,r=!i&&"json"===this.responseType;if(r||n&&gR.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw TR.from(e,TR.ERR_BAD_RESPONSE,this,null,this.response);throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:dR?cR:(dR=1,cR=null)},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};gR.forEach(["delete","get","head"],(function(e){AR.headers[e]={}})),gR.forEach(["post","put","patch"],(function(e){AR.headers[e]=gR.merge(vR)}));var bR,wR,OR=AR,NR=DT,DR=OR;function PR(){return wR?bR:(wR=1,bR=function(e){return!(!e||!e.__CANCEL__)})}var LR=DT,kR=function(e,t,i){var n=this||DR;return NR.forEach(i,(function(i){e=i.call(n,e,t)})),e},MR=PR(),UR=OR,xR=ER();function VR(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new xR}var FR,BR,jR=DT,GR=function(e,t){t=t||{};var i={};function n(e,t){return jR.isPlainObject(e)&&jR.isPlainObject(t)?jR.merge(e,t):jR.isPlainObject(t)?jR.merge({},t):jR.isArray(t)?t.slice():t}function r(i){return jR.isUndefined(t[i])?jR.isUndefined(e[i])?void 0:n(void 0,e[i]):n(e[i],t[i])}function s(e){if(!jR.isUndefined(t[e]))return n(void 0,t[e])}function o(i){return jR.isUndefined(t[i])?jR.isUndefined(e[i])?void 0:n(void 0,e[i]):n(void 0,t[i])}function a(i){return i in t?n(e[i],t[i]):i in e?n(void 0,e[i]):void 0}var c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a};return jR.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=c[e]||r,n=t(e);jR.isUndefined(n)&&t!==a||(i[e]=n)})),i};function WR(){return BR?FR:(BR=1,FR={version:"0.27.2"})}var HR=WR().version,KR=jT(),YR={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){YR[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));var qR={};YR.transitional=function(e,t,i){function n(e,t){return"[Axios v"+HR+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return function(i,r,s){if(!1===e)throw new KR(n(r," has been removed"+(t?" in "+t:"")),KR.ERR_DEPRECATED);return t&&!qR[r]&&(qR[r]=!0,console.warn(n(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,r,s)}};var JR,zR,XR,QR,ZR,$R,eC={assertOptions:function(e,t,i){if("object"!=typeof e)throw new KR("options must be an object",KR.ERR_BAD_OPTION_VALUE);for(var n=Object.keys(e),r=n.length;r-- >0;){var s=n[r],o=t[s];if(o){var a=e[s],c=void 0===a||o(a,s,e);if(!0!==c)throw new KR("option "+s+" must be "+c,KR.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new KR("Unknown option "+s,KR.ERR_BAD_OPTION)}},validators:YR},tC=DT,iC=kT,nC=FT,rC=function(e){return VR(e),e.headers=e.headers||{},e.data=kR.call(e,e.data,e.headers,e.transformRequest),e.headers=LR.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),LR.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||UR.adapter)(e).then((function(t){return VR(e),t.data=kR.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return MR(t)||(VR(e),t&&t.response&&(t.response.data=kR.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},sC=GR,oC=uR,aC=eC,cC=aC.validators;function dC(e){this.defaults=e,this.interceptors={request:new nC,response:new nC}}dC.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=sC(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var i=t.transitional;void 0!==i&&aC.assertOptions(i,{silentJSONParsing:cC.transitional(cC.boolean),forcedJSONParsing:cC.transitional(cC.boolean),clarifyTimeoutError:cC.transitional(cC.boolean)},!1);var n=[],r=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(r=r&&e.synchronous,n.unshift(e.fulfilled,e.rejected))}));var s,o=[];if(this.interceptors.response.forEach((function(e){o.push(e.fulfilled,e.rejected)})),!r){var a=[rC,void 0];for(Array.prototype.unshift.apply(a,n),a=a.concat(o),s=Promise.resolve(t);a.length;)s=s.then(a.shift(),a.shift());return s}for(var c=t;n.length;){var d=n.shift(),l=n.shift();try{c=d(c)}catch(e){l(e);break}}try{s=rC(c)}catch(e){return Promise.reject(e)}for(;o.length;)s=s.then(o.shift(),o.shift());return s},dC.prototype.getUri=function(e){e=sC(this.defaults,e);var t=oC(e.baseURL,e.url);return iC(t,e.params,e.paramsSerializer)},tC.forEach(["delete","get","head","options"],(function(e){dC.prototype[e]=function(t,i){return this.request(sC(i||{},{method:e,url:t,data:(i||{}).data}))}})),tC.forEach(["post","put","patch"],(function(e){function t(t){return function(i,n,r){return this.request(sC(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}dC.prototype[e]=t(),dC.prototype[e+"Form"]=t(!0)}));var lC=DT,hC=uT,uC=dC,pC=GR,_C=function e(t){var i=new uC(t),n=hC(uC.prototype.request,i);return lC.extend(n,uC.prototype,i),lC.extend(n,i),n.create=function(i){return e(pC(t,i))},n}(OR);_C.Axios=uC,_C.CanceledError=ER(),_C.CancelToken=function(){if(zR)return JR;zR=1;var e=ER();function t(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var i;this.promise=new Promise((function(e){i=e}));var n=this;this.promise.then((function(e){if(n._listeners){var t,i=n._listeners.length;for(t=0;t<i;t++)n._listeners[t](e);n._listeners=null}})),this.promise.then=function(e){var t,i=new Promise((function(e){n.subscribe(e),t=e})).then(e);return i.cancel=function(){n.unsubscribe(t)},i},t((function(t){n.reason||(n.reason=new e(t),i(n.reason))}))}return t.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},t.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},t.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},t.source=function(){var e;return{token:new t((function(t){e=t})),cancel:e}},JR=t}(),_C.isCancel=PR(),_C.VERSION=WR().version,_C.toFormData=zT(),_C.AxiosError=jT(),_C.Cancel=_C.CanceledError,_C.all=function(e){return Promise.all(e)},_C.spread=QR?XR:(QR=1,XR=function(e){return function(t){return e.apply(null,t)}}),_C.isAxiosError=function(){if($R)return ZR;$R=1;var e=DT;return ZR=function(t){return e.isObject(t)&&!0===t.isAxiosError}}(),hT.exports=_C,hT.exports.default=_C;var EC=z(hT.exports);function mC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function fC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?mC(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):mC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let gC,SC=0,TC=0;function RC(e,t,i,n){return new tg(((r,s)=>{t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),SC+=LS(t.data)):i&&(t.data.size?SC+=t.data.size:t.data instanceof FormData?SC+=kS(t.data):SC+=LS(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,EC.request(t).then((e=>{"string"==typeof e.data?TC+=LS(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?TC+=e.data.byteLength:TC+=LS(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{EC.isCancel(e)?s(new Vg(xg.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new Vg(xg.NETWORK_TIMEOUT,e.message)):e.response?s(new Vg(xg.NETWORK_RESPONSE_ERROR,e.response.status)):s(new Vg(xg.NETWORK_ERROR,e.message))}))}))}async function CC(e,t){const i=new Blob([t.data],{type:"buffer"});return await RC(e,fC(fC({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)}const vC=()=>"HTTPS"===(gC||gC||(gC=(window.location.protocol.split(":")[0]||"").toUpperCase(),gC)),IC=()=>void 0!==window.isSecureContext;function yC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function AC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?yC(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):yC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}var bC;!function(e){e.SET_SESSION_ID="SET_SESSION_ID",e.SET_P2P_ID="SET_P2P_id",e.SET_DC_ID="SET_DC_id",e.SET_UID="SET_UID",e.SET_PUB_ID="SET_PUB_ID",e.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",e.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",e.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",e.AVOID_JOIN_START="AVOID_JOIN_START",e.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",e.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",e.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",e.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",e.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",e.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",e.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",e.KEY_METRIC_DESCRIPTION_START="KEY_METRIC_DESCRIPTION_START",e.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",e.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",e.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",e.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",e.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",e.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",e.RESET_KEY_METRICS="RESET_KEY_METRICS",e.SET_USE_DATACHANNEL="SET_USE_DATACHANNEL",e.SET_USE_P2P="SET_USE_P2P"}(bC||(bC={}));class wC{constructor(e,t,i,n){nu(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:i,clientId:n,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,avoidJoinStart:0,keyMetrics:{publish:[],subscribe:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useDataChannel:!1,useP2P:!1}}dispatch(e){this.state=function(e,t){switch(t.type){case bC.SET_SESSION_ID:return AC(AC({},e),{},{sessionId:t.sessionId});case bC.SET_P2P_ID:return AC(AC({},e),{},{p2pId:t.p2pId});case bC.SET_UID:return AC(AC({},e),{},{uid:t.uid});case bC.SET_PUB_ID:return AC(AC({},e),{},{pubId:t.pubId});case bC.KEY_METRIC_CLIENT_CREATED:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{clientCreated:t.metric})});case bC.KEY_METRIC_JOIN_START:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{joinStart:t.metric})});case bC.AVOID_JOIN_START:return AC(AC({},e),{},{avoidJoinStart:t.avoidJoinStart});case bC.KEY_METRIC_JOIN_END:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{joinEnd:t.metric})});case bC.KEY_METRIC_REQUEST_AP_START:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{requestAPStart:t.metric})});case bC.KEY_METRIC_REQUEST_AP_END:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{requestAPEnd:t.metric})});case bC.KEY_METRIC_JOIN_GATEWAY_START:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case bC.KEY_METRIC_JOIN_GATEWAY_END:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case bC.KEY_METRIC_PEER_CONNECTION_START:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case bC.KEY_METRIC_PEER_CONNECTION_END:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case bC.KEY_METRIC_DESCRIPTION_START:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{descriptionStart:t.metric})});case bC.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case bC.KEY_METRIC_ICE_CONNECTION_END:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case bC.KEY_METRIC_PUBLISH:{const i=e.keyMetrics.publish,n=i.findIndex((e=>e.trackId===t.metric.trackId));return-1!==n?(i[n]=AC(AC({},i[n]),t.metric),AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{publish:[...i]})})):AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case bC.KEY_METRIC_SUBSCRIBE:{const i=e.keyMetrics.subscribe,n=i.findIndex((e=>e.userId===t.metric.userId&&e.type===t.metric.type));return-1!==n?(i[n]=AC(AC({},i[n]),t.metric),AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{subscribe:[...i]})})):AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case bC.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case bC.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=AC(AC({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case bC.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case bC.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[]},e;case bC.SET_USE_DATACHANNEL:return AC(AC({},e),{},{useDataChannel:t.val});case bC.SET_USE_P2P:return AC(AC({},e),{},{useP2P:t.val});default:return e}}(this.state,e)}set sessionId(e){this.dispatch({type:bC.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}get codec(){return this.state.codec}get audioCodec(){return this.state.audioCodec}get clientId(){return this.state.clientId}set p2pId(e){this.dispatch({type:bC.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:bC.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:bC.SET_UID,uid:e})}get uid(){return this.state.uid}set pubId(e){this.dispatch({type:bC.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:bC.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useDataChannel(e){this.dispatch({type:bC.SET_USE_DATACHANNEL,val:e})}get useDataChannel(){return this.state.useDataChannel}set useP2P(e){this.dispatch({type:bC.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}clientCreated(){this.dispatch({type:bC.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:bC.KEY_METRIC_JOIN_START,metric:Date.now()})}joinEnd(){this.dispatch({type:bC.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:bC.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:bC.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:bC.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:bC.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:bC.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:bC.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}descriptionStart(){this.dispatch({type:bC.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:bC.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:bC.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,n){this.dispatch({type:bC.KEY_METRIC_PUBLISH,metric:AC(AC({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})})}subscribe(e,t,i,n,r,s,o){this.dispatch({type:bC.KEY_METRIC_SUBSCRIBE,metric:AC(AC(AC(AC(AC({userId:e,type:t},i&&{subscribeStart:i}),n&&{subscribeEnd:n}),r&&{firstFrame:r}),s&&{streamAdded:s}),o&&{firstDecoded:o})})}massSubscribe(e,t,i,n){e.forEach((e=>{this.dispatch({type:bC.KEY_METRIC_SUBSCRIBE,metric:AC(AC(AC({userId:e.userId,type:e.type},t&&{subscribeStart:t}),i&&{subscribeEnd:i}),n&&{firstFrame:n})})}))}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(e,t){"gateway"===e.service&&Array.isArray(e.urls)&&(e.urls=e.urls.map((e=>e.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2"))));try{return"number"!=typeof t?(this.dispatch({type:bC.RECORD_JOIN_CHANNEL_SERVICE,record:AC(AC({},e),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(t<0||t>=this.state.joinChannelServiceRecords.length||this.dispatch({type:bC.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:bC.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:bC.RESET_KEY_METRICS})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}get avoidJoinStart(){return this.state.avoidJoinStart}set avoidJoinStart(e){this.dispatch({type:bC.AVOID_JOIN_START,avoidJoinStart:e})}}const OC=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-alpha\.([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],i=t[2];return"".concat(e,".").concat(i)}const i=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-special\.([0-9]+)/);if(i&&i[1]&&i[2]){const e=i[1],t=i[2];return"".concat(e,".").concat(100*(Number(t)+1))}return"4.0.0.999"}("4.19.1"),NC=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}(),DC="v4.19.1-0-g605286cc(10/11/2023, 2:37:03 PM)",PC={PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",ENABLE_EVENT_REPORT:!0,GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],SUBSCRIBE_TWCC:!1,PUBLISH_TWCC:!1,PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],WORKER_DOMAIN:"edge.agora.io",TURN_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,PRELOAD_MEDIA_COUNT:0,USE_PUB_RTX:!1,USE_SUB_RTX:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:"",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:["agora.io","sd-rtn.com"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!0,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,ENABLE_PUBLISHED_USER_LIST:!0,MAX_SUBSCRIPTION:50,X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:["data-reporting.agora.io","data-reporting.agora.io"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,VIDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,DISABLE_FEC:void 0,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,DISABLE_DUAL_STREAM_USE_ENCODING:!1,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,NEW_ICE_RESTART:!1,ENABLE_USER_LICENSE_CHECK:!0,SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,FINGERPRINT:null,DC_JOIN_WITH_FAILBACK:5e3,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,AP_AREA:!0,SVC:[],ENABLE_ENCODED_TRANSFORM:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,RTM2_FLAG:void 0,AP_RTM:!1,ENABLE_DATASTREAM_2:!1,DATASTREAM_MAX_RETRANSMITS:10,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_INSTANT_VIDEO:!1,ENABLE_NTP_REPORT:!1,USE_XR:!1,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:1e4,P2P:!1,SHOW_P2P_LOG:!1,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0}};function LC(e,t,i){var n,r;Lr(n=Object.keys(PC)).call(n,e)&&(!i&&Lr(r=Object.keys(MC)).call(r,e)||(PC[e]=t))}function kC(e){return PC[e]}const MC={},UC=new class extends iS{reportLogUploadError(e){this.emit("REPORT_LOG_UPLOAD",e)}};class xC{constructor(e){nu(this,"logger",void 0),nu(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.debug(...this.prefixLists,...t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.info(...this.prefixLists,...t)}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.warning(...this.prefixLists,...t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.error(...this.prefixLists,...t)}prefix(e){return this.prefixLists.push(e),this}popPrefix(){return this.prefixLists.pop(),this}}function VC(){const e=new Date;return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function FC(){const e=new Date,t=/((\d+:){2}\d+)/.exec((new Date).toUTCString());return t?(null==t?void 0:t[0])+":"+e.getUTCMilliseconds():e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}const BC={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},jC=Date.now(),GC=e=>{for(const t in BC)if(Object.prototype.hasOwnProperty.call(BC,t)&&BC[t]===e)return t;return"DEFAULT"},WC=new class{constructor(){nu(this,"proxyServerURL",void 0),nu(this,"logLevel",BC.DEBUG),nu(this,"uploadState","collecting"),nu(this,"uploadLogWaitingList",[]),nu(this,"uploadLogUploadingList",[]),nu(this,"uploadErrorCount",0),nu(this,"currentLogID",0),nu(this,"url",void 0),nu(this,"extLog",((e,t)=>{this.appendLogToWaitingList(e,...t)}))}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[BC.DEBUG].concat(t);this.log.apply(this,n)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[BC.INFO].concat(t);this.log.apply(this,n)}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[BC.WARNING].concat(t);this.log.apply(this,n)}warn(){this.warning(...arguments)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[BC.ERROR].concat(t);this.log.apply(this,n)}upload(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[BC.DEBUG].concat(t);this.uploadLog.apply(this,n)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){LC("UPLOAD_LOG",!0)}disableLogUpload(){LC("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new xC(this).prefix(e)}log(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-jC<100)return void setTimeout((()=>{this.log(...t)}),Date.now()-jC);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=VC()+" Agora-SDK [".concat(GC(n),"]:"),this.appendLogToWaitingList(n,...t),n<this.logLevel)return;const r=VC()+" %cAgora-SDK [".concat(GC(n),"]:");let s=[];if(!kC("USE_NEW_LOG"))switch(n){case BC.DEBUG:s=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,s);break;case BC.INFO:s=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,s);break;case BC.WARNING:s=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,s);break;case BC.ERROR:s=[r,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,s)}}uploadLog(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-jC<100)return void setTimeout((()=>{this.uploadLog(...t)}),Date.now()-jC);const n=Math.max(0,Math.min(4,t[0]));t[0]=VC()+" Agora-SDK [".concat(GC(n),"]:"),this.appendLogToWaitingList(n,...t)}appendLogToWaitingList(e){if(!kC("UPLOAD_LOG"))return;for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];Array.isArray(i[0])?i[0][0]=FC()+" Agora-SDK [".concat(GC(e),"]:"):i[0]=FC()+" Agora-SDK [".concat(GC(e),"]:");let r="";i.forEach((e=>{"object"==typeof e&&(e=JSON.stringify(e)),r+="".concat(e," ")})),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}startUpload(){this.uploadState="uploading",0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:OC,process_id:kC("PROCESS_ID"),payload:JSON.stringify(e)};return XS((async()=>{const e=await EC.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(kC("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(kC("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if("OK"!==e.data){const t=new Error("unexpected upload log response");throw t.response=e,t}}),(()=>(this.uploadLogUploadingList=[],!1)),(e=>(e.response?UC.reportLogUploadError({status:e.response.status,data:e.response.data,headers:e.response.headers,message:e.message}):e.request?UC.reportLogUploadError({status:e.request.status,message:e.message}):UC.reportLogUploadError({status:-1,message:e.message}),!0)),{timeout:kC("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:kC("UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL")})}uploadLogInterval(){0===this.uploadLogUploadingList.length&&0===this.uploadLogWaitingList.length||(0===this.uploadLogUploadingList.length&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,kC("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then((()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout((()=>this.uploadLogInterval()),kC("UPLOAD_LOG_INTERVAL"))})).catch((e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout((()=>this.uploadLogInterval()),kC("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout((()=>this.uploadLogInterval()),kC("UPLOAD_LOG_RETRY_INTERVAL_V1"))})))}};var HC,KC;function YC(e){return Wg(e.reportId,"params.reportId",0,100,!1),Wg(e.category,"params.category",0,100,!1),Wg(e.event,"params.event",0,100,!1),Wg(e.label,"params.label",0,100,!1),jg(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}!function(e){e.FREE="free",e.UPLOADING="uploading"}(HC||(HC={})),function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="PUBLIC_API"}(KC||(KC={}));const qC={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};var JC,zC,XC,QC;function ZC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function $C(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ZC(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ZC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe",e.WS_COMPRESSOR_INIT="ws_compressor_init",e.SESSION_INIT="session_init",e.JOIN_CHOOSE_SERVER="join_choose_server",e.REQ_USER_ACCOUNT="req_user_account",e.JOIN_GATEWAY="join_gateway",e.REJOIN_GATEWAY="rejoin_gateway",e.STREAM_SWITCH="stream_switch",e.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",e.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",e.FIRST_VIDEO_RECEIVED="first_video_received",e.FIRST_AUDIO_RECEIVED="first_audio_received",e.FIRST_VIDEO_DECODE="first_video_decode",e.FIRST_AUDIO_DECODE="first_audio_decode",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_UPDATE_STREAM="on_update_stream",e.ON_REMOVE_STREAM="on_remove_stream",e.USER_ANALYTICS="req_user_analytics",e.PC_STATS="pc_stats"}(JC||(JC={})),function(e){e.SESSION="io.agora.pb.Wrtc.Session",e.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",e.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",e.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",e.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",e.PUBLISH="io.agora.pb.Wrtc.Publish",e.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",e.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",e.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",e.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",e.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",e.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",e.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",e.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",e.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",e.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",e.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",e.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",e.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",e.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",e.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",e.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",e.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",e.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",e.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",e.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",e.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",e.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",e.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",e.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",e.PC_STATS="io.agora.pb.Wrtc.PCStats"}(zC||(zC={})),function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"}(XC||(XC={})),function(e){e[e.SESSION=26]="SESSION",e[e.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",e[e.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",e[e.JOIN_GATEWAY=28]="JOIN_GATEWAY",e[e.PUBLISH=30]="PUBLISH",e[e.SUBSCRIBE=29]="SUBSCRIBE",e[e.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",e[e.STREAM_SWITCH=32]="STREAM_SWITCH",e[e.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",e[e.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",e[e.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",e[e.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",e[e.API_INVOKE=41]="API_INVOKE",e[e.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",e[e.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",e[e.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",e[e.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",e[e.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",e[e.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",e[e.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",e[e.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",e[e.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",e[e.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",e[e.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",e[e.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",e[e.USER_ANALYTICS=1e4]="USER_ANALYTICS",e[e.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED"}(QC||(QC={}));class ev{constructor(){nu(this,"baseInfoMap",new Map),nu(this,"proxyServer",void 0),nu(this,"eventUploadTimer",void 0),nu(this,"setSessionIdTimer",void 0),nu(this,"url",void 0),nu(this,"backupUrl",void 0),nu(this,"_appId",void 0),nu(this,"keyEventUploadPendingItems",[]),nu(this,"normalEventUploadPendingItems",[]),nu(this,"apiInvokeUploadPendingItems",[]),nu(this,"apiInvokeCount",0),nu(this,"ltsList",[]),nu(this,"lastSendNormalEventTime",Date.now()),nu(this,"customReportCounterTimer",void 0),nu(this,"customReportCount",0),nu(this,"extApiInvoke",(async e=>{for(const t of e){const e=$C($C({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:oS.TRACER});this.sendApiInvoke(e)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),kC("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),kC("EVENT_REPORT_SEND_INTERVAL"))}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e)}adjustSessionStartTime(e){if(!this.baseInfoMap.has(e)&&!this.baseInfoMap.get(e))return void WC.error("adjust session ".concat(e," start time, sid is not exist or info is undefined"));const t=this.baseInfoMap.get(e),i=Date.now(),n=t.startTime;t.startTime=i,WC.debug("rewrite session ".concat(e," startTime: ").concat(i," , ").concat(i-n,"ms")),this.baseInfoMap.set(e,t)}setAppId(e){this._appId=e}reportApiInvoke(e,t,i){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const n=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,s=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:n,options:t.options,states:t.states||null}),o=!!kC("SHOW_REPORT_INVOKER_LOG");o&&WC.info("".concat(t.name," start"),t.options);let a=!1;US(t.timeout).then((()=>{a||(this.sendApiInvoke($C($C({},s()),{},{error:xg.API_INVOKE_TIMEOUT,success:!1})),WC.debug("".concat(t.name," timeout")))}));const c=new Vg(xg.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const n=()=>{if(a)throw c;return a=!0,this.sendApiInvoke($C($C({},s()),{},{success:!0},t.reportResult&&{result:e})),o&&WC.info("".concat(t.name," onSuccess")),e};return i?jS(n,t.name+"Success",i,(()=>a=!0)):n()},onError:e=>{const n=()=>{if(a)throw e;a=!0,this.sendApiInvoke($C($C({},s()),{},{success:!1,error:e})),o&&WC.info("".concat(t.name," onFailure"),e.toString())};return i?jS(n,t.name+"Error",i,(()=>a=!0)):n()}}}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const i=Date.now(),n=this.createBaseInfo(e,i);n.cname=t.cname;const r=Object.assign({},{willUploadConsoleLog:kC("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:NC?"global":"oversea",areas:kC("AREAS")&&kC("AREAS").join(",")},t.extend),s=Date.now(),o=$C($C({},n),{},{eventType:JC.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,build:DC,lts:s,elapse:s-i,extend:JSON.stringify(r),mode:t.mode,process:kC("PROCESS_ID"),appType:kC("APP_TYPE"),success:!0,version:OC});this.send({type:zC.SESSION,data:o},!0)}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.JOIN_CHOOSE_SERVER,lts:r,eventElapse:r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-i.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||"",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3});this.send({type:zC.JOIN_CHOOSE_SERVER,data:s},!0)}reqUserAccount(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:r-i.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:zC.REQ_USER_ACCOUNT,data:s},!0)}joinGateway(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info;t.vid&&(n.vid=t.vid),n.uid=t.uid,n.cid=t.cid;const r=Date.now(),{firstSuccess:s,avoidJoinStartTime:o,isProxy:a,addr:c}=t,d=r-(s&&o?o:i.startTime),l=$C($C({},n),{},{eventType:JC.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,elapse:d,eventElapse:r-t.lts,firstSuccess:s,signalChannel:t.signalChannel}),h=l.success?1:0;if(t.succ&&(i.lastJoinSuccessTime=r),s)this.send({type:zC.JOIN_GATEWAY,data:l},!0);else{let e;if(c)if(a){const t=c.match(/h=(\d{1,3}-){3}\d{1,3}/g),i=c.match(/p=[0-9]{1,6}/g);e={isSuccess:h,gatewayIp:t&&t.length?t[0].split("=")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split("=")[1]:"",isProxy:a?1:0}}else{const t=c.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),i=c.match(/(:|p=)[0-9]{1,6}/g);e={isSuccess:h,gatewayIp:t&&t.length?t[0].split("//")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split(/:|p=/g)[1]:"",isProxy:a?1:0}}else e={isSuccess:h,gatewayIp:"",port:"",isProxy:a?1:0};delete l.success,delete l.eventType,delete l.firstSuccess,l.vid=Number(l.vid);const t=Object.assign({},l,e,{eventType:JC.REJOIN_GATEWAY});this.send({type:zC.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=$C($C({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:zC.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-i.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:zC.PUBLISH,data:s},!0)}subscribe(e,t,i){const n=this.baseInfoMap.get(e);if(!n)return;const r=n.info,s=Date.now(),o=$C($C({},r),{},{eventType:JC.SUBSCRIBE,lts:s,eventElapse:t.eventElapse,elapse:s-n.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid},i&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?o.peerSuid=t.peerid:o.peer=t.peerid,this.send({type:zC.SUBSCRIBE,data:o},!0)}wsCompressorInit(e){var t;const i=[...hu(t=this.baseInfoMap).call(t)],n=i.length?i[0]:"UnableToGetSid",r=this.baseInfoMap.get(n);if(!r)return;const s=r.info,o=Date.now(),a=$C($C({},s),{},{eventType:JC.WS_COMPRESSOR_INIT,lts:o,eventElapse:e.eventElapse,elapse:o-r.startTime,status:e.status?1:2});this.send({type:zC.WS_COMPRESSOR_INIT,data:a},!0)}firstRemoteVideoDecode(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=$C($C($C({},s),n),{},{elapse:o-r.startTime,eventType:t,lts:o,firstDecodeFrame:Math.max(o-r.startTime,0),apEnd:Math.max(n.apEnd-r.startTime,0),apStart:Math.max(n.apStart-r.startTime,0),joinGwEnd:Math.max(n.joinGwEnd-r.startTime,0),joinGwStart:Math.max(n.joinGwStart-r.startTime,0),pcEnd:Math.max(n.pcEnd-r.startTime,0),pcStart:Math.max(n.pcStart-r.startTime,0),subscriberEnd:Math.max(n.subscriberEnd-r.startTime,0),subscriberStart:Math.max(n.subscriberStart-r.startTime,0),videoAddNotify:Math.max(n.videoAddNotify-r.startTime,0)});this.send({type:i,data:a},!0)}firstRemoteFrame(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=$C($C($C({},s),n),{},{elapse:o-r.startTime,eventType:t,lts:o});this.send({type:i,data:a},!0)}pcStats(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C($C({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:JC.PC_STATS,lts:r});this.send({type:zC.PC_STATS,data:s},!0)}onGatewayStream(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=$C($C($C({},s),n),{},{eventType:t,lts:o});this.send({type:i,data:a},!0)}streamSwitch(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:zC.STREAM_SWITCH,data:s},!0)}requestProxyAppCenter(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:zC.REQUEST_PROXY_APPCENTER,data:s},!0)}requestProxyWorkerManager(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:zC.REQUEST_PROXY_WORKER_MANAGER,data:s},!0)}setProxyServer(e){this.proxyServer=e,e?WC.debug("reportProxyServerurl: ".concat(e)):WC.debug("disable reportProxyServerurl: ".concat(e))}peerPublishStatus(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:r,elapse:r-i.startTime,joinChannelSuccessElapse:r-(i.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:zC.PEER_PUBLISH_STATUS,data:s},!0)}workerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=function(e,t,i){const n=e[t];if(!n||"string"!=typeof n)return[e];e[t]="";const r=LS(JSON.stringify(e));let s=0;const o=[];let a=0;for(let c=0;c<n.length;c++)a+=n.charCodeAt(c)<=127?1:3,a<=i-r||(o[o.length]=vS(vS({},e),{},{[t]:n.substring(s,c)}),s=c,a=n.charCodeAt(c)<=127?1:3);return s!==n.length-1&&(o[o.length]=vS(vS({},e),{},{[t]:n.substring(s)})),o}($C($C($C({},n),t),{},{elapse:r-i.startTime,lts:r,productType:"WebRTC"}),"payload",1300);s.forEach((e=>this.send({type:zC.WORKER_EVENT,data:e},!0)))}apworkerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C($C({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:zC.AP_WORKER_EVENT,data:s},!0)}joinWebProxyAP(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C($C({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:zC.JOIN_WEB_PROXY_AP,data:s},!0)}WebSocketQuit(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C($C({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:zC.WEBSOCKET_QUIT,data:s},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>kC("CUSTOM_REPORT_LIMIT"))throw new Vg(xg.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval((()=>{this.customReportCount=0}),5e3));const i=Date.now(),n=t.map((t=>({type:zC.USER_ANALYTICS,data:$C($C({sid:e},t),{},{lts:i})})));try{kC("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n)}catch(e){throw WC.error("send custom report message failed",e.toString()),new Vg(xg.CUSTOM_REPORT_SEND_FAILED,e.message)}}sendApiInvoke(e){const t=kC("NOT_REPORT_EVENT");if(e.tag&&Lr(t)&&Lr(t).call(t,e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const i=this.baseInfoMap.get(e.sid);if(!i)return this.apiInvokeUploadPendingItems.push(e),!1;const{cname:n,uid:r,cid:s}=i.info;let o;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof Vg){const{code:t,message:i}=e.error;o=t||i||e.error.toString()}else o=e.error.toString();const a={invokeId:e.invokeId,sid:e.sid,cname:n,cid:s,uid:r,lts:e.lts,success:e.success,elapse:e.lts-i.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?o:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:zC.API_INVOKE,data:a},!1),!0}appendSessionId(){ev.__CLIENT_LIST__.forEach((e=>{if(e._sessionId){const t=this.apiInvokeUploadPendingItems.length;for(let i=0;i<t;i++){const t=this.apiInvokeUploadPendingItems.shift();t&&(t.sid=e._sessionId,this.sendApiInvoke(Object.assign({},t)))}}}))}send(e,t){if(t)return this.keyEventUploadPendingItems.push(e),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(e),this.normalEventUploadPendingItems.length>kC("NORMAL_EVENT_QUEUE_CAPACITY")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1)}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1)}sendItems(e,t){const i=[],n=[];for(;e.length;){const t=e.shift();i.length<20?i.push(t):n.push(t)}e.push(...n);for(const e of[...i]){var r;-1!==this.ltsList.indexOf(e.data.lts)?(e.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(e.data.lts)):(this.ltsList.push(e.data.lts),Zu(r=this.ltsList).call(r,((e,t)=>e-t)))}return t||(this.lastSendNormalEventTime=Date.now()),kC("ENABLE_EVENT_REPORT")?(i.length&&(kC("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{kC("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>kC("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-kC("NORMAL_EVENT_QUEUE_CAPACITY")),WC.warning("report: drop normal events"))))})(i)),e):e}async postDataToStatsCollector2(e){RS.networkState===hS.OFFLINE&&await tg.race([RS.onlineWaiter,US(2*JS.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach((e=>{const i=Zg(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(zC).forEach((i=>{let[n,r]=i;r===e.type&&(t=EventNameToID[n])})),t})(e),s=new DataView(n);s.setUint16(0,i.byteLength,!0),s.setUint8(2,255&r),s.setUint8(3,r>>>8&255),s.setUint8(4,r>>>16&255),t=$g(t,new Uint8Array(n)),t=$g(t,i)})),t},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(kC("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(kC("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(i);for(let r=0;r<2;r+=1){1===r&&(n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(kC("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(kC("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await RC(n,{timeout:1e4,data:t(e),headers:$C($C({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0)}catch(e){if(1===r)throw e;continue}return}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map((e=>JSON.stringify(e))),vid:(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0])};RS.networkState===hS.OFFLINE&&await tg.race([RS.onlineWaiter,US(2*JS.maxRetryTimeout)]);const n=t?"/events/proto-raws":"/events/messages";let r=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(kC("EVENT_REPORT_DOMAIN"),"&p=").concat(kC("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(kC("EVENT_REPORT_DOMAIN"),":").concat(kC("STATS_COLLECTOR_PORT")).concat(n));for(let e=0;e<2;e+=1){1===e&&(r=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(kC("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(kC("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(kC("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(kC("STATS_COLLECTOR_PORT")).concat(n)));try{t?await CC(r,{timeout:1e4,data:i}):await RC(r,{timeout:1e4,data:i})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const i=Object.assign({},qC);return i.sid=e,this.baseInfoMap.set(e,{info:i,startTime:t}),i}reportResourceTiming(e,t){const i=performance.getEntriesByName(e),n=i[i.length-1];n&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:n,tag:oS.TRACER}).onSuccess()}}function tv(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,i,n){const r=n.value;if("function"==typeof r){const s=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);n.value=function(){for(var t=arguments.length,n=new Array(t),o=0;o<t;o++)n[o]=arguments[o];let a=n;if(e.argsMap)try{a=e.argsMap(this,...n)}catch(e){WC.warning(e),a=[]}try{JSON.stringify(a)}catch(e){WC.warning("arguments for method ".concat(s,".").concat(String(i)," not serializable for apiInvoke.")),a=[]}const c=(e.report||iv).reportApiInvoke(this._sessionId||null,{name:"".concat(s,".").concat(String(i)),options:a,tag:oS.TRACER,reportResult:e.reportResult},e.throttleTime);try{const t=r.apply(this,n);return t instanceof tg?t.then((t=>(c.onSuccess(e.reportResult&&t),t))).catch((e=>{throw c.onError(e),e})):(c.onSuccess(e.reportResult&&t),t)}catch(e){throw c.onError(e),e}}}return n}}nu(ev,"__CLIENT_LIST__",[]);const iv=new ev;UC.on("REPORT_LOG_UPLOAD",(e=>{e.networkState=RS.networkState,iv.reportApiInvoke(null,{name:"logUploadError",options:e,tag:oS.TRACER})}));const nv=["CHINA","GLOBAL"],rv=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),i=["t","s","t"];i.splice(1,0,"e");const n=i.join(""),r=[];for(let e=0;e<6;e++)r.push("1");const s=r.join(""),o={};return o[e]=n,o[t]=s,Object.assign(o,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=rv,NC||(PC.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],PC.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],PC.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],PC.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],PC.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],PC.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],PC.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",PC.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",PC.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",PC.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",PC.AREAS=["NORTH_AMERICA","OVERSEA"]);const sv=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],ov=[];function av(e,t){return!!t&&ov.some((i=>i.uid===e&&i.channelName===t))}ev.__CLIENT_LIST__=ov;var cv,dv,lv,hv,uv,pv,_v,Ev,mv,fv,gv,Sv,Tv,Rv,Cv,vv,Iv,yv=tr("Array").values,Av=mr,bv=ri,wv=me,Ov=yv,Nv=Array.prototype,Dv={DOMTokenList:!0,NodeList:!0},Pv=z((function(e){var t=e.values;return e===Nv||wv(Nv,e)&&t===Nv.values||bv(Dv,Av(e))?Ov:t}));function Lv(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o}function kv(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}!function(e){e.L1T1="L1T1",e.L1T2="L1T2",e.L1T3="L1T3",e.L2T1_KEY="L2T1_KEY",e.L2T2_KEY="L2T2_KEY",e.L2T3_KEY="L2T3_KEY",e.L3T1_KEY="L3T1_KEY",e.L3T2_KEY="L3T2_KEY",e.L3T3_KEY="L3T3_KEY"}(cv||(cv={})),function(e){e.CERTIFICATE="certificate",e.CODEC="codec",e.CANDIDATE_PAIR="candidate-pair",e.LOCAL_CANDIDATE="local-candidate",e.REMOTE_CANDIDATE="remote-candidate",e.INBOUND="inbound-rtp",e.TRACK="track",e.OUTBOUND="outbound-rtp",e.PC="peer-connection",e.REMOTE_INBOUND="remote-inbound-rtp",e.REMOTE_OUTBOUND="remote-outbound-rtp",e.TRANSPORT="transport",e.CSRC="csrc",e.DATA_CHANNEL="data-channel",e.STREAM="stream",e.SENDER="sender",e.RECEIVER="receiver"}(dv||(dv={})),function(e){e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR"}(lv||(lv={})),function(e){e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR"}(hv||(hv={})),function(e){e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND"}(uv||(uv={})),function(e){e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV"}(pv||(pv={})),function(e){e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY"}(_v||(_v={})),function(e){e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed"}(Ev||(Ev={})),function(e){e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_WAITTING_FINISH="ws_reconnect_waitting_finish",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_REJOIN_INFO="req_rejoin_info",e.IS_P2P_DISCONNECTED="is_p2p_dis",e.DISCONNECT_P2P="dis_p2p",e.ABORT_P2P_EXECUTION="abort_p2p_execution",e.NEED_RENEW_SESSION="need-sid",e.REPORT_JOIN_GATEWAY="report_join_gateway",e.REQUEST_TIMEOUT="request_timeout",e.REQUEST_SUCCESS="request_success",e.JOIN_RESPONSE="join_response",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_CONNECTING="datachannel_connecting",e.DATACHANNEL_FAILBACK="datachannel_failback",e.P2P_START="p2p_start",e.P2P_CONNECTION="p2p_connection",e.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",e.P2P_SUBSCRIBE="p2p_subscribe",e.P2P_UNSUBSCRIBE="p2p_unsubscribe",e.P2P_EXCHANGE_SDP="p2p_exchange_sdp",e.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",e.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream"}(mv||(mv={})),function(e){e.PING="ping",e.PING_BACK="ping_back",e.JOIN="join_v3",e.REJOIN="rejoin_v3",e.LEAVE="leave",e.SET_CLIENT_ROLE="set_client_role",e.PUBLISH="publish",e.PUBLISH_DATASTREAM="publish_datastream",e.UNPUBLISH="unpublish",e.UNPUBLISH_DATASTREAM="unpublish_datastream",e.SUBSCRIBE="subscribe",e.SUBSCRIBE_DATASTREAM="subscribe_datastream",e.SUBSCRIBE_STREAMS="subscribe_streams",e.UNSUBSCRIBE="unsubscribe",e.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",e.UNSUBSCRIBE_STREAMS="unsubscribe_streams",e.SUBSCRIBE_CHANGE="subscribe_change",e.TRAFFIC_STATS="traffic_stats",e.RENEW_TOKEN="renew_token",e.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",e.GATEWAY_INFO="gateway_info",e.CONTROL="control",e.SEND_METADATA="send_metadata",e.DATA_STREAM="data_stream",e.PICK_SVC_LAYER="pick_svc_layer",e.RESTART_ICE="restart_ice",e.CONNECT_PC="connect_pc",e.SET_VIDEO_PROFILE="set_video_profile",e.SET_PARAMETER="set_parameter",e.SET_RTM2_FLAG="set_rtm2_flag"}(fv||(fv={})),function(e){e.PUBLISH_STATS="publish_stats",e.PUBLISH_RELATED_STATS="publish_related_stats",e.SUBSCRIBE_STATS="subscribe_stats",e.SUBSCRIBE_RELATED_STATS="subscribe_related_stats",e.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",e.DENOISER_STATS="denoiser_stats",e.TRANSPORT_STATS="transport_stats",e.EXTENSION_USAGE_STATS="extension_usage_stats"}(gv||(gv={})),function(e){e.ON_USER_ONLINE="on_user_online",e.ON_USER_OFFLINE="on_user_offline",e.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",e.ON_PUBLISH_STREAM="on_publish_stream",e.ON_UPLINK_STATS="on_uplink_stats",e.ON_P2P_LOST="on_p2p_lost",e.ON_REMOVE_STREAM="on_remove_stream",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",e.ON_USER_BANNED="on_user_banned",e.ON_USER_LICENSE_BANNED="on_user_license_banned",e.ON_NOTIFICATION="on_notification",e.ON_CRYPT_ERROR="on_crypt_error",e.MUTE_AUDIO="mute_audio",e.MUTE_VIDEO="mute_video",e.UNMUTE_AUDIO="unmute_audio",e.UNMUTE_VIDEO="unmute_video",e.ON_P2P_OK="on_p2p_ok",e.RECEIVE_METADATA="receive_metadata",e.ON_DATA_STREAM="on_data_stream",e.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",e.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",e.ENABLE_LOCAL_VIDEO="enable_local_video",e.DISABLE_LOCAL_VIDEO="disable_local_video",e.ENABLE_LOCAL_AUDIO="enable_local_audio",e.DISABLE_LOCAL_AUDIO="disable_local_audio",e.ON_PUBLISHED_USER_LIST="on_published_user_list"}(Sv||(Sv={})),function(e){e.CONNECTION_STATE_CHANGE="CONNECTION_STATE_CHANGE",e.NEED_ANSWER="NEED_ANSWER",e.NEED_RENEGOTIATE="NEED_RENEGOTIATE",e.P2P_LOST="P2P_LOST",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NEED_UNPUB="NEED_UNPUB",e.NEED_UNSUB="NEED_UNSUB",e.NEED_UPLOAD="NEED_UPLOAD",e.NEED_CONTROL="NEED_CONTROL",e.START_RECONNECT="START_RECONNECT",e.END_RECONNECT="END_RECONNECT",e.NEED_SIGNAL_RTT="NEED_SIGNAL_RTT"}(Tv||(Tv={})),function(e){e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY"}(Rv||(Rv={})),function(e){e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_WAITTING_FINISH="websocket:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire"}(Cv||(Cv={}));class Mv extends Vg{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),nu(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,WC)}throw(){super.throw(WC)}}function Uv(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw WC.error("Invalid Channel Name ".concat(e)),new Mv(xg.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function xv(e){if(!("number"==typeof(t=e)&&Math.floor(t)===t&&0<=t&&t<=4294967295||Yg(e,1,255)))throw new Mv(xg.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;"string"==typeof e&&WC.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}!function(e){e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e.INJECT="inject_streaming"}(vv||(vv={})),function(e){e[e.INJECT_STREAM_STATUS_START_SUCCESS=0]="INJECT_STREAM_STATUS_START_SUCCESS",e[e.INJECT_STREAM_STATUS_START_ALREADY_EXISTS=1]="INJECT_STREAM_STATUS_START_ALREADY_EXISTS",e[e.INJECT_STREAM_STATUS_START_UNAUTHORIZED=2]="INJECT_STREAM_STATUS_START_UNAUTHORIZED",e[e.INJECT_STREAM_STATUS_START_TIMEOUT=3]="INJECT_STREAM_STATUS_START_TIMEOUT",e[e.INJECT_STREAM_STATUS_START_FAILED=4]="INJECT_STREAM_STATUS_START_FAILED",e[e.INJECT_STREAM_STATUS_STOP_SUCCESS=5]="INJECT_STREAM_STATUS_STOP_SUCCESS",e[e.INJECT_STREAM_STATUS_STOP_NOT_FOUND=6]="INJECT_STREAM_STATUS_STOP_NOT_FOUND",e[e.INJECT_STREAM_STATUS_STOP_UNAUTHORIZED=7]="INJECT_STREAM_STATUS_STOP_UNAUTHORIZED",e[e.INJECT_STREAM_STATUS_STOP_TIMEOUT=8]="INJECT_STREAM_STATUS_STOP_TIMEOUT",e[e.INJECT_STREAM_STATUS_STOP_FAILED=9]="INJECT_STREAM_STATUS_STOP_FAILED",e[e.INJECT_STREAM_STATUS_BROKEN=10]="INJECT_STREAM_STATUS_BROKEN"}(Iv||(Iv={}));const Vv={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},Fv={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function Bv(e,t){Wg(e.url,"".concat(t,".url"),1,1e3,!1),Kg(e.x)||jg(e.x,"".concat(t,".x"),0,1e4),Kg(e.y)||jg(e.y,"".concat(t,".y"),0,1e4),Kg(e.width)||jg(e.width,"".concat(t,".width"),0,1e4),Kg(e.height)||jg(e.height,"".concat(t,".height"),0,1e4),Kg(e.zOrder)||jg(e.zOrder,"".concat(t,".zOrder"),0,255),Kg(e.alpha)||jg(e.alpha,"".concat(t,".alpha"),0,1,!1)}const jv={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""},Gv={audioBitrate:48,audioChannels:2,audioVolume:100,audioSampleRate:48e3,height:0,width:0,videoBitrate:400,videoFramerate:15,videoGop:30};var Wv,Hv,Kv,Yv,qv,Jv,zv,Xv,Qv,Zv,$v,eI,tI,iI;function nI(e){if(!e.channelName)throw new Mv(xg.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new Mv(xg.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&Wg(e.token,"info.token",1,2047),xv(e.uid),Uv(e.channelName),!0}!function(e){e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.INJECT_STREAM_STATUS="@live_uap-inject-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address"}(Wv||(Wv={})),function(e){e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager"}(Hv||(Hv={})),function(e){e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN"}(Kv||(Kv={})),function(e){e.CONNECT_FAILED="connect failed",e.CONNECT_TIMEOUT="connect timeout",e.WS_DISCONNECTED="websocket disconnected",e.REQUEST_TIMEOUT="request timeout",e.REQUEST_FAILED="request failed",e.WAIT_STATUS_TIMEOUT="wait status timeout",e.WAIT_STATUS_ERROR="wait status error",e.BAD_STATE="bad state",e.WS_ABORT="ws abort",e.AP_REQUEST_TIMEOUT="AP request timeout",e.AP_JSON_PARSE_ERROR="AP json parse error",e.AP_REQUEST_ERROR="AP request error",e.AP_REQUEST_ABORT="AP request abort"}(Yv||(Yv={})),function(e){e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile"}(qv||(qv={})),function(e){e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE"}(Jv||(Jv={})),function(e){e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE"}(zv||(zv={})),function(e){e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED"}(Xv||(Xv={})),function(e){e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low"}(Qv||(Qv={})),function(e){e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.REQUEST_DC_CONNECTION_PARAMS="request-dc-connection-params",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_FAILBACK="datachannel_failback",e.RESET_SIGNAL="reset-signal"}(Zv||(Zv={})),function(e){e.P2P_DISCONNECTED="P2P_DISCONNECTED",e.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",e.TIMEOUT="TIMEOUT",e.UNKNOWN_REASON="UNKNOWN_REASON"}($v||($v={})),function(e){e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LwoVideo=2]="LwoVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7"}(eI||(eI={})),function(e){e[e.websocket=0]="websocket",e[e.datachannel=1]="datachannel"}(tI||(tI={})),function(e){e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS"}(iI||(iI={}));const rI=[iI.AFRICA,iI.ASIA,iI.CHINA,iI.EUROPE,iI.GLOBAL,iI.INDIA,iI.JAPAN,iI.NORTH_AMERICA,iI.OCEANIA,iI.OVERSEA,iI.SOUTH_AMERICA];var sI;!function(e){e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL"}(sI||(sI={}));const oI={CHINA:{},ASIA:{CODE:sI.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:sI.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:sI.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:sI.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","\tuap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:sI.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:sI.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:sI.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:sI.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:sI.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:sI.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:sI.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:sI.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:sI.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};var aI,cI,dI,lI,hI,uI,pI,_I,EI,mI,fI,gI,SI,TI,RI,CI,vI,II,yI,AI,bI,wI;NC&&(oI.CHINA={CODE:sI.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]}),function(e){e.UPDATE_BITRATE_LIMIT="update_bitrate_limit"}(aI||(aI={}));class OI extends iS{constructor(e,t){super(),nu(this,"onICEConnectionStateChange",void 0),nu(this,"onConnectionStateChange",void 0),nu(this,"onDTLSTransportStateChange",void 0),nu(this,"onDTLSTransportError",void 0),nu(this,"onICETransportStateChange",void 0),nu(this,"onFirstAudioReceived",void 0),nu(this,"onFirstVideoReceived",void 0),nu(this,"onFirstAudioDecoded",void 0),nu(this,"onFirstVideoDecoded",void 0),nu(this,"onFirstVideoDecodedTimeout",void 0),nu(this,"onSelectedLocalCandidateChanged",void 0),nu(this,"onSelectedRemoteCandidateChanged",void 0)}}class NI extends OI{constructor(e,t){super(e,t)}}!function(e){e.SEND="sendonly",e.RECV="recvonly",e.SENDRECV="sendrecv",e.INACTIVE="inactive"}(cI||(cI={})),function(e){e.VIDEO="video",e.AUDIO="audio"}(dI||(dI={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.RELAY=2]="RELAY"}(lI||(lI={})),function(e){e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.TCP_RESTART=1]="TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",e[e.OLD_RESTART=11]="OLD_RESTART",e[e.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED"}(hI||(hI={})),function(e){e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack"}(uI||(uI={})),function(e){e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected"}(pI||(pI={})),function(e){e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestRePublishDataChannel="requestRePublishDataChannel",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState",e.LocalCandidate="LocalCandidate",e.RequestP2PMuteLocal="requestP2PMuteLocal",e.RequestP2PPublish="RequestP2PPublish",e.RequestP2PUnPublish="RequestP2PUnPublish",e.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",e.RequestP2PMuteRemote="RequestP2PMuteRemote",e.RequestP2PRestartICE="RequestP2PRestartICE"}(_I||(_I={})),function(e){e.MUTE_LOCAL_VIDEO="mute_local_video",e.MUTE_LOCAL_AUDIO="mute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.MUTE_REMOTE_VIDEO="mute_remote_video",e.MUTE_REMOTE_AUDIO="mute_remote_audio",e.UNMUTE_REMOTE_VIDEO="unmute_remote_video",e.UNMUTE_REMOTE_AUDIO="unmute_remote_audio"}(EI||(EI={})),function(e){e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED"}(mI||(mI={})),function(e){e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED"}(fI||(fI={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url"}(gI||(gI={})),function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK"}(SI||(SI={})),function(e){e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_WAITTING_FINISH="transmitter:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback"}(TI||(TI={})),function(e){e.CAMERA_CHANGED="camera-changed",e.MICROPHONE_CHANGED="microphone-changed",e.PLAYBACK_DEVICE_CHANGED="playback-device-changed",e.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",e.AUTOPLAY_FAILED="autoplay-failed",e.SECURITY_POLICY_VIOLATION="security-policy-violation"}(RI||(RI={})),function(e){e[e.APP_TYPE_INVALID_VALUE=-1]="APP_TYPE_INVALID_VALUE",e[e.APP_TYPE_NATIVE=0]="APP_TYPE_NATIVE",e[e.APP_TYPE_NATIVE_COCOS=1]="APP_TYPE_NATIVE_COCOS",e[e.APP_TYPE_NATIVE_UNITY=2]="APP_TYPE_NATIVE_UNITY",e[e.APP_TYPE_NATIVE_ELECTRON=3]="APP_TYPE_NATIVE_ELECTRON",e[e.APP_TYPE_NATIVE_FLUTTER=4]="APP_TYPE_NATIVE_FLUTTER",e[e.APP_TYPE_NATIVE_UNREAL=5]="APP_TYPE_NATIVE_UNREAL",e[e.APP_TYPE_NATIVE_XAMARIN=6]="APP_TYPE_NATIVE_XAMARIN",e[e.APP_TYPE_NATIVE_API_CLOUD=7]="APP_TYPE_NATIVE_API_CLOUD",e[e.APP_TYPE_NATIVE_REACT_NATIVE=8]="APP_TYPE_NATIVE_REACT_NATIVE",e[e.APP_TYPE_NATIVE_PYTHON=9]="APP_TYPE_NATIVE_PYTHON",e[e.APP_TYPE_NATIVE_COCOS_CREATOR=10]="APP_TYPE_NATIVE_COCOS_CREATOR",e[e.APP_TYPE_NATIVE_RUST=11]="APP_TYPE_NATIVE_RUST",e[e.APP_TYPE_NATIVE_C_SHARP=12]="APP_TYPE_NATIVE_C_SHARP",e[e.APP_TYPE_NATIVE_CEF=13]="APP_TYPE_NATIVE_CEF",e[e.APP_TYPE_NATIVE_UNI_APP=14]="APP_TYPE_NATIVE_UNI_APP",e[e.APP_TYPE_WEBRTC=1e3]="APP_TYPE_WEBRTC",e[e.APP_TYPE_WEBRTC_REACT=1001]="APP_TYPE_WEBRTC_REACT",e[e.APP_TYPE_WEBRTC_VUE=1002]="APP_TYPE_WEBRTC_VUE",e[e.APP_TYPE_WEBRTC_ANGULAR=1003]="APP_TYPE_WEBRTC_ANGULAR"}(CI||(CI={})),function(e){e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED"}(vI||(vI={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url"}(II||(II={})),function(e){e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED"}(yI||(yI={})),function(e){e.CALL="call",e.CANDIDATE="candidate",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.SUBSCRIBE="subscribe",e.UNSUBSCRIBE="unsubscribe",e.CONTROL="control",e.RESTART_ICE="restart_ice",e.ACK="ack",e.JOIN="join",e.EXCHANGE_SDP="exchange_sdp",e.DO_SUBSCRIBE="do_subscribe",e.DO_UNSUBSCRIBE="do_unsubscribe"}(AI||(AI={})),function(e){e.MUTE_LOCAL_AUDIO="mute_local_audio",e.MUTE_LOCAL_VIDEO="mute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video"}(bI||(bI={})),function(e){e[e.SUCCESS=1]="SUCCESS",e[e.FAILED=0]="FAILED"}(wI||(wI={}));const DI={[lv.ACCESS_POINT]:{[pv.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[pv.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[pv.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[pv.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[pv.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[pv.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[lv.UNILBS]:{[uv.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[uv.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[uv.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[uv.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[uv.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[uv.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[uv.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[uv.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[uv.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[uv.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[uv.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[uv.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[lv.STRING_UID_ALLOCATOR]:{[hv.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[hv.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[hv.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function PI(e){const t=DI[Math.floor(e/1e4)];if(!t)return{desc:"unkonw error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===lv.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unkonw error",retry:!1}}return i}const LI={[_v.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[_v.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[_v.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[_v.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[_v.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[_v.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[_v.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[_v.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[_v.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[_v.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[_v.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[_v.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[_v.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[_v.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[_v.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[_v.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[_v.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[_v.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[_v.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[_v.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[_v.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[_v.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[_v.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[_v.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[_v.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[_v.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[_v.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[_v.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[_v.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[_v.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[_v.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[_v.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[_v.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[_v.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[_v.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[_v.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[_v.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[_v.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[_v.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[_v.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[_v.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[_v.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[_v.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[_v.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[_v.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[_v.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[_v.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[_v.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[_v.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[_v.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[_v.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[_v.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[_v.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[_v.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[_v.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[_v.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[_v.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[_v.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[_v.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[_v.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[_v.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[_v.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[_v.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function kI(e){return LI[e]||{desc:"UNKNOW_ERROR_".concat(e),action:"failed"}}function MI(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function UI(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?MI(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):MI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function xI(e){return e.every((e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING))}function VI(e,t){if("string"==typeof e)return e;const{proxy:i,host:n,port:r}=e;if(t){const e=kC("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(n,"/ws/?p=").concat(Number(r)+150):"wss://".concat(n,":").concat(e,"/ws/?p=").concat(Number(r)+150)}return i?"wss://".concat(i,"/ws/?h=").concat(n,"&p=").concat(r):"wss://".concat(n,":").concat(r)}const FI=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,BI=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,jI=/wss:\/\/(.+):([0-9]+)\/?/,GI=/wss:\/\/(.[^\/]+)\/?/;let WI=0;class HI{constructor(e,t){nu(this,"id",0),nu(this,"store",void 0),nu(this,"recordIndex",void 0),nu(this,"websockets",[]),nu(this,"try443PortDuration",2e3),nu(this,"forceCloseWSDuration",5e3),nu(this,"try443PortTimeout",null),nu(this,"forceCloseTimeout",null),nu(this,"isTry443PortFailed",!1),nu(this,"isNormalPortFailed",!1),nu(this,"useDoubleDomain",!1),nu(this,"useProxy",!1),nu(this,"startTime",Date.now()),this.id=++WI,this.try443PortDuration=kC("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t}closeAllWebsockets(){this.websockets.forEach((e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close()})),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout)}logger(){var e;const t=Date.now()-this.startTime;for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];WC.debug("[choose-best-ws ".concat(null===(e=this.store)||void 0===e?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...n)}createWebSocket(e,t,i){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:i});const n=kC("GATEWAY_DOMAINS"),r=Date.now(),s=[],o=n.find((t=>{var i;return Lr(i=e.host).call(i,t)}));o||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)n.forEach((i=>{a.push(VI(UI(UI({},e),{},{host:e.host.replace(o,i)}),t))}));else{const i=UI({},e);if(t&&o){const e=n.find((e=>e!==o));e&&(i.host=i.host.replace(o,e))}a.push(VI(i,t))}try{a.forEach((e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",s.push(t),this.logger("ws is connecting:",t.url)}))}catch(n){if(this.logger("ws create failed"),s.forEach((e=>e.close())),s.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,i);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,i);throw new Mv(xg.WS_ERR,"init websocket failed! Error: ".concat(n.toString()))}const c=ng();return this.store&&this.store.recordJoinChannelService({urls:s.map((e=>e.url)),service:"gateway"},this.recordIndex),s.forEach((e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-r,"ms")),this.websockets.forEach((t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)))})),this.websockets.length=0,c.resolve(e)},e.onclose=i=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-r,"ms state: ").concat(e.readyState)),t?this.isTry443PortFailed=xI(s):this.isNormalPortFailed=xI(s),this.logger("443: ".concat(this.useProxy?"not try":this.isTry443PortFailed?"failed":"trying"," 47xx: ").concat(this.isNormalPortFailed?"failed":"trying")),(t&&this.isTry443PortFailed||!t&&(this.isTry443PortFailed||this.useProxy)&&this.isNormalPortFailed)&&(this.logger("onclose: all websocket is closed, ".concat(i.reason)),c.reject({code:i.code,reason:$v.A_ROUND_WS_FAILED}))},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data))})),this.websockets.push(...s),i||(()=>{const i=()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))};if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{if(this.logger("2s timeout, isWebsocket created: ",c.isResolved),c.isResolved)return i();pg().os===ag.MAC_OS&&Rg()&&i(),this.createWebSocket(e,!0,!0).then((e=>c.resolve(e))).catch((e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed")})),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration)}),this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,i,n){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,i,n;return[,t,i,n]=e.match(FI)||[],t||([,i,n]=e.match(BI)||[]),i&&n||([,i,n]=e.match(jI)||[]),i&&n||([,i]=e.match(GI)||[]),i||WC.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(WC.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}function KI(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class YI extends iS{get url(){return this.websocket&&this.websocket.url||null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Lr(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(Cv.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(Cv.CONNECTED):"closed"===this._state?this.emit(Cv.CLOSED):"failed"===this._state&&this.emit(Cv.FAILED))}resetReconnectCount(e){WC.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;super(),nu(this,"connectionID",0),nu(this,"currentURLIndex",0),nu(this,"urls",[]),nu(this,"_reconnectMode","tryNext"),nu(this,"reconnectReason",void 0),nu(this,"_initMutex",new YS("websocket")),nu(this,"name",void 0),nu(this,"_state","closed"),nu(this,"reconnectInterrupter",void 0),nu(this,"websocket",void 0),nu(this,"retryConfig",void 0),nu(this,"reconnectCount",0),nu(this,"forceCloseTimeout",5e3),nu(this,"onlineReconnectListener",void 0),nu(this,"useCompress",void 0),nu(this,"tryDoubleDomain",!1),nu(this,"use443PortOnly",!1),nu(this,"wsInflateLength",0),nu(this,"wsDeflateLength",0),nu(this,"closeEstablishingWs",(()=>{})),nu(this,"store",void 0),nu(this,"joinGatewayRecordIndex",void 0),this.store=s,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?KI(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):KI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t),this.useCompress=i,this.tryDoubleDomain=n,this.use443PortOnly=r;const{timeout:o,timeoutFactor:a}=t,c=Math.max(300,Math.floor(3*o/5)),d=Math.max(1.2,Math.floor(8*a)/10);hS.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),RS.on(uS.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===hS.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=o,this.retryConfig.timeoutFactor=a))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=await this._initMutex.lock();this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=ng(),t=this.urls[this.currentURLIndex];this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(Cv.CLOSED,(()=>{e.reject(new Vg(xg.WS_DISCONNECT))})),this.once(Cv.CONNECTED,e.resolve),await e.promise}catch(e){}finally{i()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void WC.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),WC.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Vg(xg.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new Vg(xg.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var t;const i=ng();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),WC.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},r=async e=>{var t;if(WC.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)i.reject(new Vg(xg.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=SS(this,Cv.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void WC.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return i.reject(new Vg(xg.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve()}},s=e=>{this.emit(Cv.ON_MESSAGE,e)},o=e=>{WC.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),kC("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=kC("GATEWAY_WSS_ADDRESS")),WC.debug("[".concat(this.name,"] start connect, url:"),e);const a=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,n&&n(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=s,this.websocket.onerror=o,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this.joinGatewayRecordIndex=a}catch(e){const t="closed"===this.state,n=e instanceof Vg,s=n&&e.code===xg.WS_ABORT,o=n&&e.code===xg.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());WC.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:s?"aborted":"error",errors:[e]},a),t||o?(i.reject(t?new Vg(xg.WS_DISCONNECT,"websocket is closed: ".concat(c)):new Vg(xg.WS_ERR,"init websocket failed: ".concat(c))),o&&WC.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(e)}return i.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;WC.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||RS.isOnline||!RS.onlineWaiter||(this.onlineReconnectListener=RS.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=zS(this.reconnectCount,this.retryConfig);WC.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await tg.race([US(t),this.onlineReconnectListener||new tg((()=>{}))])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(Cv.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(Cv.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);WC.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(Cv.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(WC.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(Cv.RECONNECT_WAITTING_FINISH,e),this.urls=await fS(this,Cv.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var r;WC.error("[".concat(this.name,"] reconnect failed ").concat(i&&i.toString()));const n=null==i||null===(r=i.data)||void 0===r?void 0:r.desc;return Array.isArray(n)&&Lr(n).call(n,"dynamic key expired")?(this.emit(Cv.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class qI extends YI{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){const i=ng(),n=function(e,t){return new HI(e,t)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{WC.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new Vg(xg.WS_ABORT,"choose best websocket aborted"))};const r=kC("GATEWAY_DOMAINS");return WC.debug("[choose-best-ws] currentDomain: ",e,", domains: ",r,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),n.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(i.resolve).catch(i.reject),i.promise.finally((()=>{this.closeEstablishingWs=void 0}))}}class JI extends YI{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){return new tg(((i,n)=>{let r=!1;const s=[];this.closeEstablishingWs=()=>{WC.debug("[choose-best-ws] close establishing websockets"),s.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),n(new Vg(xg.WS_ABORT,"choose best websocket aborted"))};const o=kC("GATEWAY_DOMAINS");let a;const c=e.indexOf("?h="),d=o.find((t=>-1!==c?Lr(e).call(e,t,c):Lr(e).call(e,t)));WC.debug("[choose-best-ws] currentDomain: ",d,", domains: ",o);let l=!this.tryDoubleDomain||!d;if(!l&&d){var h;const u=Date.now();try{o.forEach((t=>{const i=-1===c?e.replace(d,t):e.substr(0,c)+e.substr(c).replace(d,t),n=new WebSocket(i);n.binaryType="arraybuffer",s.push(n),WC.debug("[choose-best-ws] ws is connecting:",n.url)}))}catch(e){for(WC.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEach((e=>e.close()));s.length;)s.pop();l=!0}null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:s.map((e=>e.url)),service:"gateway"},t),s.forEach((e=>{e.onopen=()=>{if(r)return;const t=Date.now()-u;WC.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),s.filter((t=>t!==e)).forEach((e=>{WC.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),r=!0,i(e)},e.onclose=e=>{a=e,r||s.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(WC.debug("[choose-best-ws] all websocket is closed"),r=!0,n(a))},e.onmessage=t=>{WC.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),US(this.forceCloseTimeout).then((()=>{s.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(l){var u;let r;WC.debug("[choose-best-ws] use single url: ",e),null===(u=this.store)||void 0===u||u.recordJoinChannelService({urls:[e],service:"gateway"},t);try{r=new WebSocket(e),s.push(r),r.binaryType="arraybuffer"}catch(e){const t=new Vg(xg.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return WC.error("[".concat(this.name,"]").concat(t)),void n(t)}r.onopen=()=>{i(r)},r.onclose=e=>{n(e)},r.onmessage=e=>{WC.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data))},US(this.forceCloseTimeout).then((()=>{r&&r.readyState!==WebSocket.OPEN&&r.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class zI extends iS{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Ev.CONNECTED?this.emit(mv.WS_CONNECTED):e===Ev.RECONNECTING?this.emit(mv.WS_RECONNECTING,this._websocketReconnectReason):e===Ev.CLOSED&&this.emit(mv.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),nu(this,"_disconnectedReason",void 0),nu(this,"_websocketReconnectReason",void 0),nu(this,"_connectionState",Ev.CLOSED),nu(this,"reconnectToken",void 0),nu(this,"websocket",void 0),nu(this,"openConnectionTime",void 0),nu(this,"clientId",void 0),nu(this,"lastMsgTime",Date.now()),nu(this,"uploadCache",[]),nu(this,"uploadCacheInterval",void 0),nu(this,"rttRolling",new dT(5)),nu(this,"pingpongTimer",void 0),nu(this,"wsInflateDataTimer",void 0),nu(this,"pingpongTimeoutCount",0),nu(this,"joinResponse",void 0),nu(this,"multiIpOption",void 0),nu(this,"initError",void 0),nu(this,"spec",void 0),nu(this,"store",void 0),nu(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(mv.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){if(this.emit(t._type,t._message),t._type===Sv.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Sv.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(cS.UID_BANNED);break;case 15:this.close(cS.IP_BANNED);break;case 16:this.close(cS.CHANNEL_BANNED)}if(t._type===Sv.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case _v.ERR_LICENSE_MISSING:this.close(cS.LICENSE_MISSING);break;case _v.ERR_LICENSE_EXPIRED:this.close(cS.LICENSE_EXPIRED);break;case _v.ERR_LICENSE_MINUTES_EXCEEDED:this.close(cS.LICENSE_MINUTES_EXCEEDED);break;case _v.ERR_LICENSE_PERIOD_INVALID:this.close(cS.LICENSE_PERIOD_INVALID);break;case _v.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(cS.LICENSE_MULTIPLE_SDK_SERVICE);break;case _v.ERR_LICENSE_ILLEGAL:this.close(cS.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new qI("gateway-".concat(this.clientId),this.spec.retryConfig,!0,kC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),kC("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===Ev.CONNECTED&&this.reconnect("retry",lS.OFFLINE)}))}async request(e,t,i,n){const r=xS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new tg(((t,i)=>{if(this.connectionState===Ev.CONNECTED)return t();const n=()=>{this.off(mv.WS_CLOSED,r),t()},r=()=>{this.off(mv.WS_CONNECTED,n),i(new Mv(xg.WS_ABORT))};this.once(mv.WS_CONNECTED,n),this.once(mv.WS_CLOSED,r),e!==fv.PUBLISH&&e!==fv.SUBSCRIBE&&e!==fv.UNSUBSCRIBE&&e!==fv.UNPUBLISH&&e!==fv.CONTROL&&e!==fv.RESTART_ICE||this.once(mv.DISCONNECT_P2P,(()=>{i(new Mv(xg.DISCONNECT_P2P))})),e!==fv.PUBLISH&&e!==fv.RESTART_ICE||this.once(mv.ABORT_P2P_EXECUTION,(()=>{i(new Mv(xg.DISCONNECT_P2P))}))}));if(this.connectionState!==Ev.CONNECTING&&this.connectionState!==Ev.RECONNECTING||e===fv.JOIN||e===fv.REJOIN||await a(),this.websocket.sendMessage(s,!0),n)return;const c=new tg(((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.emit(mv.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new Mv(xg.WS_ABORT,"type: ".concat(e))),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(mv.WS_CLOSED,c),this.once(mv.WS_RECONNECTING,c),US(kC("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==o||s||(WC.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(mv.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===Ev.CLOSED||e===fv.LEAVE)throw new Mv(xg.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===fv.JOIN||e===fv.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),h=kI(l),u=new Mv(xg.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===h.action?d.message:(WC.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(h.desc,", action: ").concat(h.action)),l===_v.ERR_TOO_MANY_BROADCASTERS?e===fv.JOIN||e===fv.REJOIN?(this.initError=u,this.close(),u.throw()):u.throw():"failed"===h.action?u.throw():"quit"===h.action?(this.initError=u,this.close(),u.throw()):(l===_v.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,WC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",lS.MULTI_IP)):this.reconnect(h.action,lS.SERVER_ERROR),e===fv.JOIN||e===fv.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new tg((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=kC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==Ev.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),kC("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new tg(((t,i)=>{this.once(mv.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(mv.WS_CLOSED,(()=>i(this.initError||new Mv(xg.WS_ABORT)))),this.connectionState=Ev.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||cS.LEAVE,this.connectionState=Ev.CLOSED,WC.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===cS.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new qI("gateway-".concat(this.clientId),this.spec.retryConfig,!0,kC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),kC("JOIN_GATEWAY_USE_443PORT_ONLY"),this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(mv.ABORT_P2P_EXECUTION);const e=await fS(this,mv.REQUEST_JOIN_INFO),t=await this.request(fv.JOIN,e);if(!t)return this.emit(mv.REPORT_JOIN_GATEWAY,$v.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(mv.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new Mv(xg.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=TS(this,mv.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(fv.REJOIN,e);return!!t&&(this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(Sv.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(Sv.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(Sv.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(Sv.MUTE_AUDIO,{uid:e.uid}):this.emit(Sv.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(Sv.MUTE_VIDEO,{uid:e.uid}):this.emit(Sv.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(Sv.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(Sv.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(Sv.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(Sv.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(Sv.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleNotification(e){WC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kI(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(cS.UID_BANNED),void this.close()):void this.reconnect(t.action,lS.SERVER_ERROR);WC.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=kC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(WC.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>kC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",lS.TIMEOUT):this.request(fv.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),kC("REPORT_STATS")&&this.send(fv.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(gv.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(Cv.RECONNECT_WAITTING_FINISH,(e=>{this.emit(mv.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(Cv.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(mv.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(Cv.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Cv.CLOSED,(()=>{this.connectionState=Ev.CLOSED})),this.websocket.on(Cv.FAILED,(()=>{this._disconnectedReason=cS.NETWORK_ERROR,this.connectionState=Ev.CLOSED})),this.websocket.on(Cv.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Ev.CONNECTED?this.connectionState=Ev.RECONNECTING:this.connectionState=Ev.CONNECTING})),this.websocket.on(Cv.WILL_RECONNECT,((e,t,i)=>{const n=TS(this,mv.IS_P2P_DISCONNECTED),r=n||"retry"!==e;n&&"retry"===e&&(WC.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=$v.P2P_DISCONNECTED),r&&(WC.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(mv.REPORT_JOIN_GATEWAY,t||$v.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(mv.NEED_RENEW_SESSION),this.emit(mv.DISCONNECT_P2P)),i(e)})),this.websocket.on(Cv.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{WC.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",lS.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(mv.REPORT_JOIN_GATEWAY,e.message||e.code||$v.UNKNOWN_REASON,this.url||""),e instanceof Mv&&e.code===xg.UNEXPECTED_RESPONSE&&e.data.code===_v.ERR_NO_AUTHORIZED)return WC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",lS.SERVER_ERROR);WC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",lS.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(Cv.REQUEST_NEW_URLS,((e,t)=>{fS(this,mv.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(Cv.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(Sv.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}var XI="\t\n\v\f\r                 \u2028\u2029\ufeff",QI=tt,ZI=Sr,$I=XI,ey=Ee("".replace),ty=RegExp("^["+$I+"]+"),iy=RegExp("(^|[^"+$I+"])["+$I+"]+$"),ny=function(e){return function(t){var i=ZI(QI(t));return 1&e&&(i=ey(i,ty,"")),2&e&&(i=ey(i,iy,"$1")),i}},ry={start:ny(1),end:ny(2),trim:ny(3)},sy=zd.PROPER,oy=de,ay=XI,cy=ry.trim;Mn({target:"String",proto:!0,forced:function(e){return oy((function(){return!!ay[e]()||"​…᠎"!=="​…᠎"[e]()||sy&&ay[e].name!==e}))}("trim")},{trim:function(){return cy(this)}});var dy,ly,hy=tr("String").trim,uy=me,py=hy,_y=String.prototype,Ey=z((function(e){var t=e.trim;return"string"==typeof e||e===_y||uy(_y,e)&&t===_y.trim?py:t}));function my(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function fy(e,t,i,n,r){return{width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r}}function gy(e,t,i,n,r){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r}}function Sy(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}!function(e){e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK"}(dy||(dy={})),function(e){e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change"}(ly||(ly={}));const Ty={"90p":fy(160,90),"90p_1":fy(160,90),"120p":fy(160,120,15,30,65),"120p_1":fy(160,120,15,30,65),"120p_3":fy(120,120,15,30,50),"120p_4":fy(212,120),"180p":fy(320,180,15,30,140),"180p_1":fy(320,180,15,30,140),"180p_3":fy(180,180,15,30,100),"180p_4":fy(240,180,15,30,120),"240p":fy(320,240,15,40,200),"240p_1":fy(320,240,15,40,200),"240p_3":fy(240,240,15,40,140),"240p_4":fy(424,240,15,40,220),"360p":fy(640,360,15,80,400),"360p_1":fy(640,360,15,80,400),"360p_3":fy(360,360,15,80,260),"360p_4":fy(640,360,30,80,600),"360p_6":fy(360,360,30,80,400),"360p_7":fy(480,360,15,80,320),"360p_8":fy(480,360,30,80,490),"360p_9":fy(640,360,15,80,800),"360p_10":fy(640,360,24,80,800),"360p_11":fy(640,360,24,80,1e3),"480p":fy(640,480,15,100,500),"480p_1":fy(640,480,15,100,500),"480p_2":fy(640,480,30,100,1e3),"480p_3":fy(480,480,15,100,400),"480p_4":fy(640,480,30,100,750),"480p_6":fy(480,480,30,100,600),"480p_8":fy(848,480,15,100,610),"480p_9":fy(848,480,30,100,930),"480p_10":fy(640,480,10,100,400),"720p":fy(1280,720,15,120,1130),"720p_1":fy(1280,720,15,120,1130),"720p_2":fy(1280,720,30,120,2e3),"720p_3":fy(1280,720,30,120,1710),"720p_5":fy(960,720,15,120,910),"720p_6":fy(960,720,30,120,1380),"1080p":fy(1920,1080,15,120,2080),"1080p_1":fy(1920,1080,15,120,2080),"1080p_2":fy(1920,1080,30,120,3e3),"1080p_3":fy(1920,1080,30,120,3150),"1080p_5":fy(1920,1080,60,120,4780),"1440p":fy(2560,1440,30,120,4850),"1440p_1":fy(2560,1440,30,120,4850),"1440p_2":fy(2560,1440,60,120,7350),"4k":fy(3840,2160,30,120,8910),"4k_1":fy(3840,2160,30,120,8910),"4k_3":fy(3840,2160,60,120,13500)},Ry={"480p":gy(640,480,5),"480p_1":gy(640,480,5),"480p_2":gy(640,480,30),"480p_3":gy(640,480,15),"720p":gy(1280,720,5),"720p_1":gy(1280,720,5),"720p_2":gy(1280,720,30),"720p_3":gy(1280,720,15),"1080p":gy(1920,1080,5),"1080p_1":gy(1920,1080,5),"1080p_2":gy(1920,1080,30),"1080p_3":gy(1920,1080,15)},Cy={"1SL1TL":Sy(1,1),"3SL3TL":Sy(3,3),"2SL3TL":Sy(2,3)};function vy(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},Ty[e]):e}function Iy(e){return"string"==typeof e?Object.assign({},Ry[e]):e}function yy(e){return"string"==typeof e?Object.assign({},Cy[e]):e}const Ay={speech_low_quality:my(16e3,!1),speech_standard:my(32e3,!1,18),music_standard:my(48e3,!1),standard_stereo:my(48e3,!0,56),high_quality:my(48e3,!1,128),high_quality_stereo:my(48e3,!0,192)};function by(e){return"string"==typeof e?Object.assign({},Ay[e]):e}const wy=[];function Oy(e){return Bg(e,"mediaSource",["screen","window","application"]),!0}var Ny,Dy,Py,Ly,ky,My,Uy,xy,Vy,Fy;!function(e){e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track"}(Ny||(Ny={})),function(e){e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream"}(Dy||(Dy={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM"}(Py||(Py={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM"}(Ly||(Ly={})),function(e){e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY"}(ky||(ky={})),function(e){e.TRANSCEIVER_UPDATED="transceiver-updated"}(My||(My={})),function(e){e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed"}(Uy||(Uy={})),function(e){e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status"}(xy||(xy={})),function(e){e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source"}(Vy||(Vy={})),function(e){e.UPDATE_TRACK_SOURCE="update-track-source"}(Fy||(Fy={}));const By={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},jy={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},Gy={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},Wy={uplinkNetworkQuality:0,downlinkNetworkQuality:0},Hy={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};var Ky,Yy,qy,Jy,zy;!function(e){e.ON_TRACK="on_track",e.ON_NODE="on_node"}(Ky||(Ky={})),function(e){e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints"}(Yy||(Yy={})),function(e){e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND"}(qy||(qy={})),function(e){e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged"}(Jy||(Jy={})),function(e){e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata"}(zy||(zy={}));const Xy={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};var Qy;!function(e){e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error"}(Qy||(Qy={}));class Zy extends iS{constructor(e,t){super(),nu(this,"_ID",void 0),nu(this,"_rtpTransceiver",void 0),nu(this,"_lowRtpTransceiver",void 0),nu(this,"_hints",[]),nu(this,"_isClosed",!1),nu(this,"_originMediaStreamTrack",void 0),nu(this,"_mediaStreamTrack",void 0),nu(this,"_external",{}),this._ID=t||xS(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,function(e){Lr(wy).call(wy,e)||wy.push(e)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){if(!e){const e=iv.reportApiInvoke(null,{name:sS.GET_MEDIA_STREAM_TRACK,options:[],tag:oS.TRACER});this._mediaStreamTrack&&"string"==typeof this._mediaStreamTrack.label?e.onSuccess(this._mediaStreamTrack.label):e.onSuccess("")}return this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===Py.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){const t=wy.indexOf(e);-1!==t&&wy.splice(t,1)}(this),this.emit(Uy.CLOSED)}_updateRtpTransceiver(e,t){if(t===Py.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(My.TRANSCEIVER_UPDATED,e,t)}}class $y extends Zy{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}constructor(e,t){super(e,t),nu(this,"_enabled",!0),nu(this,"_muted",!1),nu(this,"_isExternalTrack",!1),nu(this,"_isClosed",!1),nu(this,"_enabledMutex",void 0),nu(this,"processor",void 0),nu(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new YS("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,WC.debug("[".concat(this.getTrackId(),"] close")),this.emit(Ny.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gS(this,Ny.NEED_REPLACE_TRACK,this),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){WC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Uy.TRACK_ENDED)}stateCheck(e,t){if(WC.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),Fg(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new Vg(xg.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",WC);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new Vg(xg.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",WC)}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}function eA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const tA=window.AudioContext||window.webkitAudioContext;let iA=null;const nA=new class extends iS{constructor(){super(...arguments),nu(this,"prevState",void 0),nu(this,"curState",void 0),nu(this,"currentTime",void 0),nu(this,"currentTimeStuckAt",void 0),nu(this,"interruptDetectorTrack",void 0),nu(this,"onLocalAudioTrackMute",(()=>{WC.info("ios15-interruption-start"),this.emit(ly.IOS_15_16_INTERRUPTION_START)})),nu(this,"onLocalAudioTrackUnmute",(async()=>{WC.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?WC.info("ios15-interruption-end-canceled"):(iA&&await iA.suspend(),this.emit(ly.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){WC.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){WC.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function rA(){if(!tA)return void WC.error("your browser is not support web audio");WC.info("create audio context");const e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?eA(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):eA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},kC("WEBAUDIO_INIT_OPTIONS"));WC.debug("audio context init option:",JSON.stringify(e)),iA=new tA(e),nA.curState=iA.state,iA.onstatechange=()=>{nA.prevState=nA.curState,nA.curState=iA?iA.state:void 0;const{prevState:e,curState:t}=nA,i="running"===t,n="interrupted"===t,r="running"===e,s="suspended"===e,o="interrupted"===e,a=pg().osVersion;(Cg()||Dg())&&r&&n&&(WC.info("ios".concat(a,"-interruption-start")),nA.emit(ly.IOS_INTERRUPTION_START)),(Cg()||Dg())&&(s||o)&&i&&(WC.info("ios".concat(a,"-interruption-end")),nA.emit(ly.IOS_INTERRUPTION_END)),e!==t&&(WC.debug("AudioContext State Change","".concat(e,"=>").concat(t)),nA.emit(ly.STATE_CHANGE))},setInterval((()=>{var e;const t=null===(e=iA)||void 0===e?void 0:e.currentTime;nA.currentTime!==t?(nA.currentTimeStuckAt&&(WC.debug("AudioContext current time resume at ".concat(t)),nA.currentTimeStuckAt=void 0),nA.currentTime=t):(t!==nA.currentTimeStuckAt&&(iv.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:oS.TRACER}).onSuccess(),WC.warning("AudioContext current time stuck at ".concat(t))),nA.currentTimeStuckAt=t)}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,n=!1,r=!1,s=!1;function o(t){"running"===e.state?a(!1):Cg()||Dg()?"suspended"===e.state&&(a(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(a(!0),t&&e.resume().then(d,d))}function a(e){if(n!==e){n=e;for(let i=0,n=t;i<n.length;i+=1){const t=n[i];e?window.addEventListener(t,l,{capture:!0,passive:!0}):window.removeEventListener(t,l,{capture:!0,passive:!0})}}}function c(){o(!0)}function d(){o(!1)}function l(){o(!0)}function h(e){if(!s)if(i.paused)if(e){let t;u(!1),s=!0;try{t=i.play(),t?t.then(p,p):(i.addEventListener("playing",p),i.addEventListener("abort",p),i.addEventListener("error",p))}catch(e){p()}}else u(!0);else u(!1)}function u(e){if(r!==e){r=e;for(let i=0,n=t;i<n.length;i++){const t=n[i];e?window.addEventListener(t,_,{capture:!0,passive:!0}):window.removeEventListener(t,_,{capture:!0,passive:!0})}}}function p(){i.removeEventListener("playing",p),i.removeEventListener("abort",p),i.removeEventListener("error",p),s=!1,h(!1)}function _(){h(!0)}if(Cg()){const t=e.createMediaStreamDestination(),n=document.createElement("div");n.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=n.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,h(!0)}nA.on(ly.STATE_CHANGE,c),o(!1)}(iA)}function sA(){if(!iA){if(rA(),!iA)throw new Vg(xg.NOT_SUPPORTED,"can not create audio context");return iA}return iA}function oA(){return!!iA}function aA(e){if(function(){if(null!==cA)return cA;const e=sA(),t=e.createBufferSource(),i=e.createGain(),n=e.createGain();t.connect(i),t.connect(n),t.disconnect(i);let r=!1;try{t.disconnect(i)}catch(e){r=!0}return t.disconnect(),cA=r,r}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>{var s;return e._inputNodes||(e._inputNodes=[]),Lr(s=e._inputNodes).call(s,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,n,r)):t.call(e,i,n)),e},e.disconnect=(n,r,s)=>{i.call(e),n?IS(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}let cA=null;function dA(e,t){let i=!1;const n=1/t;if(kC("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*n)}else{const t=sA();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const s=()=>{if(i)return void(r=null);const o=t.createOscillator();o.onended=s,o.connect(r),o.start(0),o.stop(t.currentTime+n),e(t.currentTime)};s()}return()=>{i=!0}}const lA={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1};function hA(){return lA}class uA{constructor(){nu(this,"context",void 0),nu(this,"analyserNode",void 0),nu(this,"sourceNode",void 0),this.context=sA(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||Cg()||Dg()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;i<e.length;++i)e[i]=t[i]/128-1}const t=cT(e).call(e,((e,t)=>e+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){WC.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class pA extends iS{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),nu(this,"outputNode",void 0),nu(this,"outputTrack",void 0),nu(this,"isPlayed",!1),nu(this,"context",void 0),nu(this,"audioBufferNode",void 0),nu(this,"destNode",void 0),nu(this,"audioOutputLevel",0),nu(this,"volumeLevelAnalyser",void 0),nu(this,"_processedNode",void 0),nu(this,"playNode",void 0),nu(this,"isDestroyed",!1),nu(this,"onNoAudioInput",void 0),nu(this,"isNoAudioInput",!1),nu(this,"_noAudioInputCount",0),this.context=sA(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),aA(this.outputNode),this.volumeLevelAnalyser=new uA}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit(Vy.ON_AUDIO_BUFFER,function(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const i=e.outputBuffer.getChannelData(t);for(let e=0;e<i.length;e+=1)i[e]=0}return e.inputBuffer}(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!hA().webAudioMediaStreamDest)throw new Vg(xg.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(e){"running"!==this.context.state&&AS((()=>{nA.emit("autoplay-failed")})),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(e){}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;Cg()||Dg()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let n=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(n=!0);return n?(this.isNoAudioInput=!1,!0):(await US(200),await this.checkHasAudioInput(e?e+1:1)&&n)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode),this.volumeLevelAnalyser.updateSource(this.outputNode)}}class _A extends pA{get isFreeze(){return!1}constructor(e,t,i){var n;if(super(),nu(this,"sourceNode",void 0),nu(this,"track",void 0),nu(this,"clonedTrack",void 0),nu(this,"audioElement",void 0),nu(this,"isCurrentTrackCloned",!1),nu(this,"isRemoteTrack",!1),nu(this,"originVolumeLevelAnalyser",void 0),nu(this,"rebuildWebAudio",(async()=>{if(WC.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void WC.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>WC.info("resume success"))),WC.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),aA(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),aA(this.outputNode),this.emit(Vy.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==e.kind)throw new Vg(xg.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),aA(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,WC.debug("create an unmuted track ".concat(e.id," from the original track ").concat(i.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));aA(t),this.originVolumeLevelAnalyser=new uA,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const s=pg();t&&s.os===ag.IOS&&Number(null===(n=s.osVersion)||void 0===n?void 0:n.split(".")[0])<15&&(nA.on(ly.STATE_CHANGE,(()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio()})),this.checkHasAudioInput().then((e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0)})))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),aA(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(Vy.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),nA.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),WC.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const i=this.context.createMediaStreamSource(new MediaStream([t]));aA(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function EA(e,t,i){const n=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:n(t.height,1080),maxWidth:n(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r)}async function mA(e,t){const i=await fA(e.mediaSource),{sourceId:n,audio:r}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new tg(((i,n)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const s=document.createElement("div");s.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const o=document.createElement("div");o.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",o.setAttribute("style","height: 12%;");const a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(u);const e=new Error("NotAllowedError");e.name="NotAllowedError",n(e)};let l=t;const h=document.createElement("div");if(t){const e=document.createElement("input");e.setAttribute("type","checkbox");const t=document.createElement("span");e.setAttribute("style","margin-right: 6px;"),t.innerText="Share audio",e.checked=l,e.onchange=()=>{l=e.checked},h.appendChild(e),h.appendChild(t)}c.appendChild(h),c.appendChild(d),s.appendChild(o),s.appendChild(a),s.appendChild(c);const u=document.createElement("div");u.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),u.appendChild(r),u.appendChild(s),document.body.appendChild(u),e.map((e=>{if(e.id){const t=document.createElement("div");t.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let n=e.thumbnail;try{const{width:e}=n.getSize();e>1920&&(n=n.resize({width:1920}))}catch(e){throw e&&e.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),e}t.innerHTML='<div style="height: 120px; display: table-cell; vertical-align: middle;"><img style="width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);" src='+n.toDataURL()+' /></div><span style="\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+e.name.replace(/[\u00A0-\u9999<>\&]/g,(function(e){return"&#"+e.charCodeAt(0)+";"}))+"</span>",t.onclick=()=>{document.body.removeChild(u),i({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(i,t);return await EA(n,e,r)}async function fA(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=rS();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new Vg(xg.ELECTRON_IS_NULL);let n=null;try{var r;n=(null===(r=i.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){n=null}n&&n.then||(n=new tg(((e,n)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?n(t):e(i)}))})));try{return await n}catch(e){throw new Vg(xg.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}function gA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const SA=new YS("safari");let TA=!1,RA=!1;async function CA(e,t){let i=0,n=null;for(;i<2;)try{n=await vA(e,t,i>0);break}catch(e){if(e instanceof Vg)throw WC.error("[".concat(t,"] ").concat(e.toString())),e;const n=IA(e.name||e.code||e,e.message);if(n.code===xg.MEDIA_OPTION_INVALID){WC.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await US(500);continue}throw WC.error("[".concat(t,"] ").concat(n.toString())),n}if(!n)throw new Vg(xg.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n}async function vA(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Vg(xg.NOT_SUPPORTED,"can not find getUserMedia");i&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const n=hA(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return WC.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(rS())e.screen.sourceId?yA(r,await EA(e.screen.sourceId,e.screen,e.screenAudio)):yA(r,await mA(e.screen,e.screenAudio));else if(Sg()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new Vg(xg.NOT_SUPPORTED,"This browser does not support screen sharing");WC.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const i=await(o=e.screen.extensionId,a=t,new tg(((e,t)=>{try{chrome.runtime.sendMessage(o,{getStream:!0},(i=>{if(!i||!i.streamId)return WC.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new Vg(xg.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){WC.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(o,")"),e.toString()),t(new Vg(xg.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=i,yA(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(n.getDisplayMedia){var s;e.screen.mediaSource&&Oy(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(s=e.screen.displaySurface)&&void 0!==s?s:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},{selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a}=e.screen,c={selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a};!n&&delete c.selfBrowserSurface,!o&&delete c.surfaceSwitching,!a&&delete c.systemAudio,WC.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:!!e.screenAudio,controls:c}));const d=await navigator.mediaDevices.getDisplayMedia(function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?gA(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):gA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({video:i,audio:!!e.screenAudio},c));yA(r,d)}else{if(!Rg())throw WC.error("[".concat(t,"] This browser does not support screenSharing")),new Vg(xg.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&Oy(e.screen.mediaSource);const i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};WC.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i))),yA(r,await navigator.mediaDevices.getUserMedia(i))}}var o,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=kC("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=WS(c,d)}catch(e){}WC.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),pg();let l,h=null;(Tg()||Cg()||mg())&&(h=await SA.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw h&&h(),e}return c.audio&&(TA=!0),c.video&&(RA=!0),yA(r,l),h&&h(),r}function IA(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new Vg(xg.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new Vg(xg.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new Vg(xg.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new Vg(xg.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new Vg(xg.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new Vg(xg.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return WC.error("getUserMedia unexpected error",e),new Vg(xg.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function yA(e,t){const i=e.getVideoTracks()[0],n=e.getAudioTracks()[0],r=t.getVideoTracks()[0],s=t.getAudioTracks()[0];s&&(n&&e.removeTrack(n),e.addTrack(s)),r&&(i&&e.removeTrack(i),e.addTrack(r))}const AA=new class extends iS{get state(){return this._state}set state(e){e!==this._state&&(this.emit(Jy.STATE_CHANGE,e),this._state=e)}constructor(){super(),nu(this,"_state",qy.IDLE),nu(this,"isAccessMicrophonePermission",!1),nu(this,"isAccessCameraPermission",!1),nu(this,"lastAccessMicrophonePermission",!1),nu(this,"lastAccessCameraPermission",!1),nu(this,"checkdeviceMatched",!1),nu(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(kC("ENUMERATE_DEVICES_INTERVAL")||(Mg()||_g()===ag.HARMONY_OS)&&kg())&&this.updateDevicesInfo()}),kC("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>WC.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return new Vg(xg.NOT_SUPPORTED,"enumerateDevices() not supported.").throw();const n=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(n);let s=!this.isAccessMicrophonePermission&&e,o=!this.isAccessCameraPermission&&t;r.audio&&(s=!1),r.video&&(o=!1);let a=null,c=null,d=null;if(!i&&(s||o)){if(SA.isLocked&&(WC.debug("[device manager] wait GUM lock"),(await SA.lock())(),WC.debug("[device manager] GUM unlock")),TA&&(s=!1,this.isAccessMicrophonePermission=!0),RA&&(o=!1,this.isAccessCameraPermission=!0),WC.debug("[device manager] check media device permissions",e,t,s,o),s&&o){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=IA(e.name||e.code||e,e.message);if(t.code===xg.PERMISSION_DENIED)throw t;WC.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(s){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=IA(e.name||e.code||e,e.message);if(t.code===xg.PERMISSION_DENIED)throw t;WC.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(o){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=IA(e.name||e.code||e,e.message);if(t.code===xg.PERMISSION_DENIED)throw t;WC.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}WC.debug("[device manager] mic permission",e,"cam permission",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,e}catch(e){return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,new Vg(xg.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audioinput"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>"videoinput"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audiooutput"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((i=>{i.device.label===e&&(t=i.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new Vg(xg.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=qy.INITING;try{await this.updateDevicesInfo(),this.state=qy.INITEND}catch(e){throw WC.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=qy.IDLE,("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname)||new Vg(xg.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw(),e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),i=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&i?i.groupId===t.groupId?WC.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):WC.warning("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):WC.debug("[device-check] default input or output not found")}const n=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const n=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(n?n.state:"INACTIVE")){const n={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),n),i.push(n)}n&&(n.updateAt=t)})),this.deviceInfoMap.forEach(((e,n)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))})),this.state!==qy.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(Jy.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(Jy.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(Jy.PLAYOUT_DEVICE_CHANGED,e)}})),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),i=e.filter((e=>"videoinput"===e.kind)),n={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){n.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){n.video=!0;break}return n}};let bA=!1;const wA=new class extends iS{constructor(){super(...arguments),nu(this,"onAutoplayFailed",void 0),nu(this,"onAudioAutoplayFailed",void 0)}};function OA(){if(pg(),!bA){const e=t=>{t.preventDefault(),bA=!1,Ug()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};bA=!0,Ug()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),WC.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),wA.onAutoplayFailed?wA.onAutoplayFailed():wA.onAudioAutoplayFailed?WC.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):WC.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),wA.emit("autoplay-failed")}}function NA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function DA(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?NA(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):NA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function PA(e,t,i,n){if(!e)return;const r=iv.getBaseInfoBySessionId(e);if(!r)return;const s=r.info,o=Date.now(),a=DA(DA({},s),{},{vid:void 0===s.vid?0:Number(s.vid),lts:o,elapse:o-r.startTime,cbRegistered:wA.onAutoplayFailed||wA.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:n,extend:void 0});iv.send({type:zC.AUTOPLAY_FAILED,data:a},!0)}const LA=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],kA=new class{constructor(){nu(this,"onAutoplayFailed",void 0),nu(this,"elementMap",new Map),nu(this,"elementStateMap",new Map),nu(this,"elementsNeedToResume",[]),nu(this,"sinkIdMap",new Map),nu(this,"autoResumeAfterInterruption",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const n=this.elementStateMap.get(t),r=i.srcObject.getAudioTracks()[0];wg()?r&&"live"===r.readyState&&"running"===nA.curState&&(WC.debug("auto resume after interruption for iOS 15"),i.pause(),i.play()):n&&"paused"===n&&r&&"live"===r.readyState&&"running"===nA.curState&&(WC.debug("auto resume after interruption for iOS"),i.play())}))})),nu(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&"live"===n.readyState&&(WC.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),nA.on(ly.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),nA.on(ly.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),nA.on(ly.STATE_CHANGE,(()=>{Cg()&&"suspended"===nA.prevState&&"running"===nA.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new Vg(xg.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,n){if(this.elementMap.has(t))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,zy.INIT),this.setVolume(t,i);const s=this.sinkIdMap.get(t);if(s)try{r.setSinkId(s).catch((e=>{WC.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){WC.warning("[".concat(t,"] set sink id failed"),e.toString())}const o=r.play();o&&o.then&&o.catch((e=>{n&&PA(n,"audio",e.message,t),WC.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(WC.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),AS((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),OA()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){LA.forEach((i=>{t.addEventListener(i,(i=>{const n=this.elementStateMap.get(e),r="pause"===i.type?"paused":i.type;if(WC.debug("[".concat(e,"] audio-element-status change ").concat(n," => ").concat(r)),"error"===i.type){const i=null==t?void 0:t.error;i&&WC.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message))}this.elementStateMap.set(e,r)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{WC.debug("Auto resume audio element success")})).catch((e=>{WC.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};new tg((e=>{document.body?e():window.addEventListener("load",(()=>e()))})).then((()=>{Ug()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function MA(){return function(e,t,i){const n=i.value;return"function"==typeof n&&(i.value=function(){this._isClosed&&new Vg(xg.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",WC);for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const r=n.apply(this,t);return r instanceof tg?new tg(((e,t)=>{r.then(e).catch(t)})):r}),i}}function UA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function xA(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?UA(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):UA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class VA extends iS{constructor(e){super(),nu(this,"name","VideoProcessorDestination"),nu(this,"ID","0"),nu(this,"_source",void 0),nu(this,"videoContext",void 0),nu(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new Vg(xg.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new Vg(xg.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(Ky.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(Ky.ON_TRACK,void 0)}}class FA extends iS{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),nu(this,"constraintsMap",new Map),nu(this,"statsRegistry",[]),nu(this,"usageRegistry",[]),nu(this,"trackId",void 0),nu(this,"direction",void 0),nu(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await fS(this,Yy.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return WC.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),gS(this,Yy.REQUEST_UPDATE_CONSTRAINTS,Array.from(Pv(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return WC.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),gS(this,Yy.REQUEST_UPDATE_CONSTRAINTS,Array.from(Pv(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const s=r();e.push({processorID:t,processorName:i,type:n,stats:s})}catch(e){WC.error(new Vg(xg.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof tg&&(i=await i),e.push(xA(xA({},i),{},{direction:this.direction}))}catch(e){WC.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class BA extends iS{constructor(e){super(),nu(this,"name","AudioProcessorDestination"),nu(this,"ID","0"),nu(this,"inputTrack",void 0),nu(this,"inputNode",void 0),nu(this,"audioProcessorContext",void 0),nu(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new Vg(xg.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new Vg(xg.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(Ky.ON_TRACK,void 0),this.emit(Ky.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(Ky.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(Ky.ON_NODE,this.inputNode))}}class jA extends iS{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),nu(this,"constraintsMap",new Map),nu(this,"statsRegistry",[]),nu(this,"audioContext",void 0),nu(this,"trackId",void 0),nu(this,"direction",void 0),nu(this,"usageRegistry",[]),nu(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return fS(this,Yy.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return WC.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),gS(this,Yy.REQUEST_UPDATE_CONSTRAINTS,Array.from(Pv(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),gS(this,Yy.REQUEST_UPDATE_CONSTRAINTS,Array.from(Pv(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const s=r();e.push({processorID:t,processorName:i,type:n,stats:s})}catch(e){WC.error(new Vg(xg.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof tg&&(i=await i),e.push(xA(xA({},i),{},{direction:this.direction}))}catch(e){WC.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class GA extends iS{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),nu(this,"context",void 0),nu(this,"processSourceNode",void 0),nu(this,"outputTrack",void 0),nu(this,"processedNode",void 0),nu(this,"clonedTrack",void 0),nu(this,"outputNode",void 0),this.outputNode=new WA}setVolume(){}createOutputTrack(){throw new Vg(xg.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class WA{disconnect(){}connect(){}}let HA=null;class KA{constructor(){nu(this,"state","open"),nu(this,"trigger",void 0),nu(this,"tasks",[]),WC.debug("[macro-task-queue] is created."),this.trigger=window.setTimeout((()=>{this.state="closed",WC.debug("[macro-task-queue] will be closed, all remaining tasks will execute. [".concat(this.tasks.map((e=>e.key)),"]")),this.trigger=void 0,this.tasks.forEach((e=>{let{func:t}=e;return t()})),this.tasks.length=0,WC.debug("[macro-task-queue] is closed.")}))}enqueue(e,t){"closed"!==this.state&&(this.tasks.push({key:e,func:t}),WC.debug("[macro-task-queue] is queued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")))}runTask(e){if("closed"===this.state)return;const t=this.tasks.findIndex((t=>t.key===e));if(-1!==t){const i=this.tasks.splice(t,1);WC.debug("[macro-task-queue] is unqueued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")),i[0].func()}}release(){this.trigger&&(this.state="closed",clearTimeout(this.trigger),this.trigger=void 0,this.tasks.length=0,WC.debug("[macro-task-queue] is closed."))}}function YA(e){return function(t,i,n){var r;const s=null!==(r=n.value)&&void 0!==r?r:n.get,o=function(){HA&&"open"===HA.state&&HA.runTask(e);for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return null==s?void 0:s.apply(this,...i)};return n.value?n.value=o:n.get=o,n}}function qA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function JA(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?qA(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):qA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class zA extends $y{get _source(){return this._trackSource}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get processorDestination(){return this._processorDestination}set processorDestination(e){this._processorDestination=e}get isPlaying(){return this._useAudioElement?kA.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,n,r){super(e,i),nu(this,"trackMediaType","audio"),nu(this,"_encoderConfig",void 0),nu(this,"_trackSource",void 0),nu(this,"_enabled",!0),nu(this,"_volume",100),nu(this,"_useAudioElement",!1),nu(this,"_bypassWebAudio",!1),nu(this,"processor",void 0),nu(this,"_processorContext",void 0),nu(this,"_processorDestination",void 0),nu(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!n;const s=()=>{this.processorContext=new jA(this._source.context,this.getTrackId(),"local"),this.processorDestination=new BA(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Vy.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))},o=r&&Tg()&&!oA();kC("DISABLE_WEBAUDIO")?(this._source=new GA,this._useAudioElement=!0,this._bypassWebAudio=!0):o?this._source=new GA:(this._source=new _A(e,!1,this._getOriginVolumeLevel?e:void 0),kC("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0)),s(),!kC("DISABLE_WEBAUDIO")&&o&&(HA||(HA=new KA),HA).enqueue("INIT_WEBAUDIO",(()=>{this._source=new _A(e,!1,this._getOriginVolumeLevel?e:void 0),kC("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0),s(),this.emit(Fy.UPDATE_TRACK_SOURCE)}))}setVolume(e){jg(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&kA.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void WC.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,gS(this,Ny.NEED_REPLACE_TRACK,this).then((()=>{WC.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{WC.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e)})))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement)throw new Vg(xg.NOT_SUPPORTED,"your browser does not support setting the audio output device");await kA.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,i){return this._setEnabled(e,t,i)}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(WC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await gS(this,Ny.NEED_ENABLE_TRACK,this),WC.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),WC.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await gS(this,Ny.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),WC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,WC.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await gS(this,Ny.NEED_MUTE_TRACK,this):await gS(this,Ny.NEED_UNMUTE_TRACK,this))}getStats(){return NS((()=>{WC.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning"),SS(this,Ny.GET_STATS)||JA({},By)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Vy.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Vy.ON_AUDIO_BUFFER),this._source.on(Vy.ON_AUDIO_BUFFER,(t=>e(t)))}play(){WC.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(WC.debug("[".concat(this.getTrackId(),"] start audio playback in element")),kA.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){WC.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?kA.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];WC.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&kA.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this.processor.updateInput({track:e,context:this.processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gS(this,Ny.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return tg.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new Vg(xg.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new Vg(xg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Ky.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await gS(this,Ny.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gS(this,Ny.NEED_REPLACE_TRACK,this))})),this.processorDestination.on(Ky.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Ky.ON_TRACK),this.processorDestination.removeAllListeners(Ky.ON_NODE)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(Yy.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(Yy.REQUEST_CONSTRAINTS)}}Lv([YA("INIT_WEBAUDIO"),kv("design:type",Object),kv("design:paramtypes",[Object])],zA.prototype,"_source",null),Lv([YA("INIT_WEBAUDIO"),kv("design:type",jA),kv("design:paramtypes",[jA])],zA.prototype,"processorContext",null),Lv([YA("INIT_WEBAUDIO"),kv("design:type",BA),kv("design:paramtypes",[BA])],zA.prototype,"processorDestination",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",void 0)],zA.prototype,"setVolume",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],zA.prototype,"setPlaybackDevice",null),Lv([qS("LocalAudioTrack","_enabledMutex"),tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Object,Boolean]),kv("design:returntype",tg)],zA.prototype,"setEnabled",null),Lv([qS("LocalAudioTrack","_enabledMutex"),tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean]),kv("design:returntype",tg)],zA.prototype,"setMuted",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",Object)],zA.prototype,"getStats",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[Object,Number]),kv("design:returntype",void 0)],zA.prototype,"setAudioFrameCallback",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],zA.prototype,"play",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],zA.prototype,"stop",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],zA.prototype,"close",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t.name]}),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",Object)],zA.prototype,"pipe",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],zA.prototype,"unpipe",null);class XA extends zA{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,n){super(e,t.encoderConfig?by(t.encoderConfig):{},n,kC("GET_VOLUME_OF_MUTED_AUDIO_TRACK"),!0),nu(this,"_config",void 0),nu(this,"_deviceName","default"),nu(this,"_constraints",void 0),nu(this,"_originalConstraints",void 0),nu(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(wg()||Og())&&nA.bindInterruptDetectorTrack(this),this.on(Fy.UPDATE_TRACK_SOURCE,(()=>{this.bindProcessorContextEvents()})),oA()&&this.bindProcessorContextEvents()}async setDevice(e){if(WC.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await AA.getDeviceById(e),i={};i.audio=JA({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await CA(i,this.getTrackId())}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await CA({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await AA.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return WC.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(WC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){var n;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(n=this._source.clonedTrack)||void 0===n||n.stop(),i||(this._enabled=!1);try{await gS(this,Ny.NEED_DISABLE_TRACK,this)}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=JA({},this._constraints),s=AA.searchDeviceIdByName(this._deviceName);s&&!r.deviceId&&(r.deviceId=s);try{i||(this._enabled=!0);const e=await CA({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await gS(this,Ny.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),WC.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(wg()||Og())&&nA.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((Cg()||Dg())&&this._enabled&&!this._isClosed&&nA.duringInterruption){const e=async()=>{nA.off(ly.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(WC.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};nA.on(ly.IOS_INTERRUPTION_END,e)}else WC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Uy.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=AA.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await CA({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(){this.processorContext.on(Yy.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(Yy.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}}Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],XA.prototype,"setDevice",null),Lv([qS("MicrophoneAudioTrack","_enabledMutex"),tv({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Boolean,Boolean]),kv("design:returntype",tg)],XA.prototype,"setEnabled",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],XA.prototype,"close",null);class QA extends zA{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),nu(this,"source",void 0),nu(this,"_bufferSource",void 0),this.source=e,this._bufferSource=t,this._bufferSource.on(Vy.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(Uy.SOURCE_STATE_CHANGE,e)}));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){jg(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",void 0)],QA.prototype,"startProcessAudioBuffer",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],QA.prototype,"pauseProcessAudioBuffer",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",void 0)],QA.prototype,"seekAudioBuffer",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],QA.prototype,"resumeProcessAudioBuffer",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],QA.prototype,"stopProcessAudioBuffer",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],QA.prototype,"close",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",void 0)],QA.prototype,"setAudioBufferPlaybackSpeed",null);class ZA extends zA{get __className__(){return"MixingAudioTrack"}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){const e=sA().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,xS(8,"track-mix-")),nu(this,"trackList",void 0),nu(this,"destNode",void 0);try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return-1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(WC.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):WC.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){WC.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}IS(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach((t=>{t instanceof ZA?t.emit(My.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}function $A(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=vy(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!Lg()&&i.frameRate&&(t.frameRate=i.frameRate),pg().name===cg.EDGE&&"object"==typeof t.frameRate&&(t.frameRate.max=60),Rg()&&(t.frameRate={ideal:30,max:30}),t}function eb(e){const t={};if(Lg()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,Sg()&&e.ANS&&(t.googHighpassFilter=e.ANS))),e.encoderConfig){const i=by(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),Mg()&&(t.sampleRate=void 0),t}class tb extends pA{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(Vy.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),nu(this,"audioBuffer",void 0),nu(this,"sourceNode",void 0),nu(this,"startPlayTime",0),nu(this,"startPlayOffset",0),nu(this,"pausePlayTime",0),nu(this,"options",void 0),nu(this,"currentLoopCount",0),nu(this,"currentPlaybackSpeed",100),nu(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):WC.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(e){}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}}const ib=new Map;async function nb(e,t){let i=null;if("string"==typeof e){const t=ib.get(e);if(t)return WC.debug("use cached audio resource: ",e),t;try{i=(await XS((()=>EC.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new Vg(xg.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new tg(((t,i)=>{const n=new FileReader;n.onload=e=>{e.target?t(e.target.result):i(new Vg(xg.READ_LOCAL_AUDIO_FILE_ERROR))},n.onerror=()=>{i(new Vg(xg.READ_LOCAL_AUDIO_FILE_ERROR))},n.readAsArrayBuffer(e)}));i=await t}const n=await function(e){const t=sA();return new tg(((i,n)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{n(new Vg(xg.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}(i);return"string"==typeof e&&t&&ib.set(e,n),n}const rb=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new tg(((i,n)=>{t.toBlob((async e=>{if(t.remove(),e){const n=await sb(e);i({buffer:n,width:t.width,height:t.height})}else n(new Vg(xg.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},sb=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)},ob=new class extends iS{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),nu(this,"_lastHiddenTime",0),nu(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),WC.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}};function ab(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function cb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ab(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ab(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class db{get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(WC.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}constructor(e){nu(this,"trackId",void 0),nu(this,"config",void 0),nu(this,"onFirstVideoFrameDecoded",void 0),nu(this,"freezeTimeCounterList",[]),nu(this,"renderFreezeAccTime",0),nu(this,"isKeepLastFrame",!1),nu(this,"timeUpdatedCount",0),nu(this,"freezeTime",0),nu(this,"playbackTime",0),nu(this,"lastTimeUpdatedTime",0),nu(this,"autoplayFailed",!1),nu(this,"videoTrack",void 0),nu(this,"videoElement",void 0),nu(this,"cacheVideoElement",void 0),nu(this,"videoElementCheckInterval",void 0),nu(this,"_videoElementStatus",zy.NONE),nu(this,"isGettingVideoDimensions",!1),nu(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return WC.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),nu(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===nA.curState&&(WC.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Eg())),Ng()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),nu(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=zy.PLAYING;break;case"loadeddata":if(this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=zy.CANPLAY;break;case"stalled":this.videoElementStatus=zy.STALLED;break;case"suspend":this.videoElementStatus=zy.SUSPEND;break;case"pause":this.videoElementStatus=zy.PAUSED,Cg()||Dg()||Tg()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(WC.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=zy.WAITING;break;case"abort":this.videoElementStatus=zy.ABORT;break;case"ended":this.videoElementStatus=zy.ENDED;break;case"emptied":this.videoElementStatus=zy.EMPTIED;break;case"error":{this.videoElementStatus=zy.ERROR;const e=this.videoElement.error;e&&WC.error("[".concat(this.trackId,"] media error, code: ").concat(e.code,", message: ").concat(e.message));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,ob.lastVisibleTime<ob.lastHiddenTime||i<ob.lastHiddenTime||i<ob.lastVisibleTime)return;for(t>kC("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}})),nu(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(WC.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Eg())),Ng()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),nA.on(ly.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),nA.on(ly.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch((t=>{e&&PA(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(WC.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):WC.warning("[".concat(this.trackId,"] play warning: "),t)}));const i=pg();if(("Safari"===i.name&&15===Number(i.version)||wg())&&t&&t.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};t.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return WC.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const n=i.getContext("2d");return n?(n.drawImage(this.videoElement,0,0,i.width,i.height),new tg(((n,r)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await sb(e);n({buffer:t,width:i.width,height:i.height})}else r(new Vg(xg.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await rb(e)}destroy(){nA.off(ly.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),nA.off(ly.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[]}initVideoElement(){if(this.videoElementStatus=zy.INIT,!this.videoElementCheckInterval&&(lb.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{(function(e){return e!==document.body&&document.body.contains(e)})(this.videoElement)||(this.videoElementStatus=zy.DESTROYED)}),1e3),kC("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i;const n=(e,t)=>{if(this.videoElementStatus===zy.PLAYING){if(i){const e=t.presentationTime-i.presentationTime;e>kC("VIDEO_FREEZE_DURATION")&&ob.lastVisibleTime>=ob.lastHiddenTime&&i.timestamp>ob.lastVisibleTime&&i.timestamp>ob.lastHiddenTime&&(this.renderFreezeAccTime+=e)}i=cb(cb({},t),{},{timestamp:e})}var r,s;kC("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(r=(s=this.videoElement).requestVideoFrameCallback)||void 0===r||r.call(s,n))};null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e||e.call(t,n)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),Mg()&&(this.videoElement.poster="noposter");const i=pg();"Safari"===i.name&&15===Number(i.version)||wg()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream?this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Rg()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Rg()&&this.videoElement.load());const n=this.videoElement.play();void 0!==n&&n.catch((e=>{WC.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){lb.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=zy.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{WC.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{WC.error(e)})),this.autoplayFailed=!1,Ug()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};Ug()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),OA()}}const lb=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class hb extends db{constructor(e){super(e),nu(this,"container",void 0),nu(this,"slot",void 0),this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await rb(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",kC("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}function ub(e){return new tg(((t,i)=>{let n=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const s=Cg()?"canplay":"playing";r.addEventListener(s,(()=>{const e=r.videoWidth,i=r.videoHeight;!e&&Rg()||(n=!0,r.srcObject=null,r.remove(),t([e,i]))})),r.srcObject=new MediaStream([e]),r.play().catch(FS),setTimeout((()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}const pb=async(e,t,i)=>{const n=function(e){const t=[];for(let i=0;i<e.length;i+=2)t.push(parseInt(e.slice(i,i+2),16));return Uint8Array.from(t)}(function(e){const t="0123456789abcdef";function i(e){let i,n="";for(i=0;i<=3;i++)n+=t.charAt(e>>8*i+4&15)+t.charAt(e>>8*i&15);return n}function n(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function r(e,t,i,r,s,o){return n(function(e,t){return e<<t|e>>>32-t}(n(n(t,e),n(r,o)),s),i)}function s(e,t,i,n,s,o,a){return r(t&i|~t&n,e,t,s,o,a)}function o(e,t,i,n,s,o,a){return r(t&n|i&~n,e,t,s,o,a)}function a(e,t,i,n,s,o,a){return r(t^i^n,e,t,s,o,a)}function c(e,t,i,n,s,o,a){return r(i^(t|~n),e,t,s,o,a)}const d=function(e){let t;const i=1+(e.length+8>>6),n=new Array(16*i);for(t=0;t<16*i;t++)n[t]=0;for(t=0;t<e.length;t++)n[t>>2]|=e.charCodeAt(t)<<t%4*8;return n[t>>2]|=128<<t%4*8,n[16*i-2]=8*e.length,n}(e);let l,h,u,p,_,E=1732584193,m=-271733879,f=-1732584194,g=271733878;for(l=0;l<d.length;l+=16)h=E,u=m,p=f,_=g,E=s(E,m,f,g,d[l+0],7,-680876936),g=s(g,E,m,f,d[l+1],12,-389564586),f=s(f,g,E,m,d[l+2],17,606105819),m=s(m,f,g,E,d[l+3],22,-1044525330),E=s(E,m,f,g,d[l+4],7,-176418897),g=s(g,E,m,f,d[l+5],12,1200080426),f=s(f,g,E,m,d[l+6],17,-1473231341),m=s(m,f,g,E,d[l+7],22,-45705983),E=s(E,m,f,g,d[l+8],7,1770035416),g=s(g,E,m,f,d[l+9],12,-1958414417),f=s(f,g,E,m,d[l+10],17,-42063),m=s(m,f,g,E,d[l+11],22,-1990404162),E=s(E,m,f,g,d[l+12],7,1804603682),g=s(g,E,m,f,d[l+13],12,-40341101),f=s(f,g,E,m,d[l+14],17,-1502002290),m=s(m,f,g,E,d[l+15],22,1236535329),E=o(E,m,f,g,d[l+1],5,-165796510),g=o(g,E,m,f,d[l+6],9,-1069501632),f=o(f,g,E,m,d[l+11],14,643717713),m=o(m,f,g,E,d[l+0],20,-373897302),E=o(E,m,f,g,d[l+5],5,-701558691),g=o(g,E,m,f,d[l+10],9,38016083),f=o(f,g,E,m,d[l+15],14,-660478335),m=o(m,f,g,E,d[l+4],20,-405537848),E=o(E,m,f,g,d[l+9],5,568446438),g=o(g,E,m,f,d[l+14],9,-1019803690),f=o(f,g,E,m,d[l+3],14,-187363961),m=o(m,f,g,E,d[l+8],20,1163531501),E=o(E,m,f,g,d[l+13],5,-1444681467),g=o(g,E,m,f,d[l+2],9,-51403784),f=o(f,g,E,m,d[l+7],14,1735328473),m=o(m,f,g,E,d[l+12],20,-1926607734),E=a(E,m,f,g,d[l+5],4,-378558),g=a(g,E,m,f,d[l+8],11,-2022574463),f=a(f,g,E,m,d[l+11],16,1839030562),m=a(m,f,g,E,d[l+14],23,-35309556),E=a(E,m,f,g,d[l+1],4,-1530992060),g=a(g,E,m,f,d[l+4],11,1272893353),f=a(f,g,E,m,d[l+7],16,-155497632),m=a(m,f,g,E,d[l+10],23,-1094730640),E=a(E,m,f,g,d[l+13],4,681279174),g=a(g,E,m,f,d[l+0],11,-358537222),f=a(f,g,E,m,d[l+3],16,-722521979),m=a(m,f,g,E,d[l+6],23,76029189),E=a(E,m,f,g,d[l+9],4,-640364487),g=a(g,E,m,f,d[l+12],11,-421815835),f=a(f,g,E,m,d[l+15],16,530742520),m=a(m,f,g,E,d[l+2],23,-995338651),E=c(E,m,f,g,d[l+0],6,-198630844),g=c(g,E,m,f,d[l+7],10,1126891415),f=c(f,g,E,m,d[l+14],15,-1416354905),m=c(m,f,g,E,d[l+5],21,-57434055),E=c(E,m,f,g,d[l+12],6,1700485571),g=c(g,E,m,f,d[l+3],10,-1894986606),f=c(f,g,E,m,d[l+10],15,-1051523),m=c(m,f,g,E,d[l+1],21,-2054922799),E=c(E,m,f,g,d[l+8],6,1873313359),g=c(g,E,m,f,d[l+15],10,-30611744),f=c(f,g,E,m,d[l+6],15,-1560198380),m=c(m,f,g,E,d[l+13],21,1309151649),E=c(E,m,f,g,d[l+4],6,-145523070),g=c(g,E,m,f,d[l+11],10,-1120210379),f=c(f,g,E,m,d[l+2],15,718787259),m=c(m,f,g,E,d[l+9],21,-343485551),E=n(E,h),m=n(m,u),f=n(f,p),g=n(g,_);return i(E)+i(m)+i(f)+i(g)}(""+t+i)).slice(0,16),r=n.slice(0,12),s=await window.crypto.subtle.importKey("raw",n,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},s,e))},_b=async(e,t,i)=>await pb(e.buffer,t,i);function Eb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function mb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Eb(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Eb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class fb extends $y{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==zy.PLAYING)}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,t,i,n,r,s){if(super(e,r),nu(this,"trackMediaType","video"),nu(this,"_player",void 0),nu(this,"_videoVisibleTimer",null),nu(this,"_previousVideoVisibleStatus",void 0),nu(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),nu(this,"_encoderConfig",void 0),nu(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),nu(this,"_optimizationMode",void 0),nu(this,"_videoHeight",void 0),nu(this,"_videoWidth",void 0),nu(this,"_forceBitrateLimit",void 0),nu(this,"_enabled",!0),nu(this,"processorDestination",void 0),nu(this,"_processorContext",void 0),Tg()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=t,this._scalabilityMode=i,this._optimizationMode=n,this._hints=s||[],-1===this._hints.indexOf(Dy.SCREEN_TRACK))this.updateBitrateFromProfile();else if(function(e,t,i){const n=pg();return!(n.name!==e||!n.osVersion)&&(i?Number(n.version)>=t&&Number(n.version)<=i:Number(n.version)===t)}(cg.CHROME,115)&&-1!==_g().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&hA().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),n=new MediaStreamTrackGenerator({kind:"video"});let r,s,o=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),r&&(r.close(),r=void 0),e.stop(),s=void 0,n.removeEventListener("ended",a)};let c=window.setInterval((()=>{if(s&&r&&Date.now()-o>(null!=t?t:1e3))try{"live"===n.readyState?s.enqueue(r.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===n.readyState?(s=t,o=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close()}});return n.addEventListener("ended",a),i.readable.pipeThrough(d).pipeTo(n.writable),n}}(e);t&&(WC.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(Dy.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this.processorContext=new FA(this.getTrackId(),"local"),this.processorDestination=new VA(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(WC.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}WC.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=mb(mb(mb({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new db(i):this._player=new hb(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Uy.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),kC("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,WC.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(WC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await gS(this,Ny.NEED_DISABLE_TRACK,this)}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void WC.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await gS(this,Ny.NEED_ENABLE_TRACK,this)}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,WC.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await gS(this,Ny.NEED_MUTE_TRACK,this):await gS(this,Ny.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Vg(xg.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=vy(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=$A({encoderConfig:e});(Tg()||Cg()||Dg())&&(t.deviceId=void 0),WC.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new Vg(xg.UNEXPECTED_ERROR,e.toString());throw WC.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(Dy.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await gS(this,Ny.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(WC)}}getStats(){return NS((()=>{WC.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning"),SS(this,Ny.GET_STATS)||mb({},jy)}async setBeautyEffect(e){WC.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await rb(e)}async setBitrateLimit(e){if(WC.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e){this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<e.max_bitrate?this._encoderConfig.bitrateMax:e.max_bitrate:this._encoderConfig.bitrateMax=e.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=e.min_bitrate);try{await gS(this,Ny.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(WC)}}}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void WC.error(xg.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await gS(this,Ny.SET_OPTIMIZATION_MODE,this)}catch(e){throw this._optimizationMode=t,WC.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return WC.error(xg.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,WC.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){ub(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(FS)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const[n,r]=function(e,t,i,n){let r;const s=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75),o=s;if("STANDARD_BITRATE"===n)r=4*s;else{if("COMPATIABLE_BITRATE"!==n)return;r=2*s}return[Math.floor(r),Math.floor(o)]}(e,t,i,kC("BITRATE_ADAPTER_TYPE"))||[void 0,void 0];this._encoderConfig.bitrateMin||this._encoderConfig.bitrateMax||(this._encoderConfig.bitrateMin=r,this._encoderConfig.bitrateMax=n,WC.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(n,", brMin: ").concat(r,"]")))}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:s}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=Qg.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new Vg(xg.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new Vg(xg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=mb(mb({},i),vy(e))),i=wS(i);const n=xS(8,"track-video-cloned-"),r=new fb(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,i,wS(this._scalabilityMode),this._optimizationMode,n,wS(this._hints));return e&&i&&r.setEncoderConfiguration(i),WC.debug("clone video track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(t)),r}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new Vg(xg.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new Vg(xg.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}bindProcessorDestinationEvents(){this.processorDestination.on(Ky.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await gS(this,Ny.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gS(this,Ny.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Ky.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(Yy.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(Yy.REQUEST_CONSTRAINTS)}}Lv([tv({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Object,Object]),kv("design:returntype",void 0)],fb.prototype,"play",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],fb.prototype,"stop",null),Lv([qS("LocalVideoTrack","_enabledMutex"),tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Boolean]),kv("design:returntype",tg)],fb.prototype,"setEnabled",null),Lv([qS("LocalVideoTrack","_enabledMutex"),tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean]),kv("design:returntype",tg)],fb.prototype,"setMuted",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Object,Boolean]),kv("design:returntype",tg)],fb.prototype,"setEncoderConfiguration",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",Object)],fb.prototype,"getStats",null),Lv([tv({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Object]),kv("design:returntype",tg)],fb.prototype,"setBeautyEffect",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",ImageData)],fb.prototype,"getCurrentFrameData",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[String,Number]),kv("design:returntype",tg)],fb.prototype,"getCurrentFrameImage",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],fb.prototype,"setBitrateLimit",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],fb.prototype,"setOptimizationMode",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",void 0)],fb.prototype,"setScalabiltyMode",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],fb.prototype,"updateMediaStreamTrackResolution",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t.name]}),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",Object)],fb.prototype,"pipe",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],fb.prototype,"unpipe",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],fb.prototype,"close",null),Lv([tv({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),kv("design:type",Function),kv("design:paramtypes",[MediaStreamTrack,Boolean]),kv("design:returntype",tg)],fb.prototype,"replaceTrack",null);class gb extends fb{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,n,r,s){super(e,vy(t.encoderConfig),n,r,s),nu(this,"_config",void 0),nu(this,"_originalConstraints",void 0),nu(this,"_constraints",void 0),nu(this,"_enabled",!0),nu(this,"_deviceName","default"),nu(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(wg()||Og())&&!function(){const e=pg();if(e.os!==ag.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}()&&Pg()&&this._enabled&&!this._isClosed&&(WC.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=vy(this._config.encoderConfig),nA.on(ly.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),nA.on(ly.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(e){return"string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0}async _setDeviceById(e){if(WC.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await AA.getDeviceById(e),i={};i.video=mb({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await CA(i,this.getTrackId())}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await CA({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await AA.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){WC.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:mb(mb({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await CA(t,this.getTrackId())}catch(t){throw WC.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await CA({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=mb({},t.video),WC.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(WC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await CA({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await gS(this,Ny.NEED_ENABLE_TRACK,this)}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),WC.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await gS(this,Ny.NEED_DISABLE_TRACK,this)}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Vg(xg.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=vy(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin);const i=bS(this._config);i.encoderConfig=e;const n=$A(i);(Tg()||Cg()||Dg())&&(n.deviceId=void 0),WC.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(n));try{await this._originMediaStreamTrack.applyConstraints(n),this.updateMediaStreamTrackResolution()}catch(e){const t=new Vg(xg.UNEXPECTED_ERROR,e.toString());throw WC.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=i,this._constraints=n,this._originalConstraints=n,this._encoderConfig=e,-1===this._hints.indexOf(Dy.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await gS(this,Ny.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(WC)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((Cg()||Dg())&&this._enabled&&!this._isClosed&&nA.duringInterruption){const e=async()=>{nA.off(ly.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(WC.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};nA.on(ly.IOS_INTERRUPTION_END,e)}else WC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Uy.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=AA.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await CA({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),nA.off(ly.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),nA.off(ly.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=mb(mb({},i),vy(e))),i=wS(i);const n=xS(8,"track-cam-cloned-"),r=new gb(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,wS(mb(mb({},this._config),{},{encoderConfig:i})),wS(this._constraints),wS(this._scalabilityMode),this._optimizationMode,n);return e&&i&&r.setEncoderConfiguration(i),WC.debug("clone track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(t)),r}bindProcessorContextEvents(){this.processorContext.on(Yy.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(Yy.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}}function Sb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Tb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Sb(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Sb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Rb(e,t,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=Tb(Tb({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?WC.debug("[".concat(e,"] set content hint to"),i.optimizationMode):WC.debug("[".concat(e,"] set content hint failed")))):WC.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}function Cb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function vb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Cb(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Cb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],gb.prototype,"setDevice",null),Lv([qS("CameraVideoTrack","_enabledMutex"),tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Boolean]),kv("design:returntype",tg)],gb.prototype,"setEnabled",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Object,Boolean]),kv("design:returntype",tg)],gb.prototype,"setEncoderConfiguration",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],gb.prototype,"close",null);class Ib extends Zy{getUserId(){return this._userId}constructor(e,t,i,n){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(n.clientId,"_").concat(xS(5,""))),nu(this,"_userId",void 0),nu(this,"_uintId",void 0),nu(this,"_isDestroyed",!1),nu(this,"store",void 0),nu(this,"processor",void 0),this._userId=t,this._uintId=i,this.store=n}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,WC.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}class yb extends Ib{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==zy.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,n){super(e,t,i,n),nu(this,"_videoVisibleTimer",null),nu(this,"_previousVideoVisibleStatus",void 0),nu(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),nu(this,"trackMediaType","video"),nu(this,"_videoWidth",void 0),nu(this,"_videoHeight",void 0),nu(this,"_player",void 0),nu(this,"processorDestination",void 0),nu(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new FA(this.getTrackId(),"remote"),this.processorDestination=new VA(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return NS((()=>{WC.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning"),SS(this,Ny.GET_STATS)||vb({},Hy)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(WC.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}WC.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=vb(vb({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new db(i):this._player=new hb(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(xy.FIRST_FRAME_DECODED)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(xy.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),kC("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,WC.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){ub(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(FS)}_updatePlayerSource(){WC.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:s}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=Qg.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new Vg(xg.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new Vg(xg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Ky.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Ky.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}}Lv([tv({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),kv("design:type",Function),kv("design:paramtypes",[Object,Object]),kv("design:returntype",void 0)],yb.prototype,"play",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],yb.prototype,"stop",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t.name]}),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",Object)],yb.prototype,"pipe",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],yb.prototype,"unpipe",null);class Ab extends Ib{get isPlaying(){return this._useAudioElement?kA.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,n){super(e,t,i,n),nu(this,"trackMediaType","audio"),nu(this,"_source",void 0),nu(this,"_useAudioElement",!0),nu(this,"_volume",100),nu(this,"processorContext",void 0),nu(this,"processorDestination",void 0),nu(this,"_played",!1),nu(this,"_bypassWebAudio",!1),kC("DISABLE_WEBAUDIO")?(this._source=new GA,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new _A(e,!0),kC("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(Vy.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(xy.FIRST_FRAME_DECODED)})),this.processorContext=new jA(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new BA(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Vy.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Vy.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Vy.ON_AUDIO_BUFFER),this._source.on(Vy.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?kA.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement)throw new Vg(xg.NOT_SUPPORTED,"your browser does not support setting the audio output device");await kA.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){return NS((()=>{WC.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning"),SS(this,Ny.GET_STATS)||vb({},Gy)}play(){WC.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(WC.debug("[".concat(this.getTrackId(),"] use audio element to play")),kA.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){WC.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?kA.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];WC.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&kA.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new Vg(xg.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new Vg(xg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new Vg(xg.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Ky.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(Ky.ON_NODE,(e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Ky.ON_TRACK),this.processorDestination.removeAllListeners(Ky.ON_NODE)}}function bb(e){let t=e.length;for(;--t>=0;)e[t]=0}Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",void 0)],Ab.prototype,"setVolume",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],Ab.prototype,"setPlaybackDevice",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],Ab.prototype,"play",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],Ab.prototype,"stop",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t.name]}),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",Object)],Ab.prototype,"pipe",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],Ab.prototype,"unpipe",null);const wb=256,Ob=286,Nb=30,Db=15,Pb=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Lb=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),kb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Mb=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ub=new Array(576);bb(Ub);const xb=new Array(60);bb(xb);const Vb=new Array(512);bb(Vb);const Fb=new Array(256);bb(Fb);const Bb=new Array(29);bb(Bb);const jb=new Array(Nb);function Gb(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}let Wb,Hb,Kb;function Yb(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}bb(jb);const qb=e=>e<256?Vb[e]:Vb[256+(e>>>7)],Jb=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},zb=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,Jb(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)},Xb=(e,t,i)=>{zb(e,i[2*t],i[2*t+1])},Qb=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},Zb=(e,t,i)=>{const n=new Array(16);let r,s,o=0;for(r=1;r<=Db;r++)o=o+i[r-1]<<1,n[r]=o;for(s=0;s<=t;s++){let t=e[2*s+1];0!==t&&(e[2*s]=Qb(n[t]++,t))}},$b=e=>{let t;for(t=0;t<Ob;t++)e.dyn_ltree[2*t]=0;for(t=0;t<Nb;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},ew=e=>{e.bi_valid>8?Jb(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},tw=(e,t,i,n)=>{const r=2*t,s=2*i;return e[r]<e[s]||e[r]===e[s]&&n[t]<=n[i]},iw=(e,t,i)=>{const n=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r<e.heap_len&&tw(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!tw(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n},nw=(e,t,i)=>{let n,r,s,o,a=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+a++],n+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],0===n?Xb(e,r,t):(s=Fb[r],Xb(e,s+wb+1,t),o=Pb[s],0!==o&&(r-=Bb[s],zb(e,r,o)),n--,s=qb(n),Xb(e,s,i),o=Lb[s],0!==o&&(n-=jb[s],zb(e,n,o)))}while(a<e.sym_next);Xb(e,256,t)},rw=(e,t)=>{const i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,s=t.stat_desc.elems;let o,a,c,d=-1;for(e.heap_len=0,e.heap_max=573,o=0;o<s;o++)0!==i[2*o]?(e.heap[++e.heap_len]=d=o,e.depth[o]=0):i[2*o+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=d<2?++d:0,i[2*c]=1,e.depth[c]=0,e.opt_len--,r&&(e.static_len-=n[2*c+1]);for(t.max_code=d,o=e.heap_len>>1;o>=1;o--)iw(e,i,o);c=s;do{o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],iw(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=a,i[2*c]=i[2*o]+i[2*a],e.depth[c]=(e.depth[o]>=e.depth[a]?e.depth[o]:e.depth[a])+1,i[2*o+1]=i[2*a+1]=c,e.heap[1]=c++,iw(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,s=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,l,h,u,p,_,E=0;for(u=0;u<=Db;u++)e.bl_count[u]=0;for(i[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)l=e.heap[d],u=i[2*i[2*l+1]+1]+1,u>c&&(u=c,E++),i[2*l+1]=u,l>n||(e.bl_count[u]++,p=0,l>=a&&(p=o[l-a]),_=i[2*l],e.opt_len+=_*(u+p),s&&(e.static_len+=_*(r[2*l+1]+p)));if(0!==E){do{for(u=c-1;0===e.bl_count[u];)u--;e.bl_count[u]--,e.bl_count[u+1]+=2,e.bl_count[c]--,E-=2}while(E>0);for(u=c;0!==u;u--)for(l=e.bl_count[u];0!==l;)h=e.heap[--d],h>n||(i[2*h+1]!==u&&(e.opt_len+=(u-i[2*h+1])*i[2*h],i[2*h+1]=u),l--)}})(e,t),Zb(i,d,e.bl_count)},sw=(e,t,i)=>{let n,r,s=-1,o=t[1],a=0,c=7,d=4;for(0===o&&(c=138,d=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=o,o=t[2*(n+1)+1],++a<c&&r===o||(a<d?e.bl_tree[2*r]+=a:0!==r?(r!==s&&e.bl_tree[2*r]++,e.bl_tree[32]++):a<=10?e.bl_tree[34]++:e.bl_tree[36]++,a=0,s=r,0===o?(c=138,d=3):r===o?(c=6,d=3):(c=7,d=4))},ow=(e,t,i)=>{let n,r,s=-1,o=t[1],a=0,c=7,d=4;for(0===o&&(c=138,d=3),n=0;n<=i;n++)if(r=o,o=t[2*(n+1)+1],!(++a<c&&r===o)){if(a<d)do{Xb(e,r,e.bl_tree)}while(0!=--a);else 0!==r?(r!==s&&(Xb(e,r,e.bl_tree),a--),Xb(e,16,e.bl_tree),zb(e,a-3,2)):a<=10?(Xb(e,17,e.bl_tree),zb(e,a-3,3)):(Xb(e,18,e.bl_tree),zb(e,a-11,7));a=0,s=r,0===o?(c=138,d=3):r===o?(c=6,d=3):(c=7,d=4)}};let aw=!1;const cw=(e,t,i,n)=>{zb(e,0+(n?1:0),3),ew(e),Jb(e,i),Jb(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var dw=e=>{aw||((()=>{let e,t,i,n,r;const s=new Array(16);for(i=0,n=0;n<28;n++)for(Bb[n]=i,e=0;e<1<<Pb[n];e++)Fb[i++]=n;for(Fb[i-1]=n,r=0,n=0;n<16;n++)for(jb[n]=r,e=0;e<1<<Lb[n];e++)Vb[r++]=n;for(r>>=7;n<Nb;n++)for(jb[n]=r<<7,e=0;e<1<<Lb[n]-7;e++)Vb[256+r++]=n;for(t=0;t<=Db;t++)s[t]=0;for(e=0;e<=143;)Ub[2*e+1]=8,e++,s[8]++;for(;e<=255;)Ub[2*e+1]=9,e++,s[9]++;for(;e<=279;)Ub[2*e+1]=7,e++,s[7]++;for(;e<=287;)Ub[2*e+1]=8,e++,s[8]++;for(Zb(Ub,287,s),e=0;e<Nb;e++)xb[2*e+1]=5,xb[2*e]=Qb(e,5);Wb=new Gb(Ub,Pb,257,Ob,Db),Hb=new Gb(xb,Lb,0,Nb,Db),Kb=new Gb(new Array(0),kb,0,19,7)})(),aw=!0),e.l_desc=new Yb(e.dyn_ltree,Wb),e.d_desc=new Yb(e.dyn_dtree,Hb),e.bl_desc=new Yb(e.bl_tree,Kb),e.bi_buf=0,e.bi_valid=0,$b(e)},lw=(e,t,i,n)=>{let r,s,o=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<wb;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),rw(e,e.l_desc),rw(e,e.d_desc),o=(e=>{let t;for(sw(e,e.dyn_ltree,e.l_desc.max_code),sw(e,e.dyn_dtree,e.d_desc.max_code),rw(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*Mb[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=r&&(r=s)):r=s=i+5,i+4<=r&&-1!==t?cw(e,t,i,n):4===e.strategy||s===r?(zb(e,2+(n?1:0),3),nw(e,Ub,xb)):(zb(e,4+(n?1:0),3),((e,t,i,n)=>{let r;for(zb(e,t-257,5),zb(e,i-1,5),zb(e,n-4,4),r=0;r<n;r++)zb(e,e.bl_tree[2*Mb[r]+1],3);ow(e,e.dyn_ltree,t-1),ow(e,e.dyn_dtree,i-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,o+1),nw(e,e.dyn_ltree,e.dyn_dtree)),$b(e),n&&ew(e)},hw=(e,t,i)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(Fb[i]+wb+1)]++,e.dyn_dtree[2*qb(t)]++),e.sym_next===e.sym_end),uw={_tr_init:dw,_tr_stored_block:cw,_tr_flush_block:lw,_tr_tally:hw,_tr_align:e=>{zb(e,2,3),Xb(e,256,Ub),(e=>{16===e.bi_valid?(Jb(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)}},pw=(e,t,i,n)=>{let r=65535&e|0,s=e>>>16&65535|0,o=0;for(;0!==i;){o=i>2e3?2e3:i,i-=o;do{r=r+t[n++]|0,s=s+r|0}while(--o);r%=65521,s%=65521}return r|s<<16|0};const _w=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var Ew=(e,t,i,n)=>{const r=_w,s=n+i;e^=-1;for(let i=n;i<s;i++)e=e>>>8^r[255&(e^t[i])];return-1^e},mw={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},fw={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:gw,_tr_stored_block:Sw,_tr_flush_block:Tw,_tr_tally:Rw,_tr_align:Cw}=uw,{Z_NO_FLUSH:vw,Z_PARTIAL_FLUSH:Iw,Z_FULL_FLUSH:yw,Z_FINISH:Aw,Z_BLOCK:bw,Z_OK:ww,Z_STREAM_END:Ow,Z_STREAM_ERROR:Nw,Z_DATA_ERROR:Dw,Z_BUF_ERROR:Pw,Z_DEFAULT_COMPRESSION:Lw,Z_FILTERED:kw,Z_HUFFMAN_ONLY:Mw,Z_RLE:Uw,Z_FIXED:xw,Z_DEFAULT_STRATEGY:Vw,Z_UNKNOWN:Fw,Z_DEFLATED:Bw}=fw,jw=286,Gw=30,Ww=19,Hw=2*jw+1,Kw=15,Yw=258,qw=262,Jw=42,zw=113,Xw=666,Qw=(e,t)=>(e.msg=mw[t],t),Zw=e=>2*e-(e>4?9:0),$w=e=>{let t=e.length;for(;--t>=0;)e[t]=0},eO=e=>{let t,i,n,r=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=r?i-r:0}while(--t);t=r,n=t;do{i=e.prev[--n],e.prev[n]=i>=r?i-r:0}while(--t)};let tO=(e,t,i)=>(t<<e.hash_shift^i)&e.hash_mask;const iO=e=>{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},nO=(e,t)=>{Tw(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,iO(e.strm)},rO=(e,t)=>{e.pending_buf[e.pending++]=t},sO=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},oO=(e,t,i,n)=>{let r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=pw(e.adler,t,r,i):2===e.state.wrap&&(e.adler=Ew(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},aO=(e,t)=>{let i,n,r=e.max_chain_length,s=e.strstart,o=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-qw?e.strstart-(e.w_size-qw):0,d=e.window,l=e.w_mask,h=e.prev,u=e.strstart+Yw;let p=d[s+o-1],_=d[s+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,d[i+o]===_&&d[i+o-1]===p&&d[i]===d[s]&&d[++i]===d[s+1]){s+=2,i++;do{}while(d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&s<u);if(n=Yw-(u-s),s=u-Yw,n>o){if(e.match_start=t,o=n,n>=a)break;p=d[s+o-1],_=d[s+o]}}}while((t=h[t&l])>c&&0!=--r);return o<=e.lookahead?o:e.lookahead},cO=e=>{const t=e.w_size;let i,n,r;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-qw)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),eO(e),n+=t),0===e.strm.avail_in)break;if(i=oO(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=tO(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=tO(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<qw&&0!==e.strm.avail_in)},dO=(e,t)=>{let i,n,r,s=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,o=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_out<r)break;if(r=e.strm.avail_out-r,n=e.strstart-e.block_start,i>n+e.strm.avail_in&&(i=n+e.strm.avail_in),i>r&&(i=r),i<s&&(0===i&&t!==Aw||t===vw||i!==n+e.strm.avail_in))break;o=t===Aw&&i===n+e.strm.avail_in?1:0,Sw(e,0,0,o),e.pending_buf[e.pending-4]=i,e.pending_buf[e.pending-3]=i>>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,iO(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(oO(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===o);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),o?4:t!==vw&&t!==Aw&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(r=e.window_size-e.strstart,e.strm.avail_in>r&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(oO(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water<e.strstart&&(e.high_water=e.strstart),r=e.bi_valid+42>>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,s=r>e.w_size?e.w_size:r,n=e.strstart-e.block_start,(n>=s||(n||t===Aw)&&t!==vw&&0===e.strm.avail_in&&n<=r)&&(i=n>r?r:n,o=t===Aw&&0===e.strm.avail_in&&i===n?1:0,Sw(e,e.block_start,i,o),e.block_start+=i,iO(e.strm)),o?3:1)},lO=(e,t)=>{let i,n;for(;;){if(e.lookahead<qw){if(cO(e),e.lookahead<qw&&t===vw)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=tO(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-qw&&(e.match_length=aO(e,i)),e.match_length>=3)if(n=Rw(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=tO(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=tO(e,e.ins_h,e.window[e.strstart+1]);else n=Rw(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(nO(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===Aw?(nO(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nO(e,!1),0===e.strm.avail_out)?1:2},hO=(e,t)=>{let i,n,r;for(;;){if(e.lookahead<qw){if(cO(e),e.lookahead<qw&&t===vw)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=tO(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-qw&&(e.match_length=aO(e,i),e.match_length<=5&&(e.strategy===kw||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=Rw(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=tO(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(nO(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=Rw(e,0,e.window[e.strstart-1]),n&&nO(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=Rw(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===Aw?(nO(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nO(e,!1),0===e.strm.avail_out)?1:2};function uO(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}const pO=[new uO(0,0,0,0,dO),new uO(4,4,8,4,lO),new uO(4,5,16,8,lO),new uO(4,6,32,32,lO),new uO(4,4,16,16,hO),new uO(8,16,32,32,hO),new uO(8,16,128,128,hO),new uO(8,32,128,256,hO),new uO(32,128,258,1024,hO),new uO(32,258,258,4096,hO)];function _O(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Bw,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*Hw),this.dyn_dtree=new Uint16Array(2*(2*Gw+1)),this.bl_tree=new Uint16Array(2*(2*Ww+1)),$w(this.dyn_ltree),$w(this.dyn_dtree),$w(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(Kw+1),this.heap=new Uint16Array(2*jw+1),$w(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*jw+1),$w(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const EO=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==Jw&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==zw&&t.status!==Xw?1:0},mO=e=>{if(EO(e))return Qw(e,Nw);e.total_in=e.total_out=0,e.data_type=Fw;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?Jw:zw,e.adler=2===t.wrap?0:1,t.last_flush=-2,gw(t),ww},fO=e=>{const t=mO(e);var i;return t===ww&&((i=e.state).window_size=2*i.w_size,$w(i.head),i.max_lazy_match=pO[i.level].max_lazy,i.good_match=pO[i.level].good_length,i.nice_match=pO[i.level].nice_length,i.max_chain_length=pO[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t},gO=(e,t,i,n,r,s)=>{if(!e)return Nw;let o=1;if(t===Lw&&(t=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),r<1||r>9||i!==Bw||n<8||n>15||t<0||t>9||s<0||s>xw||8===n&&1!==o)return Qw(e,Nw);8===n&&(n=9);const a=new _O;return e.state=a,a.strm=e,a.status=Jw,a.wrap=o,a.gzhead=null,a.w_bits=n,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=r+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+3-1)/3),a.window=new Uint8Array(2*a.w_size),a.head=new Uint16Array(a.hash_size),a.prev=new Uint16Array(a.w_size),a.lit_bufsize=1<<r+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new Uint8Array(a.pending_buf_size),a.sym_buf=a.lit_bufsize,a.sym_end=3*(a.lit_bufsize-1),a.level=t,a.strategy=s,a.method=i,fO(e)};var SO=(e,t)=>{if(EO(e)||t>bw||t<0)return e?Qw(e,Nw):Nw;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===Xw&&t!==Aw)return Qw(e,0===e.avail_out?Pw:Nw);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(iO(e),0===e.avail_out)return i.last_flush=-1,ww}else if(0===e.avail_in&&Zw(t)<=Zw(n)&&t!==Aw)return Qw(e,Pw);if(i.status===Xw&&0!==e.avail_in)return Qw(e,Pw);if(i.status===Jw&&0===i.wrap&&(i.status=zw),i.status===Jw){let t=Bw+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=Mw||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,sO(i,t),0!==i.strstart&&(sO(i,e.adler>>>16),sO(i,65535&e.adler)),e.adler=1,i.status=zw,iO(e),0!==i.pending)return i.last_flush=-1,ww}if(57===i.status)if(e.adler=0,rO(i,31),rO(i,139),rO(i,8),i.gzhead)rO(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),rO(i,255&i.gzhead.time),rO(i,i.gzhead.time>>8&255),rO(i,i.gzhead.time>>16&255),rO(i,i.gzhead.time>>24&255),rO(i,9===i.level?2:i.strategy>=Mw||i.level<2?4:0),rO(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(rO(i,255&i.gzhead.extra.length),rO(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=Ew(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(rO(i,0),rO(i,0),rO(i,0),rO(i,0),rO(i,0),rO(i,9===i.level?2:i.strategy>=Mw||i.level<2?4:0),rO(i,3),i.status=zw,iO(e),0!==i.pending)return i.last_flush=-1,ww;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,iO(e),0!==i.pending)return i.last_flush=-1,ww;t=0,n-=r}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-n,n)),iO(e),0!==i.pending)return i.last_flush=-1,ww;n=0}t=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,rO(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-n,n)),iO(e),0!==i.pending)return i.last_flush=-1,ww;n=0}t=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,rO(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-n,n))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(iO(e),0!==i.pending))return i.last_flush=-1,ww;rO(i,255&e.adler),rO(i,e.adler>>8&255),e.adler=0}if(i.status=zw,iO(e),0!==i.pending)return i.last_flush=-1,ww}if(0!==e.avail_in||0!==i.lookahead||t!==vw&&i.status!==Xw){let n=0===i.level?dO(i,t):i.strategy===Mw?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(cO(e),0===e.lookahead)){if(t===vw)return 1;break}if(e.match_length=0,i=Rw(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(nO(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===Aw?(nO(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nO(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===Uw?((e,t)=>{let i,n,r,s;const o=e.window;for(;;){if(e.lookahead<=Yw){if(cO(e),e.lookahead<=Yw&&t===vw)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,n=o[r],n===o[++r]&&n===o[++r]&&n===o[++r])){s=e.strstart+Yw;do{}while(n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&r<s);e.match_length=Yw-(s-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=Rw(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=Rw(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(nO(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===Aw?(nO(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nO(e,!1),0===e.strm.avail_out)?1:2})(i,t):pO[i.level].func(i,t);if(3!==n&&4!==n||(i.status=Xw),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),ww;if(2===n&&(t===Iw?Cw(i):t!==bw&&(Sw(i,0,0,!1),t===yw&&($w(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),iO(e),0===e.avail_out))return i.last_flush=-1,ww}return t!==Aw?ww:i.wrap<=0?Ow:(2===i.wrap?(rO(i,255&e.adler),rO(i,e.adler>>8&255),rO(i,e.adler>>16&255),rO(i,e.adler>>24&255),rO(i,255&e.total_in),rO(i,e.total_in>>8&255),rO(i,e.total_in>>16&255),rO(i,e.total_in>>24&255)):(sO(i,e.adler>>>16),sO(i,65535&e.adler)),iO(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?ww:Ow)},TO=(e,t)=>{let i=t.length;if(EO(e))return Nw;const n=e.state,r=n.wrap;if(2===r||1===r&&n.status!==Jw||n.lookahead)return Nw;if(1===r&&(e.adler=pw(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===r&&($w(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size}const s=e.avail_in,o=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,cO(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=tO(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++}while(--t);n.strstart=e,n.lookahead=2,cO(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=o,e.input=a,e.avail_in=s,n.wrap=r,ww},RO={deflateInit:(e,t)=>gO(e,t,Bw,15,8,Vw),deflateInit2:gO,deflateReset:fO,deflateResetKeep:mO,deflateSetHeader:(e,t)=>EO(e)||2!==e.state.wrap?Nw:(e.state.gzhead=t,ww),deflate:SO,deflateEnd:e=>{if(EO(e))return Nw;const t=e.state.status;return e.state=null,t===zw?Qw(e,Dw):ww},deflateSetDictionary:TO,deflateInfo:"pako deflate (from Nodeca project)"};const CO=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var vO={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)CO(i,t)&&(e[t]=i[t])}}return e},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i<n;i++)t+=e[i].length;const i=new Uint8Array(t);for(let t=0,n=0,r=e.length;t<r;t++){let r=e[t];i.set(r,n),n+=r.length}return i}};let IO=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){IO=!1}const yO=new Uint8Array(256);for(let e=0;e<256;e++)yO[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;yO[254]=yO[254]=1;var AO={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,r,s,o=e.length,a=0;for(r=0;r<o;r++)i=e.charCodeAt(r),55296==(64512&i)&&r+1<o&&(n=e.charCodeAt(r+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),a+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Uint8Array(a),s=0,r=0;s<a;r++)i=e.charCodeAt(r),55296==(64512&i)&&r+1<o&&(n=e.charCodeAt(r+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[s++]=i:i<2048?(t[s++]=192|i>>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t},buf2string:(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let n,r;const s=new Array(2*i);for(r=0,n=0;n<i;){let t=e[n++];if(t<128){s[r++]=t;continue}let o=yO[t];if(o>4)s[r++]=65533,n+=o-1;else{for(t&=2===o?31:3===o?15:7;o>1&&n<i;)t=t<<6|63&e[n++],o--;o>1?s[r++]=65533:t<65536?s[r++]=t:(t-=65536,s[r++]=55296|t>>10&1023,s[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&IO)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let n=0;n<t;n++)i+=String.fromCharCode(e[n]);return i})(s,r)},utf8border:(e,t)=>{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+yO[e[i]]>t?i:t}},bO=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const wO=Object.prototype.toString,{Z_NO_FLUSH:OO,Z_SYNC_FLUSH:NO,Z_FULL_FLUSH:DO,Z_FINISH:PO,Z_OK:LO,Z_STREAM_END:kO,Z_DEFAULT_COMPRESSION:MO,Z_DEFAULT_STRATEGY:UO,Z_DEFLATED:xO}=fw;function VO(e){this.options=vO.assign({level:MO,method:xO,chunkSize:16384,windowBits:15,memLevel:8,strategy:UO},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new bO,this.strm.avail_out=0;let i=RO.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==LO)throw new Error(mw[i]);if(t.header&&RO.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?AO.string2buf(t.dictionary):"[object ArrayBuffer]"===wO.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=RO.deflateSetDictionary(this.strm,e),i!==LO)throw new Error(mw[i]);this._dict_set=!0}}function FO(e,t){const i=new VO(t);if(i.push(e,!0),i.err)throw i.msg||mw[i.err];return i.result}VO.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let r,s;if(this.ended)return!1;for(s=t===~~t?t:!0===t?PO:OO,"string"==typeof e?i.input=AO.string2buf(e):"[object ArrayBuffer]"===wO.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(s===NO||s===DO)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=RO.deflate(i,s),r===kO)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=RO.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===LO;if(0!==i.avail_out){if(s>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},VO.prototype.onData=function(e){this.chunks.push(e)},VO.prototype.onEnd=function(e){e===LO&&(this.result=vO.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var BO={Deflate:VO,deflate:FO,deflateRaw:function(e,t){return(t=t||{}).raw=!0,FO(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,FO(e,t)},constants:fw};const jO=16209;var GO=function(e,t){let i,n,r,s,o,a,c,d,l,h,u,p,_,E,m,f,g,S,T,R,C,v,I,y;const A=e.state;i=e.next_in,I=e.input,n=i+(e.avail_in-5),r=e.next_out,y=e.output,s=r-(t-e.avail_out),o=r+(e.avail_out-257),a=A.dmax,c=A.wsize,d=A.whave,l=A.wnext,h=A.window,u=A.hold,p=A.bits,_=A.lencode,E=A.distcode,m=(1<<A.lenbits)-1,f=(1<<A.distbits)-1;e:do{p<15&&(u+=I[i++]<<p,p+=8,u+=I[i++]<<p,p+=8),g=_[u&m];t:for(;;){if(S=g>>>24,u>>>=S,p-=S,S=g>>>16&255,0===S)y[r++]=65535&g;else{if(!(16&S)){if(0==(64&S)){g=_[(65535&g)+(u&(1<<S)-1)];continue t}if(32&S){A.mode=16191;break e}e.msg="invalid literal/length code",A.mode=jO;break e}T=65535&g,S&=15,S&&(p<S&&(u+=I[i++]<<p,p+=8),T+=u&(1<<S)-1,u>>>=S,p-=S),p<15&&(u+=I[i++]<<p,p+=8,u+=I[i++]<<p,p+=8),g=E[u&f];i:for(;;){if(S=g>>>24,u>>>=S,p-=S,S=g>>>16&255,!(16&S)){if(0==(64&S)){g=E[(65535&g)+(u&(1<<S)-1)];continue i}e.msg="invalid distance code",A.mode=jO;break e}if(R=65535&g,S&=15,p<S&&(u+=I[i++]<<p,p+=8,p<S&&(u+=I[i++]<<p,p+=8)),R+=u&(1<<S)-1,R>a){e.msg="invalid distance too far back",A.mode=jO;break e}if(u>>>=S,p-=S,S=r-s,R>S){if(S=R-S,S>d&&A.sane){e.msg="invalid distance too far back",A.mode=jO;break e}if(C=0,v=h,0===l){if(C+=c-S,S<T){T-=S;do{y[r++]=h[C++]}while(--S);C=r-R,v=y}}else if(l<S){if(C+=c+l-S,S-=l,S<T){T-=S;do{y[r++]=h[C++]}while(--S);if(C=0,l<T){S=l,T-=S;do{y[r++]=h[C++]}while(--S);C=r-R,v=y}}}else if(C+=l-S,S<T){T-=S;do{y[r++]=h[C++]}while(--S);C=r-R,v=y}for(;T>2;)y[r++]=v[C++],y[r++]=v[C++],y[r++]=v[C++],T-=3;T&&(y[r++]=v[C++],T>1&&(y[r++]=v[C++]))}else{C=r-R;do{y[r++]=y[C++],y[r++]=y[C++],y[r++]=y[C++],T-=3}while(T>2);T&&(y[r++]=y[C++],T>1&&(y[r++]=y[C++]))}break}}break}}while(i<n&&r<o);T=p>>3,i-=T,p-=T<<3,u&=(1<<p)-1,e.next_in=i,e.next_out=r,e.avail_in=i<n?n-i+5:5-(i-n),e.avail_out=r<o?o-r+257:257-(r-o),A.hold=u,A.bits=p};const WO=15,HO=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),KO=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),YO=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),qO=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var JO=(e,t,i,n,r,s,o,a)=>{const c=a.bits;let d,l,h,u,p,_,E=0,m=0,f=0,g=0,S=0,T=0,R=0,C=0,v=0,I=0,y=null;const A=new Uint16Array(16),b=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=WO;E++)A[E]=0;for(m=0;m<n;m++)A[t[i+m]]++;for(S=c,g=WO;g>=1&&0===A[g];g--);if(S>g&&(S=g),0===g)return r[s++]=20971520,r[s++]=20971520,a.bits=1,0;for(f=1;f<g&&0===A[f];f++);for(S<f&&(S=f),C=1,E=1;E<=WO;E++)if(C<<=1,C-=A[E],C<0)return-1;if(C>0&&(0===e||1!==g))return-1;for(b[1]=0,E=1;E<WO;E++)b[E+1]=b[E]+A[E];for(m=0;m<n;m++)0!==t[i+m]&&(o[b[t[i+m]]++]=m);if(0===e?(y=D=o,_=20):1===e?(y=HO,D=KO,_=257):(y=YO,D=qO,_=0),I=0,m=0,E=f,p=s,T=S,R=0,h=-1,v=1<<S,u=v-1,1===e&&v>852||2===e&&v>592)return 1;for(;;){w=E-R,o[m]+1<_?(O=0,N=o[m]):o[m]>=_?(O=D[o[m]-_],N=y[o[m]-_]):(O=96,N=0),d=1<<E-R,l=1<<T,f=l;do{l-=d,r[p+(I>>R)+l]=w<<24|O<<16|N|0}while(0!==l);for(d=1<<E-1;I&d;)d>>=1;if(0!==d?(I&=d-1,I+=d):I=0,m++,0==--A[E]){if(E===g)break;E=t[i+o[m]]}if(E>S&&(I&u)!==h){for(0===R&&(R=S),p+=f,T=E-R,C=1<<T;T+R<g&&(C-=A[T+R],!(C<=0));)T++,C<<=1;if(v+=1<<T,1===e&&v>852||2===e&&v>592)return 1;h=I&u,r[h]=S<<24|T<<16|p-s|0}}return 0!==I&&(r[p+I]=E-R<<24|64<<16|0),a.bits=S,0};const{Z_FINISH:zO,Z_BLOCK:XO,Z_TREES:QO,Z_OK:ZO,Z_STREAM_END:$O,Z_NEED_DICT:eN,Z_STREAM_ERROR:tN,Z_DATA_ERROR:iN,Z_MEM_ERROR:nN,Z_BUF_ERROR:rN,Z_DEFLATED:sN}=fw,oN=16180,aN=16190,cN=16191,dN=16192,lN=16194,hN=16199,uN=16200,pN=16206,_N=16209,EN=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function mN(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const fN=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<oN||t.mode>16211?1:0},gN=e=>{if(fN(e))return tN;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=oN,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,ZO},SN=e=>{if(fN(e))return tN;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,gN(e)},TN=(e,t)=>{let i;if(fN(e))return tN;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?tN:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,SN(e))},RN=(e,t)=>{if(!e)return tN;const i=new mN;e.state=i,i.strm=e,i.window=null,i.mode=oN;const n=TN(e,t);return n!==ZO&&(e.state=null),n};let CN,vN,IN=!0;const yN=e=>{if(IN){CN=new Int32Array(512),vN=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(JO(1,e.lens,0,288,CN,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;JO(2,e.lens,0,32,vN,0,e.work,{bits:5}),IN=!1}e.lencode=CN,e.lenbits=9,e.distcode=vN,e.distbits=5},AN=(e,t,i,n)=>{let r;const s=e.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),n>=s.wsize?(s.window.set(t.subarray(i-s.wsize,i),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>n&&(r=n),s.window.set(t.subarray(i-n,i-n+r),s.wnext),(n-=r)?(s.window.set(t.subarray(i-n,i),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=r))),0};var bN=(e,t)=>{let i,n,r,s,o,a,c,d,l,h,u,p,_,E,m,f,g,S,T,R,C,v,I=0;const y=new Uint8Array(4);let A,b;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(fN(e)||!e.output||!e.input&&0!==e.avail_in)return tN;i=e.state,i.mode===cN&&(i.mode=dN),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,h=a,u=c,v=ZO;e:for(;;)switch(i.mode){case oN:if(0===i.wrap){i.mode=dN;break}for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(2&i.wrap&&35615===d){0===i.wbits&&(i.wbits=15),i.check=0,y[0]=255&d,y[1]=d>>>8&255,i.check=Ew(i.check,y,2,0),d=0,l=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg="incorrect header check",i.mode=_N;break}if((15&d)!==sN){e.msg="unknown compression method",i.mode=_N;break}if(d>>>=4,l-=4,C=8+(15&d),0===i.wbits&&(i.wbits=C),C>15||C>i.wbits){e.msg="invalid window size",i.mode=_N;break}i.dmax=1<<i.wbits,i.flags=0,e.adler=i.check=1,i.mode=512&d?16189:cN,d=0,l=0;break;case 16181:for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(i.flags=d,(255&i.flags)!==sN){e.msg="unknown compression method",i.mode=_N;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=_N;break}i.head&&(i.head.text=d>>8&1),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=Ew(i.check,y,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.head&&(i.head.time=d),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,y[2]=d>>>16&255,y[3]=d>>>24&255,i.check=Ew(i.check,y,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.head&&(i.head.xflags=255&d,i.head.os=d>>8),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=Ew(i.check,y,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&i.flags){for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.length=d,i.head&&(i.head.extra_len=d),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=Ew(i.check,y,2,0)),d=0,l=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(p=i.length,p>a&&(p=a),p&&(i.head&&(C=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(s,s+p),C)),512&i.flags&&4&i.wrap&&(i.check=Ew(i.check,n,p,s)),a-=p,s+=p,i.length-=p),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;p=0;do{C=n[s+p++],i.head&&C&&i.length<65536&&(i.head.name+=String.fromCharCode(C))}while(C&&p<a);if(512&i.flags&&4&i.wrap&&(i.check=Ew(i.check,n,p,s)),a-=p,s+=p,C)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=16187;case 16187:if(4096&i.flags){if(0===a)break e;p=0;do{C=n[s+p++],i.head&&C&&i.length<65536&&(i.head.comment+=String.fromCharCode(C))}while(C&&p<a);if(512&i.flags&&4&i.wrap&&(i.check=Ew(i.check,n,p,s)),a-=p,s+=p,C)break e}else i.head&&(i.head.comment=null);i.mode=16188;case 16188:if(512&i.flags){for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(4&i.wrap&&d!==(65535&i.check)){e.msg="header crc mismatch",i.mode=_N;break}d=0,l=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=cN;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}e.adler=i.check=EN(d),d=0,l=0,i.mode=aN;case aN:if(0===i.havedict)return e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,eN;e.adler=i.check=1,i.mode=cN;case cN:if(t===XO||t===QO)break e;case dN:if(i.last){d>>>=7&l,l-=7&l,i.mode=pN;break}for(;l<3;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}switch(i.last=1&d,d>>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(yN(i),i.mode=hN,t===QO){d>>>=2,l-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=_N}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if((65535&d)!=(d>>>16^65535)){e.msg="invalid stored block lengths",i.mode=_N;break}if(i.length=65535&d,d=0,l=0,i.mode=lN,t===QO)break e;case lN:i.mode=16195;case 16195:if(p=i.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(n.subarray(s,s+p),o),a-=p,s+=p,c-=p,o+=p,i.length-=p;break}i.mode=cN;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(i.nlen=257+(31&d),d>>>=5,l-=5,i.ndist=1+(31&d),d>>>=5,l-=5,i.ncode=4+(15&d),d>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=_N;break}i.have=0,i.mode=16197;case 16197:for(;i.have<i.ncode;){for(;l<3;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.lens[w[i.have++]]=7&d,d>>>=3,l-=3}for(;i.have<19;)i.lens[w[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,A={bits:i.lenbits},v=JO(0,i.lens,0,19,i.lencode,0,i.work,A),i.lenbits=A.bits,v){e.msg="invalid code lengths set",i.mode=_N;break}i.have=0,i.mode=16198;case 16198:for(;i.have<i.nlen+i.ndist;){for(;I=i.lencode[d&(1<<i.lenbits)-1],m=I>>>24,f=I>>>16&255,g=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(g<16)d>>>=m,l-=m,i.lens[i.have++]=g;else{if(16===g){for(b=m+2;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(d>>>=m,l-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=_N;break}C=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2}else if(17===g){for(b=m+3;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}d>>>=m,l-=m,C=0,p=3+(7&d),d>>>=3,l-=3}else{for(b=m+7;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}d>>>=m,l-=m,C=0,p=11+(127&d),d>>>=7,l-=7}if(i.have+p>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=_N;break}for(;p--;)i.lens[i.have++]=C}}if(i.mode===_N)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=_N;break}if(i.lenbits=9,A={bits:i.lenbits},v=JO(1,i.lens,0,i.nlen,i.lencode,0,i.work,A),i.lenbits=A.bits,v){e.msg="invalid literal/lengths set",i.mode=_N;break}if(i.distbits=6,i.distcode=i.distdyn,A={bits:i.distbits},v=JO(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,A),i.distbits=A.bits,v){e.msg="invalid distances set",i.mode=_N;break}if(i.mode=hN,t===QO)break e;case hN:i.mode=uN;case uN:if(a>=6&&c>=258){e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,GO(e,u),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,i.mode===cN&&(i.back=-1);break}for(i.back=0;I=i.lencode[d&(1<<i.lenbits)-1],m=I>>>24,f=I>>>16&255,g=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(f&&0==(240&f)){for(S=m,T=f,R=g;I=i.lencode[R+((d&(1<<S+T)-1)>>S)],m=I>>>24,f=I>>>16&255,g=65535&I,!(S+m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}d>>>=S,l-=S,i.back+=S}if(d>>>=m,l-=m,i.back+=m,i.length=g,0===f){i.mode=16205;break}if(32&f){i.back=-1,i.mode=cN;break}if(64&f){e.msg="invalid literal/length code",i.mode=_N;break}i.extra=15&f,i.mode=16201;case 16201:if(i.extra){for(b=i.extra;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.length+=d&(1<<i.extra)-1,d>>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;I=i.distcode[d&(1<<i.distbits)-1],m=I>>>24,f=I>>>16&255,g=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(0==(240&f)){for(S=m,T=f,R=g;I=i.distcode[R+((d&(1<<S+T)-1)>>S)],m=I>>>24,f=I>>>16&255,g=65535&I,!(S+m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}d>>>=S,l-=S,i.back+=S}if(d>>>=m,l-=m,i.back+=m,64&f){e.msg="invalid distance code",i.mode=_N;break}i.offset=g,i.extra=15&f,i.mode=16203;case 16203:if(i.extra){for(b=i.extra;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.offset+=d&(1<<i.extra)-1,d>>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=_N;break}i.mode=16204;case 16204:if(0===c)break e;if(p=u-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=_N;break}p>i.wnext?(p-=i.wnext,_=i.wsize-p):_=i.wnext-p,p>i.length&&(p=i.length),E=i.window}else E=r,_=o-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do{r[o++]=E[_++]}while(--p);0===i.length&&(i.mode=uN);break;case 16205:if(0===c)break e;r[o++]=i.length,c--,i.mode=uN;break;case pN:if(i.wrap){for(;l<32;){if(0===a)break e;a--,d|=n[s++]<<l,l+=8}if(u-=c,e.total_out+=u,i.total+=u,4&i.wrap&&u&&(e.adler=i.check=i.flags?Ew(i.check,r,u,o-u):pw(i.check,r,u,o-u)),u=c,4&i.wrap&&(i.flags?d:EN(d))!==i.check){e.msg="incorrect data check",i.mode=_N;break}d=0,l=0}i.mode=16207;case 16207:if(i.wrap&&i.flags){for(;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(4&i.wrap&&d!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=_N;break}d=0,l=0}i.mode=16208;case 16208:v=$O;break e;case _N:v=iN;break e;case 16210:return nN;default:return tN}return e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,(i.wsize||u!==e.avail_out&&i.mode<_N&&(i.mode<pN||t!==zO))&&AN(e,e.output,e.next_out,u-e.avail_out),h-=e.avail_in,u-=e.avail_out,e.total_in+=h,e.total_out+=u,i.total+=u,4&i.wrap&&u&&(e.adler=i.check=i.flags?Ew(i.check,r,u,e.next_out-u):pw(i.check,r,u,e.next_out-u)),e.data_type=i.bits+(i.last?64:0)+(i.mode===cN?128:0)+(i.mode===hN||i.mode===lN?256:0),(0===h&&0===u||t===zO)&&v===ZO&&(v=rN),v},wN={inflateReset:SN,inflateReset2:TN,inflateResetKeep:gN,inflateInit:e=>RN(e,15),inflateInit2:RN,inflate:bN,inflateEnd:e=>{if(fN(e))return tN;let t=e.state;return t.window&&(t.window=null),e.state=null,ZO},inflateGetHeader:(e,t)=>{if(fN(e))return tN;const i=e.state;return 0==(2&i.wrap)?tN:(i.head=t,t.done=!1,ZO)},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,s;return fN(e)?tN:(n=e.state,0!==n.wrap&&n.mode!==aN?tN:n.mode===aN&&(r=1,r=pw(r,t,i,0),r!==n.check)?iN:(s=AN(e,t,i,i),s?(n.mode=16210,nN):(n.havedict=1,ZO)))},inflateInfo:"pako inflate (from Nodeca project)"},ON=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const NN=Object.prototype.toString,{Z_NO_FLUSH:DN,Z_FINISH:PN,Z_OK:LN,Z_STREAM_END:kN,Z_NEED_DICT:MN,Z_STREAM_ERROR:UN,Z_DATA_ERROR:xN,Z_MEM_ERROR:VN}=fw;function FN(e){this.options=vO.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new bO,this.strm.avail_out=0;let i=wN.inflateInit2(this.strm,t.windowBits);if(i!==LN)throw new Error(mw[i]);if(this.header=new ON,wN.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=AO.string2buf(t.dictionary):"[object ArrayBuffer]"===NN.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=wN.inflateSetDictionary(this.strm,t.dictionary),i!==LN)))throw new Error(mw[i])}function BN(e,t){const i=new FN(t);if(i.push(e),i.err)throw i.msg||mw[i.err];return i.result}FN.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let s,o,a;if(this.ended)return!1;for(o=t===~~t?t:!0===t?PN:DN,"[object ArrayBuffer]"===NN.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),s=wN.inflate(i,o),s===MN&&r&&(s=wN.inflateSetDictionary(i,r),s===LN?s=wN.inflate(i,o):s===xN&&(s=MN));i.avail_in>0&&s===kN&&i.state.wrap>0&&0!==e[i.next_in];)wN.inflateReset(i),s=wN.inflate(i,o);switch(s){case UN:case xN:case MN:case VN:return this.onEnd(s),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||s===kN))if("string"===this.options.to){let e=AO.utf8border(i.output,i.next_out),t=i.next_out-e,r=AO.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(s!==LN||0!==a){if(s===kN)return s=wN.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},FN.prototype.onData=function(e){this.chunks.push(e)},FN.prototype.onEnd=function(e){e===LN&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=vO.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var jN={Inflate:FN,inflate:BN,inflateRaw:function(e,t){return(t=t||{}).raw=!0,BN(e,t)},ungzip:BN,constants:fw};const{Deflate:GN,deflate:WN,deflateRaw:HN,gzip:KN}=BO,{Inflate:YN,inflate:qN,inflateRaw:JN,ungzip:zN}=jN;var XN,QN=WN,ZN=qN;!function(e){e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE"}(XN||(XN={}));class $N{constructor(){nu(this,"_sequence",0),nu(this,"_startTime",Date.now()),nu(this,"isUseOneByte",!0)}get startTime(){const e=Date.now()-this._startTime;return e<Math.pow(2,16)?e:(this._startTime+=Math.pow(2,16),this.startTime)}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence)}serialize(e){const t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){const i=new Uint8Array(4);i.set([1,0,0,0]);const n={id:0,length:4,data:i.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[n]};t.commonPacketHeader.extension=1,t.extension=r,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;const i=new ArrayBuffer(t.commonPacketHeader.length),n=new Uint8Array(i),r=new DataView(i);let s=0;if(r.setUint16(s,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),s+=2,r.setUint32(s,t.commonPacketHeader.sequence,!0),s+=4,r.setUint16(s,t.commonStreamHeader,!0),s+=2,t.extension){const e=this.serializeExtension(t.extension);n.set(new Uint8Array(e),s),s+=e.byteLength}if(n.set(new Uint8Array(t.payload),s),s+=t.payload.byteLength,s!==t.commonPacketHeader.length)throw Error("serialize error!");return i}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let i=0;const n=t.getUint16(i,!0);i+=2;const r=(32768&n)>>15;let s,o;if(t.getUint16(i+2,!0),t.getUint16(i,!0),i+=4,t.getUint16(i,!0),i+=2,r){o=this.deserializeExtension(e.slice(i)),i+=2+o.length,s=e.slice(i);let t=!1;if(o.datas.length>0){const e=o.datas.find((e=>0===e.id));e&&(t=1==(1&new DataView(e.data).getUint32(0,!0)))}s=t?this.decompress(s):s}else s=e.slice(8);return s}serializeExtension(e){const{profile:t,length:i,datas:n}=e,r=new ArrayBuffer(i+2),s=new Uint8Array(r),o=new DataView(r);let a=0;if(o.setUint8(a++,t),o.setUint8(a++,i),n.forEach((e=>{t?(o.setUint8(a++,e.id),o.setUint8(a++,e.length),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(o.setUint8(a++,e.id|e.length<<4),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength)})),a!==i+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(i+2));return r}deserializeExtension(e){const t=new DataView(e);let i=0;const n=t.getUint8(i);i++;const r=t.getUint8(i);i++;const s=n===XN.TWO_BYTE,o=[],a=new DataView(e,2);let c=0;for(;c<r;){let e=0,t=0,i=new ArrayBuffer(0);s?(e=a.getUint8(c),c++,t=a.getUint8(c),c++):(e=15&a.getUint8(c),t=a.getUint8(c)>>4,c++),t>0&&(i=a.buffer.slice(c+2,c+2+t),c+=i.byteLength),o.push({id:e,length:t,data:i})}if(c!==r)throw Error("parse error");return{profile:n,length:r,datas:o}}decompress(e){return ZN(new Uint8Array(e))}compress(e){return QN(new Uint8Array(e))}}class eD extends iS{constructor(e,t){super(),nu(this,"_version",1),nu(this,"_type",3),nu(this,"_config",void 0),nu(this,"_originDataChannel",void 0),nu(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),nu(this,"_dataStreamPacketHandler",void 0),nu(this,"_datachannelEventMap",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader(),this._dataStreamPacketHandler=new $N}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return kC("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting"}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new tg(((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;t(new Vg(xg.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new Vg(xg.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new Vg(xg.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[Qy.OPEN,Qy.CLOSE,Qy.ERROR].forEach((t=>{const i=()=>{this.emit(t)};this._datachannelEventMap.set(t,i),e.addEventListener(t,i)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[i,n]=t;e.removeEventListener(i,n)})),this._datachannelEventMap.clear()}}class tD extends eD{constructor(e){super(e),nu(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const t=e.data.slice(0,this._dataStreamPacketHeader.byteLength);if(new DataView(t).getUint8(3)!==this.id)return;let i=e.data.slice(this._dataStreamPacketHeader.byteLength);i=this._dataStreamPacketHandler.deserialize(i),this.emit(Qy.MESSAGE,i)}}_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents()}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close())}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener)}}class iD extends eD{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const i=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);i.set(new Uint8Array(this._dataStreamPacketHeader),0),i.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(i.buffer)}}}class nD extends iS{constructor(){super(...arguments),nu(this,"resultStorage",new Map)}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i))}setRemoteAudioStats(e,t){const i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const i=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",i,this.checkVideoDecode(t))}record(e,t,i){if(kC("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(n&&(n.result.push(i),n.result.length>=5)){var r;const i=Lr(r=n.result).call(r,!0);n.isPrevNormal&&!i&&this.emit("exception",rD[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",rD[e]+2e3,e+"_RECOVER",t),n.isPrevNormal=i,n.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof ZA&&!t.isActive||!!t.muted||0!==e.sendVolumeLevel}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=pD(t._encoderConfig.frameRate));const n=e.captureFrameRate;return!i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof ZA&&!t.isActive||!!t.muted||0!==e.sendBitrate}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const rD={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003},sD=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t))}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t))}measureFromSubscribeStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function oD(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function aD(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?oD(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):oD(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class cD{constructor(e){nu(this,"store",void 0),nu(this,"onStatsException",void 0),nu(this,"onUploadPublishDuration",void 0),nu(this,"onStatsChanged",void 0),nu(this,"localStats",new Map),nu(this,"remoteStats",new Map),nu(this,"updateStatsInterval",void 0),nu(this,"trafficStats",void 0),nu(this,"trafficStatsPeerList",[]),nu(this,"uplinkStats",void 0),nu(this,"exceptionMonitor",void 0),nu(this,"p2pChannel",void 0),nu(this,"scalabilityMode",cv.L1T1),nu(this,"updateStats",(()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.updateStatsInterval=window.setInterval(this.updateStats,1e3),this.exceptionMonitor=new nD,this.exceptionMonitor.on("exception",((e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i)}))}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(uI.LocalAudioTrack)||aD({},By)}getLocalVideoTrackStats(){return this.localStats.get(uI.LocalVideoTrack)||aD({},jy)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{audioStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n)}else Array.from(this.remoteStats.entries()).forEach((e=>{let[i,{networkStats:n}]=e;n&&(t[i]=n)}));return t}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{videoStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRTCStats(){let e=0,t=0,i=0,n=0;const r=this.localStats.get(uI.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const s=this.localStats.get(uI.LocalVideoTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate);const o=this.localStats.get(uI.LocalVideoLowTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate),this.remoteStats.forEach((e=>{let{audioStats:t,videoStats:r}=e;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),r&&(i+=r.receiveBytes,n+=r.receiveBitrate)}));let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd)),e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?sD.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?sD.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,n>r?n:r),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&WC.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,i){if(!e)return!1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,r=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!r}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let[i,n]=t;switch(i){case uI.LocalVideoTrack:case uI.LocalVideoLowTrack:{const t=n,s=aD({},jy),o=e.getStats(),a=e.getLocalMedia(i);if(o){const i=o.videoSend.find((e=>e.ssrc===(null==a?void 0:a.ssrcs[0].ssrcId)));if(i){const n=e.getLocalVideoSize(),r=e.getEncoderConfig(uI.LocalVideoTrack);"H264"!==i.codec&&"H265"!==i.codec&&"VP8"!==i.codec&&"VP9"!==i.codec&&"AV1X"!==i.codec&&"AV1"!==i.codec||(s.codecType=i.codec),s.sendBytes=i.bytes,s.sendBitrate=t?8*Math.max(0,s.sendBytes-t.sendBytes):0,i.inputFrame?(s.captureFrameRate=i.inputFrame.frameRate,s.captureResolutionHeight=i.inputFrame.height,s.captureResolutionWidth=i.inputFrame.width):n&&(s.captureResolutionWidth=n.width,s.captureResolutionHeight=n.height),i.sentFrame?(s.sendFrameRate=i.sentFrame.frameRate,s.sendResolutionHeight=i.sentFrame.height,s.sendResolutionWidth=i.sentFrame.width):n&&(s.sendResolutionWidth=n.width,s.sendResolutionHeight=n.height),i.avgEncodeMs&&(s.encodeDelay=i.avgEncodeMs),r&&r.bitrateMax&&(s.targetSendBitrate=1e3*r.bitrateMax),s.sendPackets=i.packets,s.sendPacketsLost=i.packetsLost,s.sendJitterMs=i.jitterMs,s.sendRttMs=i.rttMs,s.totalDuration=t?t.totalDuration+1:1,s.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(s.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(WC.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(s.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var r;this.localStats.set(i,s),((null==t?void 0:t.sendResolutionWidth)!==s.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==s.sendResolutionHeight)&&(null===(r=this.onStatsChanged)||void 0===r||r.call(this,"resolution",{width:s.sendResolutionWidth,height:s.sendResolutionHeight})),s&&a&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,a.track,s);break}case uI.LocalAudioTrack:{const t=n,r=aD({},By),s=e.getStats(),o=e.getLocalMedia(i);if(s){const i=s.audioSend.find((e=>e.ssrc===(null==o?void 0:o.ssrcs[0].ssrcId)));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(r.codecType=i.codec),i.inputLevel)r.sendVolumeLevel=Math.round(32767*i.inputLevel);else{const t=e.getLocalAudioVolume();t&&(r.sendVolumeLevel=Math.round(32767*t))}r.sendBytes=i.bytes,r.sendPackets=i.packets,r.sendPacketsLost=i.packetsLost,r.sendJitterMs=i.jitterMs,r.sendRttMs=i.rttMs,r.sendBitrate=t?8*Math.max(0,r.sendBytes-t.sendBytes):0}}this.trafficStats&&(r.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(uI.LocalAudioTrack,r),r&&o&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,o.track,r);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{let[i,{videoStats:n,audioStats:r,videoPcStats:s}]=t;const o=r,a=n,c=s,d=aD({},Gy),l=aD({},Hy),h=aD({},Wy),{audioTrack:u,videoTrack:p,audioSSRC:_,videoSSRC:E}=e.getRemoteMedia(i),m=e.getStats(),f=null==m?void 0:m.audioRecv.find((e=>e.ssrc===_)),g=null==m?void 0:m.videoRecv.find((e=>e.ssrc===E)),S=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===i));if(f&&("opus"!==f.codec&&"aac"!==f.codec&&"PCMU"!==f.codec&&"PCMA"!==f.codec&&"G722"!==f.codec||(d.codecType=f.codec),f.outputLevel?d.receiveLevel=Math.round(32767*f.outputLevel):u&&(d.receiveLevel=Math.round(32767*u.getVolumeLevel())),d.receiveBytes=f.bytes,d.receivePackets=f.packets,d.receivePacketsLost=f.packetsLost,d.packetLossRate=d.receivePacketsLost/(d.receivePackets+d.receivePacketsLost),d.receiveBitrate=o?8*Math.max(0,d.receiveBytes-o.receiveBytes):0,d.totalDuration=o?o.totalDuration+1:1,d.totalFreezeTime=o?o.totalFreezeTime:0,d.freezeRate=d.totalFreezeTime/d.totalDuration,d.receiveDelay=f.jitterBufferMs,d.totalDuration>10&&cD.isRemoteAudioFreeze(u)&&(d.totalFreezeTime+=1)),g){"H264"!==g.codec&&"H265"!==g.codec&&"VP8"!==g.codec&&"VP9"!==g.codec&&"AV1X"!==g.codec&&"AV1"!==g.codec||(l.codecType=g.codec),l.receiveBytes=g.bytes,l.receiveBitrate=a?8*Math.max(0,l.receiveBytes-a.receiveBytes):0,l.decodeFrameRate=g.decodeFrameRate<0?0:g.decodeFrameRate,l.renderFrameRate=g.decodeFrameRate<0?0:g.decodeFrameRate,g.outputFrame&&(l.renderFrameRate=g.outputFrame.frameRate),g.receivedFrame?(l.receiveFrameRate=g.receivedFrame.frameRate,l.receiveResolutionHeight=g.receivedFrame.height,l.receiveResolutionWidth=g.receivedFrame.width):p&&(l.receiveResolutionHeight=p._videoHeight||0,l.receiveResolutionWidth=p._videoWidth||0),void 0!==g.framesRateFirefox&&(l.receiveFrameRate=Math.round(g.framesRateFirefox)),l.receivePackets=g.packets,l.receivePacketsLost=g.packetsLost,l.packetLossRate=l.receivePacketsLost/(l.receivePackets+l.receivePacketsLost),l.totalDuration=a?a.totalDuration+1:1,l.totalFreezeTime=a?a.totalFreezeTime:0,l.receiveDelay=g.jitterBufferMs||0;const t=!!E&&e.getRemoteVideoIsReady(E);p&&t&&cD.isRemoteVideoFreeze(p,g,c)&&(l.totalFreezeTime+=1),l.freezeRate=l.totalFreezeTime/l.totalDuration}S&&(d.end2EndDelay=S.B_ad,l.end2EndDelay=S.B_vd,d.transportDelay=S.B_ed,l.transportDelay=S.B_ed,d.currentPacketLossRate=S.B_ealr4/100,l.currentPacketLossRate=S.B_evlr4/100,h.uplinkNetworkQuality=S.B_punq?S.B_punq:0,h.downlinkNetworkQuality=S.B_pdnq?S.B_pdnq:0),this.remoteStats.set(i,{audioStats:d,videoStats:l,videoPcStats:g,networkStats:h}),u&&this.exceptionMonitor.setRemoteAudioStats(u,d),p&&this.exceptionMonitor.setRemoteVideoStats(p,l)}))}}function dD(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function lD(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?dD(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):dD(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function hD(e){return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(kC("TURN_DOMAIN")):(WC.info("Cannot recognized as IP address ".concat(e,". Used As Host instead")),e)}function uD(e,t){var i,n;const r=kC("GATEWAY_DOMAINS");let s=r[1]&&-1!==t.indexOf(r[1])?1:0;e.addresses=e.addresses||[];const o=e.addresses.map((e=>e.domain_prefix?{address:"".concat(e.domain_prefix,".").concat(r[s++%r.length],":").concat(e.port)}:e.ip.match(/^[\.\:\d]+$/)?{ip:e.ip,port:e.port,address:"".concat(e.ip.replace(/[^\d]/g,"-"),".").concat(r[s++%r.length],":").concat(e.port)}:(WC.info("Cannot recognized as IP address ".concat(e.ip,". Used As Host instead")),{ip:e.ip,port:e.port,address:"".concat(e.ip,":").concat(e.port)})));if(null!==(i=e.detail)&&void 0!==i&&i[18]&&"string"==typeof(null===(n=e.detail)||void 0===n?void 0:n[18])){const t=e.detail[18],i=null==t?void 0:t.split(";");for(let e=0;e<i.length;e++){var a;const t=Ey(a=i[e]).call(a);o[e]&&t&&(o[e].ip6=t)}}return{gatewayAddrs:o,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]}}function pD(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function _D(e){const t=e._encoderConfig;if(!t)return{};const i={resolution:t.width&&t.height?"".concat(pD(t.width),"x").concat(pD(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return"number"==typeof t.frameRate?(i.maxFrameRate=t.frameRate,i.minFrameRate=t.frameRate):t.frameRate&&(i.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,i.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),i}function ED(e){const t={connectionType:0,googRtt:e.rtt};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t.connectionType=1),"tcp"===i&&(t.connectionType=3),"tls"===i&&(t.connectionType=4);break}case"srflx":t.connectionType=2}return t}function mD(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function fD(e,t){let i,n,r;switch(t){case dy.CHOOSE_SERVER:n=4096,r="choose server";break;case dy.CLOUD_PROXY:n=1048576,r="proxy";break;case dy.CLOUD_PROXY_5:n=4194304,r="proxy5";break;case dy.CLOUD_PROXY_FALLBACK:n=4194310,r="proxy fallback";break;default:throw new Mv(xg.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach((t=>{t.buffer&&t.buffer.flag===n&&(i={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map((e=>lD(lD({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:lD(lD({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})})),!i)throw new Mv(xg.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i}async function gD(e,t){return await tg.all(e.addresses.map((async e=>({address:hD(e.ip),tcpport:e.port,udpport:e.port,username:t&&kC("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():rv.username,password:t&&kC("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await tS(t.toString()):rv.password}))))}function SD(e,t){const i=t._videoHeight||t.getMediaStreamTrack(!0).getSettings().height;return i?Math.max(i/pD(e.height),1):(WC.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function TD(e){let{candidateType:t,relayProtocol:i,type:n,address:r,port:s,protocol:o}=e;return"local-candidate"===n?{candidateType:t,relayProtocol:i,protocol:o}:{candidateType:t,relayProtocol:i,address:r,port:s,protocol:o}}function RD(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class CD extends iS{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Lr(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(TI.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(TI.CONNECTED):"closed"===this._state?this.emit(TI.CLOSED):"failed"===this._state&&this.emit(TI.FAILED))}constructor(e,t,i,n){super(),nu(this,"connectionID",0),nu(this,"currentURLIndex",0),nu(this,"reconnectReason",void 0),nu(this,"_reconnectMode","tryNext"),nu(this,"_name",void 0),nu(this,"_state","closed"),nu(this,"_retryConfig",void 0),nu(this,"_reconnectCount",0),nu(this,"_forceCloseTimeout",5e3),nu(this,"_onlineReconnectListener",void 0),nu(this,"_closeEstablishingTransmitter",(()=>{})),nu(this,"_store",void 0),nu(this,"_joinChannelServiceRecordIndex",void 0),nu(this,"_useCompress",void 0),nu(this,"_inflateLength",0),nu(this,"_deflateLength",0),this._store=n,this._name=e,this._retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?RD(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):RD(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t),this._useCompress=i}resetReconnectCount(e){WC.debug("".concat(this._name," reset reconnect count, reason: ").concat(e)),this._reconnectCount=0}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const e=this._transmitter;t?setTimeout((()=>e.close()),500):e.close(),this._transmitter=void 0}this.state=e?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(e,t){if(!this._transmitter)return void WC.warning("[".concat(this._name,"] can not reconnect, no websocket"));var i;void 0!==e&&(this.reconnectMode=e),WC.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex&&(null===(i=this._store)||void 0===i||i.recordJoinChannelService({status:"error",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const n=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),n&&n.bind(this._transmitter)({code:9999,reason:t})}getInflateData(){const e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t}}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}var vD;!function(e){e[e.Default=0]="Default",e[e.Ack=1]="Ack"}(vD||(vD={}));class ID{constructor(e,t,i){nu(this,"version",1),nu(this,"initialRTO",void 0),nu(this,"maxBatchAckCount",void 0),nu(this,"maxRTO",void 0),nu(this,"initialRTT",void 0),nu(this,"ID",void 0),nu(this,"rtt",void 0),nu(this,"packetNumber",1),nu(this,"rtoRatioMap",new Map),nu(this,"timeoutMap",new Map),nu(this,"unorderedPacketQueue",[]),nu(this,"batchAckPacketQueue",[]),nu(this,"lastOrderedPacketNumber",0),nu(this,"batchAckTimer",void 0),nu(this,"sendImpl",void 0),nu(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=xS(7,"transmitter-"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:kC("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:kC("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:kC("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:kC("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:kC("TRANSMITTER_MAX_RTO")}packetize(e,t){return{type:vD.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case vD.Default:{let t;t="string"==typeof e.payload?(new TextEncoder).encode(e.payload):e.payload;const i=new ArrayBuffer(t.length+15),n=new DataView(i);return n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.packetNumber),Jg(n,7,BigInt(e.sendTs)),new Uint8Array(n.buffer).set(t,15),i}case vD.Ack:{const t=new ArrayBuffer(16),i=new DataView(t);return i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.maxAckPacketNumber),i.setUint8(7,e.shift),Jg(i,8,BigInt(e.ackSendTs)),t}}}deserialize(e){const t=new DataView(e),i=t.getUint16(0),n=t.getUint8(2);switch(n){case vD.Default:{const r=t.getUint32(3),s=qg(t,7),o=e.slice(15),a=(new TextDecoder).decode(o);return{version:i,type:n,packetNumber:r,sendTs:Number(s),payload:a}}case vD.Ack:{const e=t.getUint32(3),r=t.getUint8(7),s=qg(t,8);return{version:i,type:n,maxAckPacketNumber:e,shift:r,ackSendTs:Number(s)}}default:throw WC.error("[".concat(this.ID,"] Unrecognized packet type ").concat(n)),new Error("Unrecognized packet type ".concat(n))}}sendMessage(e){const t=this.packetize(e,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const i=this.calculateRTO(t),n=window.setTimeout((()=>{this.resendMessage(t)}),i);this.timeoutMap.set(t.packetNumber,n),this.sendPacket(t)}onData(e){const t=this.deserialize(e);t.type===vD.Default?this.ack(t):t.type===vD.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach((e=>{let[t,i]=e;window.clearTimeout(i)})),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer)}resendMessage(e){const t=this.calculateRTO(e),i=window.setTimeout((()=>{this.resendMessage(e)}),t);this.timeoutMap.set(e.packetNumber,i),this.sendPacket(e)}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const i=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),i>this.maxRTO?this.maxRTO:i}}updateRTT(e,t){const i=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-i-this.rtt)/8}ack(e){if(e.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(e):(this.batchAckPacketQueue.push(e),this.batchAckTimer=window.setTimeout((()=>{this.batchAck()}),this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(e.payload);;){const e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(e.packetNumber<=this.lastOrderedPacketNumber){const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:vD.Ack,version:this.version};this.sendPacket(t)}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:vD.Ack,version:this.version};this.sendPacket(t)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:vD.Ack,version:this.version};this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===vD.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t)}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t)}}}class yD extends CD{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),nu(this,"_initMutex",void 0),nu(this,"_reconnectInterrupter",void 0),nu(this,"_url",void 0),nu(this,"_transmitter",void 0),nu(this,"_addresses",void 0),nu(this,"_reliableTransmission",void 0),this._initMutex=new YS("datachannel");const{timeout:i,timeoutFactor:n}=t,r=Math.max(300,Math.floor(3*i/5)),s=Math.max(1.2,Math.floor(8*n)/10);hS.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=s),RS.on(uS.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===hS.ONLINE?(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=s):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=n))}))}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;const i=(t,i)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex((e=>e.fingerprint||kC("FINGERPRINT")));const n=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(n).then(t).catch(i),this.once(TI.CLOSED,(()=>i(new Mv(xg.WS_DISCONNECT)))),this.once(TI.CONNECTED,(()=>t()))};return this._initMutex.lock().then((e=>new tg(((e,t)=>{i(e,t)})).then((()=>{e()})).catch((()=>{e()}))))}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new Mv(xg.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e)),this._reliableTransmission.sendMessage(e)}catch(e){throw new Mv(xg.WS_ERR,"send datachannel signal message error"+e.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(e){const t=JSON.stringify(e);return{compressed:t,compressedLength:t.length,origin:e}}sendMessageWithUint8Array(e){return{compressed:e,compressedLength:e.byteLength,origin:e}}createTransmitterConnection(e){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(e.ip,":").concat(e.port),new tg(((t,i)=>{var n;const r=()=>{WC.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),t()},s=async e=>{var n;if(null===(n=this._closeEstablishingTransmitter)||void 0===n||n.call(this),WC.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const n=SS(this,TI.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(n);if("closed"===this.state)return void WC.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!r)return i(new Mv(xg.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else i(new Mv(xg.WS_DISCONNECT,"datachannel close: ".concat(e.code))),this.close()},o=e=>{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data)};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),WC.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));const a=null===(n=this._store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();fS(this,TI.TO_CONNECT_DATACHANNEL,e).then((e=>{var t,i;if(!e)throw new Error("transmissonInfo not exist yet");const{transmitter:n,close:d}=e;this._transmitter=n,null===(t=this._store)||void 0===t||t.signalChannelOpen();const l=Date.now()-c;WC.debug("[choose dc] dc open cost ".concat(l,"ms")),this._reliableTransmission=new ID((e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e))}),(e=>{"string"==typeof e&&this.emit(TI.ON_MESSAGE,e)})),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d()},r&&r(),n.onclose=s,n.onmessage=o,null===(i=this._store)||void 0===i||i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this._joinChannelServiceRecordIndex=a})).catch((e=>{var t;if(null===(t=this._store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof Mv&&e.code===xg.WS_ABORT?"aborted":"error",errors:[e]},a),"closed"!==this.state){if(e instanceof Mv&&e.code===xg.WS_ERR){const t=new Mv(xg.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return WC.error("[".concat(this._name,"]").concat(t)),void i(t)}s&&s(e)}else i(new Mv(xg.WS_DISCONNECT,"datachannel is closed: ".concat(e.toString())))}))}))}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount)return!1;if(!this._addresses)return!1;if("closed"===this.state)return!1;this._onlineReconnectListener||RS.networkState!==hS.OFFLINE||(this._onlineReconnectListener=RS.onlineWaiter&&RS.onlineWaiter.then((()=>{this._onlineReconnectListener=void 0})));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},t){const t=zS(this._reconnectCount,this._retryConfig);WC.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await tg.race([US(t),this._onlineReconnectListener||new tg((()=>{}))])}if("closed"===this.state||!i)return!1;this._reconnectCount+=1;const n=async(e,t)=>{this.emit(TI.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];this.emit(TI.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||kC("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return WC.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);WC.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];this.emit(TI.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else"recover"===e&&(WC.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(TI.RECONNECT_WAITTING_FINISH,e),this.emit(TI.FAILBACK));return!0}catch(i){var r,s;return WC.error("[".concat(this._name,"] reconnect failed"),i.toString()),null!=i&&null!==(r=i.data)&&void 0!==r&&r.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&Lr(s=i.data.desc).call(s,"dynamic key expired")?(this.emit(TI.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class AD extends iS{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Ev.CONNECTED?this.emit(mv.WS_CONNECTED):e===Ev.RECONNECTING?this.emit(mv.WS_RECONNECTING,this._websocketReconnectReason):e===Ev.CLOSED&&this.emit(mv.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),nu(this,"_disconnectedReason",void 0),nu(this,"_websocketReconnectReason",void 0),nu(this,"_connectionState",Ev.CLOSED),nu(this,"reconnectToken",void 0),nu(this,"websocket",void 0),nu(this,"openConnectionTime",void 0),nu(this,"clientId",void 0),nu(this,"lastMsgTime",Date.now()),nu(this,"uploadCache",[]),nu(this,"uploadCacheInterval",void 0),nu(this,"rttRolling",new dT(5)),nu(this,"pingpongTimer",void 0),nu(this,"inflateDataTimer",void 0),nu(this,"pingpongTimeoutCount",0),nu(this,"joinResponse",void 0),nu(this,"multiIpOption",void 0),nu(this,"initError",void 0),nu(this,"spec",void 0),nu(this,"store",void 0),nu(this,"onWebsocketMessage",(e=>{if(e instanceof ArrayBuffer)return void this.emit(mv.ON_BINARY_DATA,e);const t=JSON.parse(e);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")&&(this.emit(t._type,t._message),t._type===Sv.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Sv.ON_USER_BANNED))switch(t._message.error_code){case 14:this.close(cS.UID_BANNED);break;case 15:this.close(cS.IP_BANNED);break;case 16:this.close(cS.CHANNEL_BANNED)}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new yD("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===Ev.CONNECTED&&this.reconnect("retry",SI.OFFLINE)}))}async request(e,t,i,n){const r=xS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new tg(((t,i)=>{if(this.connectionState===Ev.CONNECTED)return t();const n=()=>{this.off(mv.WS_CLOSED,r),t()},r=()=>{this.off(mv.WS_CONNECTED,n),i(new Mv(xg.WS_ABORT))};this.once(mv.WS_CONNECTED,n),this.once(mv.WS_CLOSED,r),e!==fv.PUBLISH&&e!==fv.SUBSCRIBE&&e!==fv.UNSUBSCRIBE&&e!==fv.UNPUBLISH&&e!==fv.CONTROL&&e!==fv.RESTART_ICE||this.once(mv.DISCONNECT_P2P,(()=>{i(new Mv(xg.DISCONNECT_P2P))})),e!==fv.PUBLISH&&e!==fv.RESTART_ICE||this.once(mv.ABORT_P2P_EXECUTION,(()=>{i(new Mv(xg.DISCONNECT_P2P))}))}));if(this.connectionState!==Ev.CONNECTING&&this.connectionState!==Ev.RECONNECTING||e===fv.JOIN||e===fv.REJOIN||await a(),e===fv.LEAVE&&(this.websocket.unbindDcCloseEventListener(),n=!0),this.websocket.sendMessage(s,!0,!1),n)return;const c=new tg(((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.emit(mv.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new Mv(xg.WS_ABORT,"type: ".concat(e))),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(mv.WS_CLOSED,c),this.once(mv.WS_RECONNECTING,c),US(kC("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==o||s||(WC.warning("dc request timeout, type: ".concat(e)),this.emit(mv.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===Ev.CLOSED||e===fv.LEAVE)throw new Mv(xg.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===fv.JOIN||e===fv.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),h=kI(l),u=new Mv(xg.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===h.action?d.message:(WC.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(h.desc,", action: ").concat(h.action)),l===_v.ERR_TOO_MANY_BROADCASTERS?e===fv.JOIN||e===fv.REJOIN?(this.initError=u,this.close(),u.throw()):u.throw():"failed"===h.action?u.throw():"quit"===h.action?(this.initError=u,this.close(),u.throw()):(l===_v.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,WC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",SI.MULTI_IP)):this.reconnect(h.action,SI.SERVER_ERROR),e===fv.JOIN||e===fv.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new tg((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=kC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==Ev.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),kC("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new tg(((i,n)=>{this.once(mv.WS_CONNECTED,(()=>i(this.joinResponse))),this.once(mv.WS_CLOSED,(()=>n(this.initError||new Mv(xg.WS_ABORT)))),this.connectionState=Ev.CONNECTING,this.websocket.init(e).catch(n),this.websocket.once(TI.FAILBACK,(()=>{void 0===this.openConnectionTime&&n(new Mv(xg.INIT_DATACHANNEL_TIMEOUT))})),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval((()=>{this.handleInflateData()}),2e4),setTimeout((()=>{t&&void 0===this.openConnectionTime&&(WC.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),n(new Mv(xg.INIT_DATACHANNEL_TIMEOUT)))}),kC("DC_JOIN_WITH_FAILBACK"))}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||cS.LEAVE,this.connectionState=Ev.CLOSED,WC.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===cS.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new yD("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(mv.ABORT_P2P_EXECUTION);const e=await fS(this,mv.DATACHANNEL_CONNECTING),t=await this.request(fv.JOIN,e);if(!t)return this.emit(mv.REPORT_JOIN_GATEWAY,xg.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(mv.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new Mv(xg.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=TS(this,mv.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(fv.REJOIN,e);return!!t&&(this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(Sv.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(Sv.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(Sv.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(Sv.MUTE_AUDIO,{uid:e.uid}):this.emit(Sv.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(Sv.MUTE_VIDEO,{uid:e.uid}):this.emit(Sv.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(Sv.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(Sv.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(Sv.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(Sv.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(Sv.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleNotification(e){WC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kI(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(cS.UID_BANNED),void this.close()):void this.reconnect(t.action,SI.SERVER_ERROR);WC.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=kC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(WC.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>kC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",SI.TIMEOUT):this.request(fv.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),kC("REPORT_STATS")&&this.send(fv.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleInflateData(){const{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(gv.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(TI.RECONNECT_WAITTING_FINISH,(e=>{this.emit(mv.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(TI.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(mv.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(TI.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(TI.CLOSED,(()=>{this.connectionState=Ev.CLOSED})),this.websocket.on(TI.FAILED,(()=>{this._disconnectedReason=cS.NETWORK_ERROR,this.connectionState=Ev.CLOSED})),this.websocket.on(TI.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Ev.CONNECTED?this.connectionState=Ev.RECONNECTING:this.connectionState=Ev.CONNECTING})),this.websocket.on(TI.WILL_RECONNECT,((e,t)=>{if(TS(this,mv.IS_P2P_DISCONNECTED)&&"retry"===e)return WC.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(mv.NEED_RENEW_SESSION),this.emit(mv.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(WC.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(mv.NEED_RENEW_SESSION),this.emit(mv.DISCONNECT_P2P)),t(e)})),this.websocket.on(TI.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{WC.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",SI.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(mv.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof Mv&&e.code===xg.UNEXPECTED_RESPONSE&&e.data.code===_v.ERR_NO_AUTHORIZED)return WC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",SI.SERVER_ERROR);WC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",SI.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(TI.REQUEST_NEW_URLS,((e,t)=>{fS(this,mv.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(TI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(Sv.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(TI.TO_CONNECT_DATACHANNEL,(async(e,t,i)=>fS(this,mv.DATACHANNEL_PRECONNECT,e).then(t).catch(i))),this.websocket.on(TI.FAILBACK,(()=>{void 0!==this.openConnectionTime&&this.emit(mv.DATACHANNEL_FAILBACK)}))}}class bD extends iS{constructor(e){super(),nu(this,"_signal",void 0),nu(this,"_sequence",0),nu(this,"_userMap",new Map),nu(this,"_encoder",new TextEncoder),this._signal=e}async send(e,t,i,n,r){var s,o,a;"string"!=typeof t&&(t=JSON.stringify(t)),n=null!==(s=n)&&void 0!==s?s:xS(6,""),r=null!==(o=r)&&void 0!==o?o:this._sequence++;const c={_id:n,_type:e,_seq:null!==(a=r)&&void 0!==a?a:this._sequence++,_message:t};if(kC("SHOW_P2P_LOG")&&WC.debug("send message",c),this.sendStreamMessage(JSON.stringify(c)),i)return;const d=new tg(((t,i)=>{const r=window.setTimeout((()=>{this.off("res-@".concat(n),s),WC.warning("[external-signal] request timeout, type: ".concat(e)),0===this._userMap.size?i(new Vg(xg.INVALID_REMOTE_USER)):i(new Vg(xg.TIMEOUT))}),kC("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),s=(e,n)=>{r&&window.clearTimeout(r),"success"===e?t({isSuccess:!0,message:n}):i(new Vg(xg.UNEXPECTED_ERROR,n))};this.once("res-@".concat(n),s)}));let l;try{l=await d}catch(i){if(i.code===xg.TIMEOUT)return await this.send(e,t,!1,n,r);throw i}return l.isSuccess?l.message:void 0}sendStreamMessage(e){this._splitMessage(e).forEach((e=>{this._signal.request(fv.DATA_STREAM,{payload:PS(this._encoder.encode(e))})}))}onMessage(e){const{_uid:t}=e;let i;const n=this._userMap.get(t);if(n?i=n.splitMessageMap:(i=new Map,this._userMap.set(t,{isStart:!1,splitMessageMap:i,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map})),"id"in e&&"total"in e){var r;const{id:n,total:s}=e,o=null!==(r=i.get(n))&&void 0!==r?r:[];if(o.push(e),i.has(n)||i.set(n,o),o.length!==s)return;{const r=Zu(o).call(o,((e,t)=>e.index-t.index)).map((e=>e.payload)).join("");i.delete(n),(e=JSON.parse(r))._uid=t}}this.handleReceivedMessage(e)}setStart(e){this._userMap.has(e)?this._userMap.get(e).isStart=!0:this._userMap.set(e,{isStart:!0,splitMessageMap:new Map,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map}),this.handleReceivedMessage()}setEnd(e){return this._userMap.delete(e),0===this._userMap.size}ack(e,t,i){this.send(AI.ACK,JSON.stringify({success:!i,message:t}),!0,e)}handleReceivedMessage(e){const t=()=>{this._userMap.forEach((e=>{const{receivedMessagesMap:t,nextExpectedSequenceNumber:i}=e;for(;t.has(i);){const n=t.get(i);t.delete(i),this.receiveMessage(n),e.nextExpectedSequenceNumber++}}))};if(!e)return void t();const{_uid:i,_seq:n}=e,r=this._userMap.get(i),{receivedMessagesMap:s,isStart:o,nextExpectedSequenceNumber:a}=r;n<a?WC.debug("[external-signal] receive old message, seq: ".concat(n)):(s.set(n,e),o&&n===a&&(this.receiveMessage(e),s.delete(a),r.nextExpectedSequenceNumber++,t()))}receiveMessage(e){const{_id:t,_type:i,_message:n,_uid:r}=e;if(kC("SHOW_P2P_LOG")&&WC.debug("收到消息",e),t)switch(e._type){case AI.PUBLISH:const s=JSON.parse(n);this._signal.emit(i,s,r),this.ack(e._id);break;case AI.CONTROL:case AI.UNPUBLISH:case AI.DO_SUBSCRIBE:case AI.DO_UNSUBSCRIBE:{const t=JSON.parse(n);t.uid=r,fS(this._signal,i,t).then((t=>{this.ack(e._id,t)})).catch((t=>{this.ack(e._id,void 0,!0)}));break}case AI.ACK:{const{success:e,message:i}=JSON.parse(n);this.emit("res-@".concat(t),e?"success":"failed",i);break}case AI.CALL:fS(this,i,n).then((e=>{this.ack(t,e)}));break;case AI.RESTART_ICE:case AI.EXCHANGE_SDP:case AI.SUBSCRIBE:case AI.UNSUBSCRIBE:fS(this._signal,i,n).then((e=>{this.ack(t,e)})).catch((t=>{this.ack(e._id,void 0,!0)}));break;case AI.CANDIDATE:this._signal.emit(i,n),this.ack(t);break;case AI.JOIN:this.emit(i,JSON.parse(n));break;default:this.emit(i,n),this.ack(t)}}_splitMessage(e){if(e.length<bD.MAX_MESSAGE_SIZE)return[e];const t=[],i=xS(6,"");let n=0;const r=Math.ceil(e.length/800);for(;e.length>0;){n++;const s=e.slice(0,800);t.push({id:i,index:n,total:r,payload:s}),e=e.slice(800)}return t.map((e=>JSON.stringify(e)))}clear(){this._sequence=0,this._userMap.clear()}}nu(bD,"MAX_MESSAGE_SIZE",1024);class wD extends iS{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Ev.CONNECTED?this.emit(mv.WS_CONNECTED):e===Ev.RECONNECTING?this.emit(mv.WS_RECONNECTING,this._websocketReconnectReason):e===Ev.CLOSED&&this.emit(mv.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),nu(this,"_disconnectedReason",void 0),nu(this,"_websocketReconnectReason",void 0),nu(this,"_connectionState",Ev.CLOSED),nu(this,"reconnectToken",void 0),nu(this,"_userInRoom",!1),nu(this,"_userOnlineTime",void 0),nu(this,"websocket",void 0),nu(this,"openConnectionTime",void 0),nu(this,"clientId",void 0),nu(this,"lastMsgTime",Date.now()),nu(this,"uploadCache",[]),nu(this,"uploadCacheInterval",void 0),nu(this,"rttRolling",new dT(5)),nu(this,"pingpongTimer",void 0),nu(this,"wsInflateDataTimer",void 0),nu(this,"pingpongTimeoutCount",0),nu(this,"joinResponse",void 0),nu(this,"multiIpOption",void 0),nu(this,"initError",void 0),nu(this,"spec",void 0),nu(this,"store",void 0),nu(this,"_external_signal",void 0),nu(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(mv.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){switch(t._type){case Sv.ON_DATA_STREAM:return void this.handleDataStream(t._message);case Sv.MUTE_AUDIO:case Sv.MUTE_VIDEO:case Sv.ON_P2P_LOST:return;case Sv.ON_USER_ONLINE:this.emit(t._type,t._message);const{uid:e}=t._message;return this._external_signal.setStart(e),void this._external_signal.send(AI.JOIN,{onlineTime:this._userOnlineTime},!0)}if(this.emit(t._type,t._message),t._type===Sv.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Sv.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(cS.UID_BANNED);break;case 15:this.close(cS.IP_BANNED);break;case 16:this.close(cS.CHANNEL_BANNED)}if(t._type===Sv.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case _v.ERR_LICENSE_MISSING:this.close(cS.LICENSE_MISSING);break;case _v.ERR_LICENSE_EXPIRED:this.close(cS.LICENSE_EXPIRED);break;case _v.ERR_LICENSE_MINUTES_EXCEEDED:this.close(cS.LICENSE_MINUTES_EXCEEDED);break;case _v.ERR_LICENSE_PERIOD_INVALID:this.close(cS.LICENSE_PERIOD_INVALID);break;case _v.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(cS.LICENSE_MULTIPLE_SDK_SERVICE);break;case _v.ERR_LICENSE_ILLEGAL:this.close(cS.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new qI("gateway-".concat(this.clientId),this.spec.retryConfig,!0,kC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),kC("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===Ev.CONNECTED&&this.reconnect("retry",lS.OFFLINE)})),this._external_signal=new bD(this),this._handleSignalP2PEvents()}async request(e,t,i,n){const r=xS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new tg(((t,i)=>{if(this.connectionState===Ev.CONNECTED)return t();const n=()=>{this.off(mv.WS_CLOSED,r),t()},r=()=>{this.off(mv.WS_CONNECTED,n),i(new Vg(xg.WS_ABORT))};this.once(mv.WS_CONNECTED,n),this.once(mv.WS_CLOSED,r),e!==fv.PUBLISH&&e!==fv.SUBSCRIBE&&e!==fv.UNSUBSCRIBE&&e!==fv.UNPUBLISH&&e!==fv.CONTROL&&e!==fv.RESTART_ICE||this.once(mv.DISCONNECT_P2P,(()=>{i(new Vg(xg.DISCONNECT_P2P))})),e!==fv.PUBLISH&&e!==fv.RESTART_ICE||this.once(mv.ABORT_P2P_EXECUTION,(()=>{i(new Vg(xg.DISCONNECT_P2P))}))}));if(this.connectionState!==Ev.CONNECTING&&this.connectionState!==Ev.RECONNECTING||e===fv.JOIN||e===fv.REJOIN||await a(),this.websocket.sendMessage(s,!0),n)return;const c=new tg(((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.emit(mv.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new Vg(xg.WS_ABORT,"type: ".concat(e))),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(mv.WS_CLOSED,c),this.once(mv.WS_RECONNECTING,c),US(kC("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==o||s||(WC.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(mv.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===Ev.CLOSED||e===fv.LEAVE)throw new Vg(xg.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===fv.JOIN||e===fv.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),h=kI(l),u=new Vg(xg.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===h.action?d.message:(WC.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(h.desc,", action: ").concat(h.action)),l===_v.ERR_TOO_MANY_BROADCASTERS?e===fv.JOIN||e===fv.REJOIN?(this.initError=u,this.close(),u.throw()):u.throw():"failed"===h.action?u.throw():"quit"===h.action?(this.initError=u,this.close(),u.throw()):(l===_v.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,WC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",lS.MULTI_IP)):this.reconnect(h.action,lS.SERVER_ERROR),e===fv.JOIN||e===fv.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new tg((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=kC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==Ev.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),kC("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}async sendExtensionMessage(e,t,i){return await this.waitTillUserOnline(),await this._external_signal.send(e,t,i)}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new tg(((t,i)=>{this.once(mv.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(mv.WS_CLOSED,(()=>i(this.initError||new Vg(xg.WS_ABORT)))),this.connectionState=Ev.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||cS.LEAVE,this.connectionState=Ev.CLOSED,WC.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===cS.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new qI("gateway-".concat(this.clientId),this.spec.retryConfig,!0,kC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),kC("JOIN_GATEWAY_USE_443PORT_ONLY"),this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(mv.ABORT_P2P_EXECUTION);const e=await fS(this,mv.REQUEST_JOIN_INFO),t=await this.request(fv.JOIN,e);if(!t)return this.emit(mv.REPORT_JOIN_GATEWAY,xg.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(mv.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),this._userOnlineTime=(new Date).getTime(),this._external_signal.clear(),!0}async rejoin(){if(!this.reconnectToken)throw new Vg(xg.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=TS(this,mv.REQUEST_REJOIN_INFO);return e.token=this.reconnectToken,!!await this.request(fv.REJOIN,e)&&(this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleDataStream(e){try{var t;const i=DS(e.payload),n=(new TextDecoder).decode(i),r=JSON.parse(n);"total"in r&&"id"in r||Lr(t=Object.values(AI)).call(t,r._type)?(e.seq&&delete e.seq,r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(Sv.ON_DATA_STREAM,e)}catch(e){}}handleNotification(e){WC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kI(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(cS.UID_BANNED),void this.close()):void this.reconnect(t.action,lS.SERVER_ERROR);WC.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=kC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(WC.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>kC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",lS.TIMEOUT):this.request(fv.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),kC("REPORT_STATS")&&this.send(fv.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(gv.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(Cv.RECONNECT_WAITTING_FINISH,(e=>{this.emit(mv.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(Cv.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(mv.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(Cv.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Cv.CLOSED,(()=>{this.connectionState=Ev.CLOSED})),this.websocket.on(Cv.FAILED,(()=>{this._disconnectedReason=cS.NETWORK_ERROR,this.connectionState=Ev.CLOSED})),this.websocket.on(Cv.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Ev.CONNECTED?this.connectionState=Ev.RECONNECTING:this.connectionState=Ev.CONNECTING})),this.websocket.on(Cv.WILL_RECONNECT,((e,t,i)=>{if(TS(this,mv.IS_P2P_DISCONNECTED)&&"retry"===e)return WC.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(mv.NEED_RENEW_SESSION),this.emit(mv.DISCONNECT_P2P),i("tryNext");"retry"!==e&&(WC.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(mv.NEED_RENEW_SESSION),this.emit(mv.DISCONNECT_P2P)),i(e)})),this.websocket.on(Cv.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{WC.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",lS.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(mv.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof Vg&&e.code===xg.UNEXPECTED_RESPONSE&&e.data.code===_v.ERR_NO_AUTHORIZED)return WC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",lS.SERVER_ERROR);WC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",lS.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(Cv.REQUEST_NEW_URLS,((e,t)=>{fS(this,mv.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(Cv.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(Sv.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}_handleSignalP2PEvents(){this._external_signal.on(AI.JOIN,(async e=>{if(this._userOnlineTime&&this._userOnlineTime<e.onlineTime){const e=await fS(this,mv.P2P_START,void 0),t=await this._external_signal.send(AI.CALL,e);this.emit(mv.P2P_CONNECTION,t,!0)}this._userInRoom=!0,this.emit("user-online")})),this.on(Sv.ON_USER_OFFLINE,(async e=>{this._external_signal.clear(),this._userInRoom=!1})),this._external_signal.on(AI.CALL,(async(e,t,i)=>{this._userInRoom=!0,this.emit("user-online");try{t(await fS(this,mv.P2P_START,e))}catch(e){i(e)}}))}async waitTillUserOnline(){return new tg((e=>{if(this._userInRoom)e();else{const t=()=>{this.off("user-online",t),e()};this.on("user-online",t)}}))}}function OD(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function ND(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?OD(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):OD(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const DD=new Map;class PD extends iS{get state(){return this._state}set state(e){if(e===this._state)return;const t=this._state;this._state=e,"DISCONNECTED"===e&&this._disconnectedReason?this.emit(Zv.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(Zv.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){WC.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){super(),nu(this,"store",void 0),nu(this,"joinInfo",void 0),nu(this,"key",void 0),nu(this,"ntpOffset",0),nu(this,"signal",void 0),nu(this,"role",void 0),nu(this,"inChannelInfo",{joinAt:null,duration:0}),nu(this,"spec",void 0),nu(this,"_state","DISCONNECTED"),nu(this,"_statsCollector",void 0),nu(this,"_disconnectedReason",void 0),nu(this,"isSignalRecover",!1),nu(this,"hasChangeBGPAddress",!1),nu(this,"trafficStatsInterval",void 0),nu(this,"networkQualityInterval",void 0),nu(this,"_joinGatewayStartTime",0),nu(this,"_signalTimeout",!1),nu(this,"_clientRoleOptions",void 0),nu(this,"_isProactiveJoin",!1),this.store=e,this.spec=t,this.signal=this.store.useP2P?new wD(ND(ND({},t),{},{retryConfig:t.websocketRetryConfig}),e):this.store.useDataChannel?new AD(ND(ND({},t),{},{retryConfig:t.websocketRetryConfig}),e):new zI(ND(ND({},t),{},{retryConfig:t.websocketRetryConfig}),e),this._statsCollector=t.statsCollector,this.role=t.role||"audience",this._clientRoleOptions=t.clientRoleOptions,this.handleSignalEvents()}async join(e,t,i){if(this.signal instanceof AD){let t=!1;"disabled"!==e.cloudProxyServer?(WC.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(e.cloudProxyServer,")")),t=!0):"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length>255||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length<22?(WC.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),t=!0):e.apResponse.addresses.some((e=>e.fingerprint))||kC("FINGERPRINT")||(WC.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0),t&&this.resetSignal()}this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const n=Date.now();let r=DD.get(e.cname);if(r||(r=new Map,DD.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new Mv(xg.UID_CONFLICT);throw iv.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!e.proxyServer,signalChannel:this.signal instanceof AD?"1":"0"}),this._isProactiveJoin=!1,t}r.set(e.uid,!0),this.joinInfo=e,this.key=t;let s=0;this.joinGatewayStartTime=n;const o=e.proxyServer;try{let t;if(WC.debug("[".concat(this.store.clientId,"] use ").concat(this.signal instanceof AD?"datachannel":"websocket"," join uid ").concat(s)),this.signal instanceof AD)t=await this.signal.init(e.apResponse.addresses,i);else{const n=e.gatewayAddrs.map((t=>{let{address:i}=t;const[n,r]=i.split(":"),s={host:n,port:r};return e.proxyServer&&(s.proxy=e.proxyServer),s}));t=await this.signal.init(n,i)}s=t.uid,WC.debug("[".concat(this.store.clientId,"] ").concat(this.signal instanceof AD?"datachannel":"websocket"," join uid ").concat(s," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){if(t&&t.code===xg.INIT_WEBSOCKET_TIMEOUT)throw WC.warning("[".concat(this.store.clientId,"] User join failed"),t.toString()),t;if(t&&t.code===xg.INIT_DATACHANNEL_TIMEOUT)throw WC.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw WC.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),iv.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!o,signalChannel:this.signal instanceof AD?"1":"0"}),this._isProactiveJoin=!1,r.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),WC.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{WC.warning("[".concat(this.store.clientId,"] get traffic stats error"),e.toString())}))}),3e3),this.networkQualityInterval=window.setInterval((()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(Zv.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(Zv.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(Zv.NETWORK_QUALITY,{uplinkNetworkQuality:mD(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:mD(this._statsCollector.trafficStats.B_dnq)}):this.emit(Zv.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})}),2e3),this.store.joinGatewayEnd(),s}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==cS.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==Ev.CONNECTED||await function(e,t){return t===1/0?e:tg.race([e,MS(t)])}(this.signal.request(fv.LEAVE,void 0,!0),3e3)}catch(e){WC.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==cS.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const n={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:kC("PUB_EXTEND"),twcc:!!kC("PUBLISH_TWCC"),rtx:!!kC("USE_PUB_RTX")};try{return(await this.signal.request(fv.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===_v.ERR_PUBLISH_REQUEST_INVALID)return WC.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),n.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw n}}async publishDataChannel(e,t,i){var n;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const r={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(n=t.maxRetransmits)&&void 0!==n?n:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(fv.PUBLISH_DATASTREAM,r,!0)}catch(n){if(i&&n.data&&n.data.code===_v.ERR_PUBLISH_REQUEST_INVALID)return WC.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),n.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw n}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(fv.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){WC.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await tg.all(e.map((e=>this.signal.request(fv.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){WC.warning("unpublish datachannels warning: ",e)}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!kC("SUBSCRIBE_TWCC"),rtx:!!kC("USE_SUB_RTX"),extend:kC("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(kC("SVC"))&&0!==kC("SVC").length?kC("SVC"):void 0};try{return(await this.signal.request(fv.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===_v.ERR_SUBSCRIBE_REQUEST_INVALID)return WC.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),n.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw n}}async subscribeDataChannel(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const n={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(fv.SUBSCRIBE_DATASTREAM,n,!0)}catch(n){if(i&&n.data&&n.data.code===_v.ERR_SUBSCRIBE_REQUEST_INVALID)return WC.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),n.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw n}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!kC("USE_SUB_RTX")};try{return await this.signal.request(fv.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===_v.ERR_SUBSCRIBE_REQUEST_INVALID)return WC.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,n=e.height,r=!0;return"number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(r=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,t||(r=!1)),r?{stream_type:0,width:i,height:n,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0}(e);if(t)return this.signal.request(fv.SET_VIDEO_PROFILE,t);WC.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(fv.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){WC.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await tg.all(e.map((e=>this.signal.request(fv.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){WC.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(fv.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){WC.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=e;return{gatewayEstablishParams:await this.signal.request(fv.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(fv.GATEWAY_INFO)}async renewToken(e){await this.signal.request(fv.RENEW_TOKEN,e),this.key=e.token}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),"CONNECTED"!==this.state)return void(this.role=e);let i,n=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,n=1):n=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:n=0,await this.signal.request(fv.SET_CLIENT_ROLE,{role:e,level:n,delay:i,client_ts:Date.now()}),this.role=e}async setRemoteVideoStreamType(e,t){await this.signal.request(fv.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(fv.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(fv.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(fv.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(fv.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,i){if(this.signal instanceof wD)return this.signal.sendExtensionMessage(e,t,i)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),ND({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(fv.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=DD.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0)}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:rv.username,password:rv.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null}(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(ND(ND({},rv),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if("CONNECTED"!==this.state)return;const e=await this.signal.request(fv.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach((e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find((t=>t.peer_uid===e.peer_uid));t&&t.B_st!==e.B_st&&AS((()=>{this.emit(Zv.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){if(!this.joinInfo||!this.key)throw new Mv(xg.UNEXPECTED_ERROR,"can not generate join message, no join info");const t=Object.assign({},this.joinInfo.apResponse);let i=kC("REPORT_APP_SCENARIO");if("string"!=typeof i)try{i=JSON.stringify(i)}catch(e){i=void 0}i&&i.length>128&&(i=void 0);const n=ND({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:OC,browser:navigator.userAgent,process_id:kC("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:t,extend:kC("JOIN_EXTEND"),details:{6:this.joinInfo.stringUid,cservice_map:"proxy3"===this.joinInfo.cloudProxyServer?"1":"proxy5"===this.joinInfo.cloudProxyServer?"2":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:i,attributes:{userAttributes:{enablePublishedUserList:kC("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:kC("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:"number"==typeof kC("SUBSCRIBE_AUDIO_FILTER_TOPN")?kC("SUBSCRIBE_AUDIO_FILTER_TOPN"):void 0,enablePublishAudioFilter:"boolean"==typeof kC("ENABLE_PUBLISH_AUDIO_FILTER")?kC("ENABLE_PUBLISH_AUDIO_FILTER"):void 0,enableUserLicenseCheck:"boolean"==typeof kC("ENABLE_USER_LICENSE_CHECK")?kC("ENABLE_USER_LICENSE_CHECK"):void 0,enableRTX:!0===kC("USE_PUB_RTX")||!0===kC("USE_SUB_RTX")||void 0,disableFEC:kC("DISABLE_FEC"),enableNTPReport:!!kC("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:!!kC("ENABLE_INSTANT_VIDEO")||void 0,enableDataStream2:"boolean"==typeof kC("ENABLE_DATASTREAM_2")?kC("ENABLE_DATASTREAM_2"):void 0,rtm2Flag:"number"==typeof kC("RTM2_FLAG")?kC("RTM2_FLAG"):void 0,enableUserAutoRebalanceCheck:!!kC("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:"boolean"==typeof kC("USE_XR")?kC("USE_XR"):void 0}},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(n.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(n.aes_mode=this.joinInfo.aesmode,kC("ENCRYPT_AES")?(n.aes_secret=this.joinInfo.aespassword,n.aes_encrypt=!0):n.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(n.aes_salt=this.joinInfo.aessalt)),t.addresses[this.signal.websocket.currentURLIndex]&&(n.ap_response.ticket=t.addresses[this.signal.websocket.currentURLIndex].ticket,delete t.addresses),void 0!==this.joinInfo.defaultVideoStream&&(n.default_video_stream=this.joinInfo.defaultVideoStream),n}getRejoinMessage(){if(!this.joinInfo)throw new Mv(xg.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(mv.WS_RECONNECT_WAITTING_FINISH,(e=>{var t;Lr(t=["tryNext","recover"]).call(t,e)&&this.joinInfo&&iv.adjustSessionStartTime(this.joinInfo.sid)})),this.signal.on(mv.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(mv.WS_RECONNECTING,(e=>{this.joinInfo&&iv.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||lS.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",iv.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(mv.WS_CLOSED,(e=>{let t;switch(e){case cS.LEAVE:t=lS.LEAVE;break;case cS.UID_BANNED:case cS.IP_BANNED:case cS.CHANNEL_BANNED:case cS.SERVER_ERROR:t=lS.SERVER_ERROR;break;case cS.FALLBACK:t=lS.FALLBACK;break;case cS.LICENSE_MISSING:case cS.LICENSE_EXPIRED:case cS.LICENSE_MINUTES_EXCEEDED:case cS.LICENSE_PERIOD_INVALID:case cS.LICENSE_MULTIPLE_SDK_SERVICE:case cS.LICENSE_ILLEGAL:case cS.TOKEN_EXPIRE:t=e;break;default:t=lS.NETWORK_ERROR}WC.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+lS.NETWORK_ERROR)),this.joinInfo&&iv.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===cS.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==cS.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(mv.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo&&("audience"===this.role&&this._clientRoleOptions&&(this._clientRoleOptions.level||this._clientRoleOptions.delay)&&(WC.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(this._clientRoleOptions.level,", delay: ").concat(this._clientRoleOptions.delay)),this.setClientRole(this.role,this._clientRoleOptions)),iv.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof AD?"1":"0"}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion)){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void WC.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));LC("EVENT_REPORT_DOMAIN",e[1]),LC("EVENT_REPORT_BACKUP_DOMAIN",e[1]),LC("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}})),this.signal.on(Sv.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(mv.REQUEST_RECOVER,((e,t,i)=>{if(!this.joinInfo)return i(new Mv(xg.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,fS(this,Zv.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)})),this.signal.on(mv.REQUEST_JOIN_INFO,(async e=>{var t;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const{iceParameters:i,dtlsParameters:n,rtpCapabilities:r}=await fS(this,Zv.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:null===(t=this.joinInfo)||void 0===t?void 0:t.turnServer});e(this.getJoinMessage({ortc:{iceParameters:i,dtlsParameters:n,rtpCapabilities:r,version:"2"}}))})),this.signal.on(mv.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(mv.REPORT_JOIN_GATEWAY,((e,t)=>{this.joinInfo&&(iv.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:e,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof AD?"1":"0"}),this._isProactiveJoin=!1)})),this.signal.on(mv.IS_P2P_DISCONNECTED,(e=>{e(TS(this,Zv.IS_P2P_DISCONNECTED))})),this.signal.on(mv.DISCONNECT_P2P,(()=>{this.emit(Zv.DISCONNECT_P2P)})),this.signal.on(mv.NEED_RENEW_SESSION,(()=>{this.emit(Zv.NEED_RENEW_SESSION)})),this.signal.on(mv.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(mv.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(mv.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(Zv.JOIN_RESPONSE,e,t)})),this.signal.on(mv.DATACHANNEL_PRECONNECT,(async(e,t,i)=>{this.updateTurnConfigFromSignal();const n=this.getCurrentGatewayAddress();return fS(this,Zv.DATACHANNEL_PRECONNECT,e,n).then(t).catch(i)})),this.signal.on(mv.DATACHANNEL_CONNECTING,(async e=>{const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await fS(this,Zv.REQUEST_DC_CONNECTION_PARAMS);e(this.getJoinMessage({ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n,version:"2"}}))})),this.signal.on(mv.DATACHANNEL_FAILBACK,(()=>{WC.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(Zv.DATACHANNEL_FAILBACK)}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(fv.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(fv.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw WC.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(fv.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(fv.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw WC.warning("unpublish datastream warning: ",e),e}}async tryMassUnsubBeforeResub(e){const t={users:e.map((e=>({stream_id:e.stream_id,stream_type:e.stream_type})))};try{await this.signal.request(fv.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const i={action:e.find((e=>e.stream_type===Qv.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(fv.CONTROL,i,!0,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const i={action:e.find((e=>e.stream_type===Qv.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(fv.CONTROL,i,!0,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const i={action:e===dI.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(fv.CONTROL,i,!0,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const i={action:e===dI.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(fv.CONTROL,i,!0,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),e),e}}uploadStats(e,t){this.signal.upload(e,t)}getSignalRTT(){return this.signal.rtt}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(fv.RESTART_ICE,t,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(){"CONNECTED"===this.state&&this.signal.reconnect(void 0,lS.P2P_FAILED)}getCurrentGatewayAddress(){var e;if(!kC("GATEWAY_WSS_ADDRESS"))return null!==(e=this.joinInfo)&&void 0!==e&&e.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(fv.SET_PARAMETER,{enablePublishAudioFilter:e})}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(cS.FALLBACK)),this.store.useDataChannel=!1,this.signal=new zI(ND(ND({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(Zv.RESET_SIGNAL,tI.websocket)}}let LD=0,kD=0;function MD(e,t,i,n){return new tg(((r,s)=>{t.timeout=t.timeout||kC("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),LD+=LS(t.data)):i&&(t.data.size?LD+=t.data.size:t.data instanceof FormData?LD+=kS(t.data):LD+=LS(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,EC.request(t).then((e=>{"string"==typeof e.data?kD+=LS(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?kD+=e.data.byteLength:kD+=LS(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{EC.isCancel(e)?s(new Mv(xg.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new Mv(xg.NETWORK_TIMEOUT,e.message)):e.response?s(new Mv(xg.NETWORK_RESPONSE_ERROR,e.response.status)):s(new Mv(xg.NETWORK_ERROR,e.message))}))}))}
1
+ "use strict";var e=require("./index-3379da44.js");function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var i,n={exports:{}};i=n,e.commonjsGlobal,i.exports=function(){function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}let i=!0,n=!0;function r(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function s(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function o(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(i=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function a(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(n=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function c(){if("object"==typeof window){if(i)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function d(e,t){n&&console.warn(e+" is deprecated, please use "+t+" instead.")}function l(e){return"[object Object]"===Object.prototype.toString.call(e)}function h(e){return l(e)?Object.keys(e).reduce((function(t,i){const n=l(e[i]),r=n?h(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function u(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?u(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{u(e,e.get(t),i)}))})))}function p(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&u(e,i,r)}))})),r}const _=c;function E(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),_("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return _("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function m(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function f(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else s(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function g(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function S(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(s(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(r(t)))},i])})).then(i,n)}}function T(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>p(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),s(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>p(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function R(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function C(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return R(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function v(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function I(e,t){s(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var y=Object.freeze({__proto__:null,fixNegotiationNeeded:I,shimAddTrackRemoveTrack:C,shimAddTrackRemoveTrackWithNative:R,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:g,shimGetStats:S,shimGetUserMedia:E,shimMediaStream:m,shimOnTrack:f,shimPeerConnection:v,shimSenderReceiverGetStats:T});function A(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){d("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function b(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function w(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,s)}}function O(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function N(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),s(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function D(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){d("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function P(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function L(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function k(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function M(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function U(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var x=Object.freeze({__proto__:null,shimAddTransceiver:L,shimCreateAnswer:U,shimCreateOffer:M,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:k,shimGetUserMedia:A,shimOnTrack:b,shimPeerConnection:w,shimRTCDataChannel:P,shimReceiverGetStats:N,shimRemoveStream:D,shimSenderGetStats:O});function V(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function F(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function B(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function j(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(G(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function G(e){return e&&void 0!==e.video?Object.assign({},e,{video:h(e.video)}):e}function W(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];!n.hasOwnProperty("urls")&&n.hasOwnProperty("url")?(d("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function H(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function K(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Y(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var q=Object.freeze({__proto__:null,shimAudioContext:Y,shimCallbacksAPI:B,shimConstraints:G,shimCreateOfferLegacy:K,shimGetUserMedia:j,shimLocalStreamsAPI:V,shimRTCIceServerUrls:W,shimRemoteStreamsAPI:F,shimTrackEventTransceiver:H}),J="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==e.commonjsGlobal?e.commonjsGlobal:"undefined"!=typeof self?self:{};function z(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var X={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;return r=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(X);var Q=X.exports,Z=z(Q),$=t({__proto__:null,default:Z},[Q]);function ee(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Z.parseCandidate(e.candidate),r=Object.assign(i,n);return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,s(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function te(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||s(e,"icecandidate",(e=>{if(e.candidate){const t=Z.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function ie(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=function(e){if(!e||!e.sdp)return!1;const t=Z.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Z.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},n=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},s=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=Z.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){const e=n(arguments[0]),t=r(e),i=s(arguments[0],e);let o;o=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>o}),this._sctp=a}return o.apply(this,arguments)}}function ne(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},s(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function re(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function se(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function oe(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ae(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var ce=Object.freeze({__proto__:null,removeExtmapAllowMixed:se,shimAddIceCandidateNullOrEmpty:oe,shimConnectionState:re,shimMaxMessageSize:ie,shimParameterlessSetLocalDescription:ae,shimRTCIceCandidate:ee,shimRTCIceCandidateRelayProtocol:te,shimSendThrowTypeError:ne});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=c,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=r(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=r(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=r(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:n,commonShim:ce,extractVersion:r,disableLog:o,disableWarnings:a,sdp:$};switch(n.browser){case"chrome":if(!y||!v||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=y,oe(e,n),ae(e),E(e,n),m(e),v(e,n),f(e),C(e,n),g(e),S(e),T(e),I(e,n),ee(e),te(e),re(e),ie(e,n),ne(e),se(e,n);break;case"firefox":if(!x||!w||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=x,oe(e,n),ae(e),A(e,n),w(e,n),b(e),D(e),O(e),N(e),P(e),L(e),k(e),M(e),U(e),ee(e),re(e),ie(e,n),ne(e);break;case"safari":if(!q||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=q,oe(e,n),ae(e),W(e),K(e),B(e),V(e),F(e),H(e),j(e),Y(e),ee(e),te(e),ie(e,n),ne(e),se(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var de=function(e){try{return!!e()}catch(e){return!0}},le=!de((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),he=le,ue=Function.prototype,pe=ue.call,_e=he&&ue.bind.bind(pe,pe),Ee=he?_e:function(e){return function(){return pe.apply(e,arguments)}},me=Ee({}.isPrototypeOf),fe=function(e){return e&&e.Math==Math&&e},ge=fe("object"==typeof globalThis&&globalThis)||fe("object"==typeof window&&window)||fe("object"==typeof self&&self)||fe("object"==typeof J&&J)||function(){return this}()||J||Function("return this")(),Se=le,Te=Function.prototype,Re=Te.apply,Ce=Te.call,ve="object"==typeof Reflect&&Reflect.apply||(Se?Ce.bind(Re):function(){return Ce.apply(Re,arguments)}),Ie=Ee,ye=Ie({}.toString),Ae=Ie("".slice),be=function(e){return Ae(ye(e),8,-1)},we=be,Oe=Ee,Ne=function(e){if("Function"===we(e))return Oe(e)},De="object"==typeof document&&document.all,Pe={all:De,IS_HTMLDDA:void 0===De&&void 0!==De},Le=Pe.all,ke=Pe.IS_HTMLDDA?function(e){return"function"==typeof e||e===Le}:function(e){return"function"==typeof e},Me={},Ue=!de((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),xe=le,Ve=Function.prototype.call,Fe=xe?Ve.bind(Ve):function(){return Ve.apply(Ve,arguments)},Be={},je={}.propertyIsEnumerable,Ge=Object.getOwnPropertyDescriptor,We=Ge&&!je.call({1:2},1);Be.f=We?function(e){var t=Ge(this,e);return!!t&&t.enumerable}:je;var He,Ke,Ye=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},qe=de,Je=be,ze=Object,Xe=Ee("".split),Qe=qe((function(){return!ze("z").propertyIsEnumerable(0)}))?function(e){return"String"==Je(e)?Xe(e,""):ze(e)}:ze,Ze=function(e){return null==e},$e=Ze,et=TypeError,tt=function(e){if($e(e))throw et("Can't call method on "+e);return e},it=Qe,nt=tt,rt=function(e){return it(nt(e))},st=ke,ot=Pe.all,at=Pe.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:st(e)||e===ot}:function(e){return"object"==typeof e?null!==e:st(e)},ct={},dt=ct,lt=ge,ht=ke,ut=function(e){return ht(e)?e:void 0},pt=function(e,t){return arguments.length<2?ut(dt[e])||ut(lt[e]):dt[e]&&dt[e][t]||lt[e]&&lt[e][t]},_t="undefined"!=typeof navigator&&String(navigator.userAgent)||"",Et=ge,mt=_t,ft=Et.process,gt=Et.Deno,St=ft&&ft.versions||gt&&gt.version,Tt=St&&St.v8;Tt&&(Ke=(He=Tt.split("."))[0]>0&&He[0]<4?1:+(He[0]+He[1])),!Ke&&mt&&(!(He=mt.match(/Edge\/(\d+)/))||He[1]>=74)&&(He=mt.match(/Chrome\/(\d+)/))&&(Ke=+He[1]);var Rt=Ke,Ct=Rt,vt=de,It=ge.String,yt=!!Object.getOwnPropertySymbols&&!vt((function(){var e=Symbol();return!It(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Ct&&Ct<41})),At=yt&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,bt=pt,wt=ke,Ot=me,Nt=Object,Dt=At?function(e){return"symbol"==typeof e}:function(e){var t=bt("Symbol");return wt(t)&&Ot(t.prototype,Nt(e))},Pt=String,Lt=function(e){try{return Pt(e)}catch(e){return"Object"}},kt=ke,Mt=Lt,Ut=TypeError,xt=function(e){if(kt(e))return e;throw Ut(Mt(e)+" is not a function")},Vt=xt,Ft=Ze,Bt=function(e,t){var i=e[t];return Ft(i)?void 0:Vt(i)},jt=Fe,Gt=ke,Wt=at,Ht=TypeError,Kt={exports:{}},Yt=ge,qt=Object.defineProperty,Jt=function(e,t){try{qt(Yt,e,{value:t,configurable:!0,writable:!0})}catch(i){Yt[e]=t}return t},zt="__core-js_shared__",Xt=ge[zt]||Jt(zt,{}),Qt=Xt;(Kt.exports=function(e,t){return Qt[e]||(Qt[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Zt=Kt.exports,$t=tt,ei=Object,ti=function(e){return ei($t(e))},ii=ti,ni=Ee({}.hasOwnProperty),ri=Object.hasOwn||function(e,t){return ni(ii(e),t)},si=Ee,oi=0,ai=Math.random(),ci=si(1..toString),di=function(e){return"Symbol("+(void 0===e?"":e)+")_"+ci(++oi+ai,36)},li=Zt,hi=ri,ui=di,pi=yt,_i=At,Ei=ge.Symbol,mi=li("wks"),fi=_i?Ei.for||Ei:Ei&&Ei.withoutSetter||ui,gi=function(e){return hi(mi,e)||(mi[e]=pi&&hi(Ei,e)?Ei[e]:fi("Symbol."+e)),mi[e]},Si=Fe,Ti=at,Ri=Dt,Ci=Bt,vi=function(e,t){var i,n;if("string"===t&&Gt(i=e.toString)&&!Wt(n=jt(i,e)))return n;if(Gt(i=e.valueOf)&&!Wt(n=jt(i,e)))return n;if("string"!==t&&Gt(i=e.toString)&&!Wt(n=jt(i,e)))return n;throw Ht("Can't convert object to primitive value")},Ii=TypeError,yi=gi("toPrimitive"),Ai=function(e,t){if(!Ti(e)||Ri(e))return e;var i,n=Ci(e,yi);if(n){if(void 0===t&&(t="default"),i=Si(n,e,t),!Ti(i)||Ri(i))return i;throw Ii("Can't convert object to primitive value")}return void 0===t&&(t="number"),vi(e,t)},bi=Dt,wi=function(e){var t=Ai(e,"string");return bi(t)?t:t+""},Oi=at,Ni=ge.document,Di=Oi(Ni)&&Oi(Ni.createElement),Pi=function(e){return Di?Ni.createElement(e):{}},Li=Pi,ki=!Ue&&!de((function(){return 7!=Object.defineProperty(Li("div"),"a",{get:function(){return 7}}).a})),Mi=Ue,Ui=Fe,xi=Be,Vi=Ye,Fi=rt,Bi=wi,ji=ri,Gi=ki,Wi=Object.getOwnPropertyDescriptor;Me.f=Mi?Wi:function(e,t){if(e=Fi(e),t=Bi(t),Gi)try{return Wi(e,t)}catch(e){}if(ji(e,t))return Vi(!Ui(xi.f,e,t),e[t])};var Hi=de,Ki=ke,Yi=/#|\.prototype\./,qi=function(e,t){var i=zi[Ji(e)];return i==Qi||i!=Xi&&(Ki(t)?Hi(t):!!t)},Ji=qi.normalize=function(e){return String(e).replace(Yi,".").toLowerCase()},zi=qi.data={},Xi=qi.NATIVE="N",Qi=qi.POLYFILL="P",Zi=qi,$i=xt,en=le,tn=Ne(Ne.bind),nn=function(e,t){return $i(e),void 0===t?e:en?tn(e,t):function(){return e.apply(t,arguments)}},rn={},sn=Ue&&de((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),on=at,an=String,cn=TypeError,dn=function(e){if(on(e))return e;throw cn(an(e)+" is not an object")},ln=Ue,hn=ki,un=sn,pn=dn,_n=wi,En=TypeError,mn=Object.defineProperty,fn=Object.getOwnPropertyDescriptor,gn="enumerable",Sn="configurable",Tn="writable";rn.f=ln?un?function(e,t,i){if(pn(e),t=_n(t),pn(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Tn in i&&!i[Tn]){var n=fn(e,t);n&&n[Tn]&&(e[t]=i.value,i={configurable:Sn in i?i[Sn]:n[Sn],enumerable:gn in i?i[gn]:n[gn],writable:!1})}return mn(e,t,i)}:mn:function(e,t,i){if(pn(e),t=_n(t),pn(i),hn)try{return mn(e,t,i)}catch(e){}if("get"in i||"set"in i)throw En("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Rn=rn,Cn=Ye,vn=Ue?function(e,t,i){return Rn.f(e,t,Cn(1,i))}:function(e,t,i){return e[t]=i,e},In=ge,yn=ve,An=Ne,bn=ke,wn=Me.f,On=Zi,Nn=ct,Dn=nn,Pn=vn,Ln=ri,kn=function(e){var t=function(i,n,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(i);case 2:return new e(i,n)}return new e(i,n,r)}return yn(e,this,arguments)};return t.prototype=e.prototype,t},Mn=function(e,t){var i,n,r,s,o,a,c,d,l,h=e.target,u=e.global,p=e.stat,_=e.proto,E=u?In:p?In[h]:(In[h]||{}).prototype,m=u?Nn:Nn[h]||Pn(Nn,h,{})[h],f=m.prototype;for(s in t)n=!(i=On(u?s:h+(p?".":"#")+s,e.forced))&&E&&Ln(E,s),a=m[s],n&&(c=e.dontCallGetSet?(l=wn(E,s))&&l.value:E[s]),o=n&&c?c:t[s],n&&typeof a==typeof o||(d=e.bind&&n?Dn(o,In):e.wrap&&n?kn(o):_&&bn(o)?An(o):o,(e.sham||o&&o.sham||a&&a.sham)&&Pn(d,"sham",!0),Pn(m,s,d),_&&(Ln(Nn,r=h+"Prototype")||Pn(Nn,r,{}),Pn(Nn[r],s,o),e.real&&f&&(i||!f[s])&&Pn(f,s,o)))},Un=Math.ceil,xn=Math.floor,Vn=Math.trunc||function(e){var t=+e;return(t>0?xn:Un)(t)},Fn=function(e){var t=+e;return t!=t||0===t?0:Vn(t)},Bn=Fn,jn=Math.max,Gn=Math.min,Wn=function(e,t){var i=Bn(e);return i<0?jn(i+t,0):Gn(i,t)},Hn=Fn,Kn=Math.min,Yn=function(e){return e>0?Kn(Hn(e),9007199254740991):0},qn=function(e){return Yn(e.length)},Jn=rt,zn=Wn,Xn=qn,Qn=function(e){return function(t,i,n){var r,s=Jn(t),o=Xn(s),a=zn(n,o);if(e&&i!=i){for(;o>a;)if((r=s[a++])!=r)return!0}else for(;o>a;a++)if((e||a in s)&&s[a]===i)return e||a||0;return!e&&-1}},Zn={includes:Qn(!0),indexOf:Qn(!1)},$n=Zn.includes;Mn({target:"Array",proto:!0,forced:de((function(){return!Array(1).includes()}))},{includes:function(e){return $n(this,e,arguments.length>1?arguments[1]:void 0)}});var er=ct,tr=function(e){return er[e+"Prototype"]},ir=tr("Array").includes,nr=at,rr=be,sr=gi("match"),or=function(e){var t;return nr(e)&&(void 0!==(t=e[sr])?!!t:"RegExp"==rr(e))},ar=TypeError,cr={};cr[gi("toStringTag")]="z";var dr="[object z]"===String(cr),lr=dr,hr=ke,ur=be,pr=gi("toStringTag"),_r=Object,Er="Arguments"==ur(function(){return arguments}()),mr=lr?ur:function(e){var t,i,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=_r(e),pr))?i:Er?ur(t):"Object"==(n=ur(t))&&hr(t.callee)?"Arguments":n},fr=mr,gr=String,Sr=function(e){if("Symbol"===fr(e))throw TypeError("Cannot convert a Symbol value to a string");return gr(e)},Tr=gi("match"),Rr=Mn,Cr=function(e){if(or(e))throw ar("The method doesn't accept regular expressions");return e},vr=tt,Ir=Sr,yr=function(e){var t=/./;try{"/./"[e](t)}catch(i){try{return t[Tr]=!1,"/./"[e](t)}catch(e){}}return!1},Ar=Ee("".indexOf);Rr({target:"String",proto:!0,forced:!yr("includes")},{includes:function(e){return!!~Ar(Ir(vr(this)),Ir(Cr(e)),arguments.length>1?arguments[1]:void 0)}});var br=tr("String").includes,wr=me,Or=ir,Nr=br,Dr=Array.prototype,Pr=String.prototype,Lr=z((function(e){var t=e.includes;return e===Dr||wr(Dr,e)&&t===Dr.includes?Or:"string"==typeof e||e===Pr||wr(Pr,e)&&t===Pr.includes?Nr:t})),kr={exports:{}},Mr=Mn,Ur=Ue,xr=rn.f;Mr({target:"Object",stat:!0,forced:Object.defineProperty!==xr,sham:!Ur},{defineProperty:xr});var Vr=ct.Object,Fr=kr.exports=function(e,t,i){return Vr.defineProperty(e,t,i)};Vr.defineProperty.sham&&(Fr.sham=!0);var Br=z(kr.exports),jr=be,Gr=Array.isArray||function(e){return"Array"==jr(e)},Wr=TypeError,Hr=wi,Kr=rn,Yr=Ye,qr=function(e,t,i){var n=Hr(t);n in e?Kr.f(e,n,Yr(0,i)):e[n]=i},Jr=ke,zr=Xt,Xr=Ee(Function.toString);Jr(zr.inspectSource)||(zr.inspectSource=function(e){return Xr(e)});var Qr=zr.inspectSource,Zr=Ee,$r=de,es=ke,ts=mr,is=Qr,ns=function(){},rs=[],ss=pt("Reflect","construct"),os=/^\s*(?:class|function)\b/,as=Zr(os.exec),cs=!os.exec(ns),ds=function(e){if(!es(e))return!1;try{return ss(ns,rs,e),!0}catch(e){return!1}},ls=function(e){if(!es(e))return!1;switch(ts(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return cs||!!as(os,is(e))}catch(e){return!0}};ls.sham=!0;var hs=!ss||$r((function(){var e;return ds(ds.call)||!ds(Object)||!ds((function(){e=!0}))||e}))?ls:ds,us=Gr,ps=hs,_s=at,Es=gi("species"),ms=Array,fs=function(e){var t;return us(e)&&(t=e.constructor,(ps(t)&&(t===ms||us(t.prototype))||_s(t)&&null===(t=t[Es]))&&(t=void 0)),void 0===t?ms:t},gs=function(e,t){return new(fs(e))(0===t?0:t)},Ss=de,Ts=Rt,Rs=gi("species"),Cs=Mn,vs=de,Is=Gr,ys=at,As=ti,bs=qn,ws=function(e){if(e>9007199254740991)throw Wr("Maximum allowed index exceeded");return e},Os=qr,Ns=gs,Ds=function(e){return Ts>=51||!Ss((function(){var t=[];return(t.constructor={})[Rs]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},Ps=Rt,Ls=gi("isConcatSpreadable"),ks=Ps>=51||!vs((function(){var e=[];return e[Ls]=!1,e.concat()[0]!==e})),Ms=function(e){if(!ys(e))return!1;var t=e[Ls];return void 0!==t?!!t:Is(e)};Cs({target:"Array",proto:!0,arity:1,forced:!ks||!Ds("concat")},{concat:function(e){var t,i,n,r,s,o=As(this),a=Ns(o,0),c=0;for(t=-1,n=arguments.length;t<n;t++)if(Ms(s=-1===t?o:arguments[t]))for(r=bs(s),ws(c+r),i=0;i<r;i++,c++)i in s&&Os(a,c,s[i]);else ws(c+1),Os(a,c++,s);return a.length=c,a}});var Us={},xs={},Vs=ri,Fs=rt,Bs=Zn.indexOf,js=xs,Gs=Ee([].push),Ws=function(e,t){var i,n=Fs(e),r=0,s=[];for(i in n)!Vs(js,i)&&Vs(n,i)&&Gs(s,i);for(;t.length>r;)Vs(n,i=t[r++])&&(~Bs(s,i)||Gs(s,i));return s},Hs=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ks=Ws,Ys=Hs,qs=Object.keys||function(e){return Ks(e,Ys)},Js=Ue,zs=sn,Xs=rn,Qs=dn,Zs=rt,$s=qs;Us.f=Js&&!zs?Object.defineProperties:function(e,t){Qs(e);for(var i,n=Zs(t),r=$s(t),s=r.length,o=0;s>o;)Xs.f(e,i=r[o++],n[i]);return e};var eo,to=pt("document","documentElement"),io=di,no=Zt("keys"),ro=function(e){return no[e]||(no[e]=io(e))},so=dn,oo=Us,ao=Hs,co=xs,lo=to,ho=Pi,uo="prototype",po="script",_o=ro("IE_PROTO"),Eo=function(){},mo=function(e){return"<"+po+">"+e+"</"+po+">"},fo=function(e){e.write(mo("")),e.close();var t=e.parentWindow.Object;return e=null,t},go=function(){try{eo=new ActiveXObject("htmlfile")}catch(e){}var e,t,i;go="undefined"!=typeof document?document.domain&&eo?fo(eo):(t=ho("iframe"),i="java"+po+":",t.style.display="none",lo.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(mo("document.F=Object")),e.close(),e.F):fo(eo);for(var n=ao.length;n--;)delete go[uo][ao[n]];return go()};co[_o]=!0;var So=Object.create||function(e,t){var i;return null!==e?(Eo[uo]=so(e),i=new Eo,Eo[uo]=null,i[_o]=e):i=go(),void 0===t?i:oo.f(i,t)},To={},Ro=Ws,Co=Hs.concat("length","prototype");To.f=Object.getOwnPropertyNames||function(e){return Ro(e,Co)};var vo={},Io=Wn,yo=qn,Ao=qr,bo=Array,wo=Math.max,Oo=function(e,t,i){for(var n=yo(e),r=Io(t,n),s=Io(void 0===i?n:i,n),o=bo(wo(s-r,0)),a=0;r<s;r++,a++)Ao(o,a,e[r]);return o.length=a,o},No=be,Do=rt,Po=To.f,Lo=Oo,ko="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];vo.f=function(e){return ko&&"Window"==No(e)?function(e){try{return Po(e)}catch(e){return Lo(ko)}}(e):Po(Do(e))};var Mo={};Mo.f=Object.getOwnPropertySymbols;var Uo=vn,xo=function(e,t,i,n){return n&&n.enumerable?e[t]=i:Uo(e,t,i),e},Vo=rn,Fo=function(e,t,i){return Vo.f(e,t,i)},Bo={},jo=gi;Bo.f=jo;var Go,Wo,Ho,Ko=ct,Yo=ri,qo=Bo,Jo=rn.f,zo=function(e){var t=Ko.Symbol||(Ko.Symbol={});Yo(t,e)||Jo(t,e,{value:qo.f(e)})},Xo=Fe,Qo=pt,Zo=gi,$o=xo,ea=function(){var e=Qo("Symbol"),t=e&&e.prototype,i=t&&t.valueOf,n=Zo("toPrimitive");t&&!t[n]&&$o(t,n,(function(e){return Xo(i,this)}),{arity:1})},ta=mr,ia=dr?{}.toString:function(){return"[object "+ta(this)+"]"},na=dr,ra=rn.f,sa=vn,oa=ri,aa=ia,ca=gi("toStringTag"),da=function(e,t,i,n){if(e){var r=i?e:e.prototype;oa(r,ca)||ra(r,ca,{configurable:!0,value:t}),n&&!na&&sa(r,"toString",aa)}},la=ke,ha=ge.WeakMap,ua=la(ha)&&/native code/.test(String(ha)),pa=ge,_a=at,Ea=vn,ma=ri,fa=Xt,ga=ro,Sa=xs,Ta="Object already initialized",Ra=pa.TypeError,Ca=pa.WeakMap;if(ua||fa.state){var va=fa.state||(fa.state=new Ca);va.get=va.get,va.has=va.has,va.set=va.set,Go=function(e,t){if(va.has(e))throw Ra(Ta);return t.facade=e,va.set(e,t),t},Wo=function(e){return va.get(e)||{}},Ho=function(e){return va.has(e)}}else{var Ia=ga("state");Sa[Ia]=!0,Go=function(e,t){if(ma(e,Ia))throw Ra(Ta);return t.facade=e,Ea(e,Ia,t),t},Wo=function(e){return ma(e,Ia)?e[Ia]:{}},Ho=function(e){return ma(e,Ia)}}var ya={set:Go,get:Wo,has:Ho,enforce:function(e){return Ho(e)?Wo(e):Go(e,{})},getterFor:function(e){return function(t){var i;if(!_a(t)||(i=Wo(t)).type!==e)throw Ra("Incompatible receiver, "+e+" required");return i}}},Aa=nn,ba=Qe,wa=ti,Oa=qn,Na=gs,Da=Ee([].push),Pa=function(e){var t=1==e,i=2==e,n=3==e,r=4==e,s=6==e,o=7==e,a=5==e||s;return function(c,d,l,h){for(var u,p,_=wa(c),E=ba(_),m=Aa(d,l),f=Oa(E),g=0,S=h||Na,T=t?S(c,f):i||o?S(c,0):void 0;f>g;g++)if((a||g in E)&&(p=m(u=E[g],g,_),e))if(t)T[g]=p;else if(p)switch(e){case 3:return!0;case 5:return u;case 6:return g;case 2:Da(T,u)}else switch(e){case 4:return!1;case 7:Da(T,u)}return s?-1:n||r?r:T}},La={forEach:Pa(0),map:Pa(1),filter:Pa(2),some:Pa(3),every:Pa(4),find:Pa(5),findIndex:Pa(6),filterReject:Pa(7)},ka=Mn,Ma=ge,Ua=Fe,xa=Ee,Va=Ue,Fa=yt,Ba=de,ja=ri,Ga=me,Wa=dn,Ha=rt,Ka=wi,Ya=Sr,qa=Ye,Ja=So,za=qs,Xa=To,Qa=vo,Za=Mo,$a=Me,ec=rn,tc=Us,ic=Be,nc=xo,rc=Fo,sc=Zt,oc=xs,ac=di,cc=gi,dc=Bo,lc=zo,hc=ea,uc=da,pc=ya,_c=La.forEach,Ec=ro("hidden"),mc="Symbol",fc="prototype",gc=pc.set,Sc=pc.getterFor(mc),Tc=Object[fc],Rc=Ma.Symbol,Cc=Rc&&Rc[fc],vc=Ma.TypeError,Ic=Ma.QObject,yc=$a.f,Ac=ec.f,bc=Qa.f,wc=ic.f,Oc=xa([].push),Nc=sc("symbols"),Dc=sc("op-symbols"),Pc=sc("wks"),Lc=!Ic||!Ic[fc]||!Ic[fc].findChild,kc=Va&&Ba((function(){return 7!=Ja(Ac({},"a",{get:function(){return Ac(this,"a",{value:7}).a}})).a}))?function(e,t,i){var n=yc(Tc,t);n&&delete Tc[t],Ac(e,t,i),n&&e!==Tc&&Ac(Tc,t,n)}:Ac,Mc=function(e,t){var i=Nc[e]=Ja(Cc);return gc(i,{type:mc,tag:e,description:t}),Va||(i.description=t),i},Uc=function(e,t,i){e===Tc&&Uc(Dc,t,i),Wa(e);var n=Ka(t);return Wa(i),ja(Nc,n)?(i.enumerable?(ja(e,Ec)&&e[Ec][n]&&(e[Ec][n]=!1),i=Ja(i,{enumerable:qa(0,!1)})):(ja(e,Ec)||Ac(e,Ec,qa(1,{})),e[Ec][n]=!0),kc(e,n,i)):Ac(e,n,i)},xc=function(e,t){Wa(e);var i=Ha(t),n=za(i).concat(jc(i));return _c(n,(function(t){Va&&!Ua(Vc,i,t)||Uc(e,t,i[t])})),e},Vc=function(e){var t=Ka(e),i=Ua(wc,this,t);return!(this===Tc&&ja(Nc,t)&&!ja(Dc,t))&&(!(i||!ja(this,t)||!ja(Nc,t)||ja(this,Ec)&&this[Ec][t])||i)},Fc=function(e,t){var i=Ha(e),n=Ka(t);if(i!==Tc||!ja(Nc,n)||ja(Dc,n)){var r=yc(i,n);return!r||!ja(Nc,n)||ja(i,Ec)&&i[Ec][n]||(r.enumerable=!0),r}},Bc=function(e){var t=bc(Ha(e)),i=[];return _c(t,(function(e){ja(Nc,e)||ja(oc,e)||Oc(i,e)})),i},jc=function(e){var t=e===Tc,i=bc(t?Dc:Ha(e)),n=[];return _c(i,(function(e){!ja(Nc,e)||t&&!ja(Tc,e)||Oc(n,Nc[e])})),n};Fa||(Rc=function(){if(Ga(Cc,this))throw vc("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?Ya(arguments[0]):void 0,t=ac(e),i=function(e){this===Tc&&Ua(i,Dc,e),ja(this,Ec)&&ja(this[Ec],t)&&(this[Ec][t]=!1),kc(this,t,qa(1,e))};return Va&&Lc&&kc(Tc,t,{configurable:!0,set:i}),Mc(t,e)},nc(Cc=Rc[fc],"toString",(function(){return Sc(this).tag})),nc(Rc,"withoutSetter",(function(e){return Mc(ac(e),e)})),ic.f=Vc,ec.f=Uc,tc.f=xc,$a.f=Fc,Xa.f=Qa.f=Bc,Za.f=jc,dc.f=function(e){return Mc(cc(e),e)},Va&&rc(Cc,"description",{configurable:!0,get:function(){return Sc(this).description}})),ka({global:!0,constructor:!0,wrap:!0,forced:!Fa,sham:!Fa},{Symbol:Rc}),_c(za(Pc),(function(e){lc(e)})),ka({target:mc,stat:!0,forced:!Fa},{useSetter:function(){Lc=!0},useSimple:function(){Lc=!1}}),ka({target:"Object",stat:!0,forced:!Fa,sham:!Va},{create:function(e,t){return void 0===t?Ja(e):xc(Ja(e),t)},defineProperty:Uc,defineProperties:xc,getOwnPropertyDescriptor:Fc}),ka({target:"Object",stat:!0,forced:!Fa},{getOwnPropertyNames:Bc}),hc(),uc(Rc,mc),oc[Ec]=!0;var Gc=yt&&!!Symbol.for&&!!Symbol.keyFor,Wc=Mn,Hc=pt,Kc=ri,Yc=Sr,qc=Zt,Jc=Gc,zc=qc("string-to-symbol-registry"),Xc=qc("symbol-to-string-registry");Wc({target:"Symbol",stat:!0,forced:!Jc},{for:function(e){var t=Yc(e);if(Kc(zc,t))return zc[t];var i=Hc("Symbol")(t);return zc[t]=i,Xc[i]=t,i}});var Qc=Mn,Zc=ri,$c=Dt,ed=Lt,td=Gc,id=Zt("symbol-to-string-registry");Qc({target:"Symbol",stat:!0,forced:!td},{keyFor:function(e){if(!$c(e))throw TypeError(ed(e)+" is not a symbol");if(Zc(id,e))return id[e]}});var nd=Ee([].slice),rd=Gr,sd=ke,od=be,ad=Sr,cd=Ee([].push),dd=Mn,ld=pt,hd=ve,ud=Fe,pd=Ee,_d=de,Ed=ke,md=Dt,fd=nd,gd=function(e){if(sd(e))return e;if(rd(e)){for(var t=e.length,i=[],n=0;n<t;n++){var r=e[n];"string"==typeof r?cd(i,r):"number"!=typeof r&&"Number"!=od(r)&&"String"!=od(r)||cd(i,ad(r))}var s=i.length,o=!0;return function(e,t){if(o)return o=!1,t;if(rd(this))return t;for(var n=0;n<s;n++)if(i[n]===e)return t}}},Sd=yt,Td=String,Rd=ld("JSON","stringify"),Cd=pd(/./.exec),vd=pd("".charAt),Id=pd("".charCodeAt),yd=pd("".replace),Ad=pd(1..toString),bd=/[\uD800-\uDFFF]/g,wd=/^[\uD800-\uDBFF]$/,Od=/^[\uDC00-\uDFFF]$/,Nd=!Sd||_d((function(){var e=ld("Symbol")();return"[null]"!=Rd([e])||"{}"!=Rd({a:e})||"{}"!=Rd(Object(e))})),Dd=_d((function(){return'"\\udf06\\ud834"'!==Rd("\udf06\ud834")||'"\\udead"'!==Rd("\udead")})),Pd=function(e,t){var i=fd(arguments),n=gd(t);if(Ed(n)||void 0!==e&&!md(e))return i[1]=function(e,t){if(Ed(n)&&(t=ud(n,this,Td(e),t)),!md(t))return t},hd(Rd,null,i)},Ld=function(e,t,i){var n=vd(i,t-1),r=vd(i,t+1);return Cd(wd,e)&&!Cd(Od,r)||Cd(Od,e)&&!Cd(wd,n)?"\\u"+Ad(Id(e,0),16):e};Rd&&dd({target:"JSON",stat:!0,arity:3,forced:Nd||Dd},{stringify:function(e,t,i){var n=fd(arguments),r=hd(Nd?Pd:Rd,null,n);return Dd&&"string"==typeof r?yd(r,bd,Ld):r}});var kd=Mo,Md=ti;Mn({target:"Object",stat:!0,forced:!yt||de((function(){kd.f(1)}))},{getOwnPropertySymbols:function(e){var t=kd.f;return t?t(Md(e)):[]}}),zo("asyncIterator"),zo("hasInstance"),zo("isConcatSpreadable"),zo("iterator"),zo("match"),zo("matchAll"),zo("replace"),zo("search"),zo("species"),zo("split");var Ud=ea;zo("toPrimitive"),Ud();var xd=pt,Vd=da;zo("toStringTag"),Vd(xd("Symbol"),"Symbol"),zo("unscopables"),da(ge.JSON,"JSON",!0);var Fd,Bd,jd,Gd=ct.Symbol,Wd={},Hd=Ue,Kd=ri,Yd=Function.prototype,qd=Hd&&Object.getOwnPropertyDescriptor,Jd=Kd(Yd,"name"),zd={EXISTS:Jd,PROPER:Jd&&"something"===function(){}.name,CONFIGURABLE:Jd&&(!Hd||Hd&&qd(Yd,"name").configurable)},Xd=!de((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Qd=ri,Zd=ke,$d=ti,el=Xd,tl=ro("IE_PROTO"),il=Object,nl=il.prototype,rl=el?il.getPrototypeOf:function(e){var t=$d(e);if(Qd(t,tl))return t[tl];var i=t.constructor;return Zd(i)&&t instanceof i?i.prototype:t instanceof il?nl:null},sl=de,ol=ke,al=at,cl=So,dl=rl,ll=xo,hl=gi("iterator"),ul=!1;[].keys&&("next"in(jd=[].keys())?(Bd=dl(dl(jd)))!==Object.prototype&&(Fd=Bd):ul=!0);var pl=!al(Fd)||sl((function(){var e={};return Fd[hl].call(e)!==e}));ol((Fd=pl?{}:cl(Fd))[hl])||ll(Fd,hl,(function(){return this}));var _l={IteratorPrototype:Fd,BUGGY_SAFARI_ITERATORS:ul},El=_l.IteratorPrototype,ml=So,fl=Ye,gl=da,Sl=Wd,Tl=function(){return this},Rl=Ee,Cl=xt,vl=ke,Il=String,yl=TypeError,Al=function(e,t,i){try{return Rl(Cl(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(e){}},bl=dn,wl=function(e){if("object"==typeof e||vl(e))return e;throw yl("Can't set "+Il(e)+" as a prototype")},Ol=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Al(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(e){}return function(i,n){return bl(i),wl(n),t?e(i,n):i.__proto__=n,i}}():void 0),Nl=Mn,Dl=Fe,Pl=function(e,t,i,n){var r=t+" Iterator";return e.prototype=ml(El,{next:fl(+!n,i)}),gl(e,r,!1,!0),Sl[r]=Tl,e},Ll=rl,kl=da,Ml=xo,Ul=Wd,xl=_l,Vl=zd.PROPER,Fl=xl.BUGGY_SAFARI_ITERATORS,Bl=gi("iterator"),jl="keys",Gl="values",Wl="entries",Hl=function(){return this},Kl=function(e,t,i,n,r,s,o){Pl(i,t,n);var a,c,d,l=function(e){if(e===r&&E)return E;if(!Fl&&e in p)return p[e];switch(e){case jl:case Gl:case Wl:return function(){return new i(this,e)}}return function(){return new i(this)}},h=t+" Iterator",u=!1,p=e.prototype,_=p[Bl]||p["@@iterator"]||r&&p[r],E=!Fl&&_||l(r),m="Array"==t&&p.entries||_;if(m&&(a=Ll(m.call(new e)))!==Object.prototype&&a.next&&(kl(a,h,!0,!0),Ul[h]=Hl),Vl&&r==Gl&&_&&_.name!==Gl&&(u=!0,E=function(){return Dl(_,this)}),r)if(c={values:l(Gl),keys:s?E:l(jl),entries:l(Wl)},o)for(d in c)(Fl||u||!(d in p))&&Ml(p,d,c[d]);else Nl({target:t,proto:!0,forced:Fl||u},c);return o&&p[Bl]!==E&&Ml(p,Bl,E,{name:r}),Ul[t]=E,c},Yl=function(e,t){return{value:e,done:t}},ql=rt,Jl=Wd,zl=ya;rn.f;var Xl=Kl,Ql=Yl,Zl="Array Iterator",$l=zl.set,eh=zl.getterFor(Zl);Xl(Array,"Array",(function(e,t){$l(this,{type:Zl,target:ql(e),index:0,kind:t})}),(function(){var e=eh(this),t=e.target,i=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,Ql(void 0,!0)):Ql("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1)}),"values"),Jl.Arguments=Jl.Array;var th={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},ih=ge,nh=mr,rh=vn,sh=Wd,oh=gi("toStringTag");for(var ah in th){var ch=ih[ah],dh=ch&&ch.prototype;dh&&nh(dh)!==oh&&rh(dh,oh,ah),sh[ah]=sh.Array}var lh=Gd,hh=gi,uh=rn.f,ph=hh("metadata"),_h=Function.prototype;void 0===_h[ph]&&uh(_h,ph,{value:null}),zo("dispose"),zo("metadata");var Eh=lh;zo("asyncDispose");var mh=Ee,fh=pt("Symbol"),gh=fh.keyFor,Sh=mh(fh.prototype.valueOf),Th=fh.isRegisteredSymbol||function(e){try{return void 0!==gh(Sh(e))}catch(e){return!1}};Mn({target:"Symbol",stat:!0},{isRegisteredSymbol:Th});for(var Rh=Zt,Ch=pt,vh=Ee,Ih=Dt,yh=gi,Ah=Ch("Symbol"),bh=Ah.isWellKnownSymbol,wh=Ch("Object","getOwnPropertyNames"),Oh=vh(Ah.prototype.valueOf),Nh=Rh("wks"),Dh=0,Ph=wh(Ah),Lh=Ph.length;Dh<Lh;Dh++)try{var kh=Ph[Dh];Ih(Ah[kh])&&yh(kh)}catch(t){}var Mh=function(e){if(bh&&bh(e))return!0;try{for(var t=Oh(e),i=0,n=wh(Nh),r=n.length;i<r;i++)if(Nh[n[i]]==t)return!0}catch(e){}return!1};Mn({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:Mh}),zo("matcher"),zo("observable"),Mn({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:Th}),Mn({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:Mh}),zo("metadataKey"),zo("patternMatch"),zo("replaceAll");var Uh=z(Eh),xh=Ee,Vh=Fn,Fh=Sr,Bh=tt,jh=xh("".charAt),Gh=xh("".charCodeAt),Wh=xh("".slice),Hh=function(e){return function(t,i){var n,r,s=Fh(Bh(t)),o=Vh(i),a=s.length;return o<0||o>=a?e?"":void 0:(n=Gh(s,o))<55296||n>56319||o+1===a||(r=Gh(s,o+1))<56320||r>57343?e?jh(s,o):n:e?Wh(s,o,o+2):r-56320+(n-55296<<10)+65536}},Kh=(Hh(!1),Hh(!0)),Yh=Sr,qh=ya,Jh=Kl,zh=Yl,Xh="String Iterator",Qh=qh.set,Zh=qh.getterFor(Xh);Jh(String,"String",(function(e){Qh(this,{type:Xh,string:Yh(e),index:0})}),(function(){var e,t=Zh(this),i=t.string,n=t.index;return n>=i.length?zh(void 0,!0):(e=Kh(i,n),t.index+=e.length,zh(e,!1))}));var $h=z(Bo.f("iterator"));function eu(e){return eu="function"==typeof Uh&&"symbol"==typeof $h?function(e){return typeof e}:function(e){return e&&"function"==typeof Uh&&e.constructor===Uh&&e!==Uh.prototype?"symbol":typeof e},eu(e)}var tu=z(Bo.f("toPrimitive"));function iu(e){var t=function(e,t){if("object"!==eu(e)||null===e)return e;var i=e[tu];if(void 0!==i){var n=i.call(e,t||"default");if("object"!==eu(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===eu(t)?t:String(t)}function nu(e,t,i){return(t=iu(t))in e?Br(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var ru=tr("Array").keys,su=mr,ou=ri,au=me,cu=ru,du=Array.prototype,lu={DOMTokenList:!0,NodeList:!0},hu=z((function(e){var t=e.keys;return e===du||au(du,e)&&t===du.keys||ou(lu,su(e))?cu:t})),uu=Lt,pu=TypeError,_u=Oo,Eu=Math.floor,mu=function(e,t){var i=e.length,n=Eu(i/2);return i<8?fu(e,t):gu(e,mu(_u(e,0,n),t),mu(_u(e,n),t),t)},fu=function(e,t){for(var i,n,r=e.length,s=1;s<r;){for(n=s,i=e[s];n&&t(e[n-1],i)>0;)e[n]=e[--n];n!==s++&&(e[n]=i)}return e},gu=function(e,t,i,n){for(var r=t.length,s=i.length,o=0,a=0;o<r||a<s;)e[o+a]=o<r&&a<s?n(t[o],i[a])<=0?t[o++]:i[a++]:o<r?t[o++]:i[a++];return e},Su=mu,Tu=de,Ru=function(e,t){var i=[][e];return!!i&&Tu((function(){i.call(null,t||function(){return 1},1)}))},Cu=_t.match(/firefox\/(\d+)/i),vu=!!Cu&&+Cu[1],Iu=/MSIE|Trident/.test(_t),yu=_t.match(/AppleWebKit\/(\d+)\./),Au=!!yu&&+yu[1],bu=Mn,wu=Ee,Ou=xt,Nu=ti,Du=qn,Pu=function(e,t){if(!delete e[t])throw pu("Cannot delete property "+uu(t)+" of "+uu(e))},Lu=Sr,ku=de,Mu=Su,Uu=Ru,xu=vu,Vu=Iu,Fu=Rt,Bu=Au,ju=[],Gu=wu(ju.sort),Wu=wu(ju.push),Hu=ku((function(){ju.sort(void 0)})),Ku=ku((function(){ju.sort(null)})),Yu=Uu("sort"),qu=!ku((function(){if(Fu)return Fu<70;if(!(xu&&xu>3)){if(Vu)return!0;if(Bu)return Bu<603;var e,t,i,n,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(n=0;n<47;n++)ju.push({k:t+n,v:i})}for(ju.sort((function(e,t){return t.v-e.v})),n=0;n<ju.length;n++)t=ju[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));bu({target:"Array",proto:!0,forced:Hu||!Ku||!Yu||!qu},{sort:function(e){void 0!==e&&Ou(e);var t=Nu(this);if(qu)return void 0===e?Gu(t):Gu(t,e);var i,n,r=[],s=Du(t);for(n=0;n<s;n++)n in t&&Wu(r,t[n]);for(Mu(r,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Lu(t)>Lu(i)?1:-1}}(e)),i=Du(r),n=0;n<i;)t[n]=r[n++];for(;n<s;)Pu(t,n++);return t}});var Ju=tr("Array").sort,zu=me,Xu=Ju,Qu=Array.prototype,Zu=z((function(e){var t=e.sort;return e===Qu||zu(Qu,e)&&t===Qu.sort?Xu:t})),$u=pt,ep=To,tp=Mo,ip=dn,np=Ee([].concat),rp=$u("Reflect","ownKeys")||function(e){var t=ep.f(ip(e)),i=tp.f;return i?np(t,i(e)):t},sp=ri,op=rp,ap=Me,cp=rn,dp=at,lp=vn,hp=Error,up=Ee("".replace),pp=String(hp("zxcasd").stack),_p=/\n\s*at [^:]*:[^\n]*/,Ep=_p.test(pp),mp=Ye,fp=!de((function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",mp(1,7)),7!==e.stack)})),gp=vn,Sp=function(e,t){if(Ep&&"string"==typeof e&&!hp.prepareStackTrace)for(;t--;)e=up(e,_p,"");return e},Tp=fp,Rp=Error.captureStackTrace,Cp=Wd,vp=gi("iterator"),Ip=Array.prototype,yp=mr,Ap=Bt,bp=Ze,wp=Wd,Op=gi("iterator"),Np=function(e){if(!bp(e))return Ap(e,Op)||Ap(e,"@@iterator")||wp[yp(e)]},Dp=Fe,Pp=xt,Lp=dn,kp=Lt,Mp=Np,Up=TypeError,xp=Fe,Vp=dn,Fp=Bt,Bp=nn,jp=Fe,Gp=dn,Wp=Lt,Hp=function(e){return void 0!==e&&(Cp.Array===e||Ip[vp]===e)},Kp=qn,Yp=me,qp=function(e,t){var i=arguments.length<2?Mp(e):t;if(Pp(i))return Lp(Dp(i,e));throw Up(kp(e)+" is not iterable")},Jp=Np,zp=function(e,t,i){var n,r;Vp(e);try{if(!(n=Fp(e,"return"))){if("throw"===t)throw i;return i}n=xp(n,e)}catch(e){r=!0,n=e}if("throw"===t)throw i;if(r)throw n;return Vp(n),i},Xp=TypeError,Qp=function(e,t){this.stopped=e,this.result=t},Zp=Qp.prototype,$p=function(e,t,i){var n,r,s,o,a,c,d,l=i&&i.that,h=!(!i||!i.AS_ENTRIES),u=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),_=!(!i||!i.INTERRUPTED),E=Bp(t,l),m=function(e){return n&&zp(n,"normal",e),new Qp(!0,e)},f=function(e){return h?(Gp(e),_?E(e[0],e[1],m):E(e[0],e[1])):_?E(e,m):E(e)};if(u)n=e.iterator;else if(p)n=e;else{if(!(r=Jp(e)))throw Xp(Wp(e)+" is not iterable");if(Hp(r)){for(s=0,o=Kp(e);o>s;s++)if((a=f(e[s]))&&Yp(Zp,a))return a;return new Qp(!1)}n=qp(e,r)}for(c=u?e.next:n.next;!(d=jp(c,n)).done;){try{a=f(d.value)}catch(e){zp(n,"throw",e)}if("object"==typeof a&&a&&Yp(Zp,a))return a}return new Qp(!1)},e_=Sr,t_=Mn,i_=me,n_=rl,r_=Ol,s_=function(e,t,i){for(var n=op(t),r=cp.f,s=ap.f,o=0;o<n.length;o++){var a=n[o];sp(e,a)||i&&sp(i,a)||r(e,a,s(t,a))}},o_=So,a_=vn,c_=Ye,d_=function(e,t){dp(t)&&"cause"in t&&lp(e,"cause",t.cause)},l_=function(e,t,i,n){Tp&&(Rp?Rp(e,t):gp(e,"stack",Sp(i,n)))},h_=$p,u_=function(e,t){return void 0===e?arguments.length<2?"":t:e_(e)},p_=gi("toStringTag"),__=Error,E_=[].push,m_=function(e,t){var i,n=i_(f_,this);r_?i=r_(__(),n?n_(this):f_):(i=n?this:o_(f_),a_(i,p_,"Error")),void 0!==t&&a_(i,"message",u_(t)),l_(i,m_,i.stack,1),arguments.length>2&&d_(i,arguments[2]);var r=[];return h_(e,E_,{that:r}),a_(i,"errors",r),i};r_?r_(m_,__):s_(m_,__,{name:!0});var f_=m_.prototype=o_(__.prototype,{constructor:c_(1,m_),message:c_(1,""),name:c_(1,"AggregateError")});t_({global:!0,constructor:!0,arity:2},{AggregateError:m_});var g_,S_,T_,R_,C_="undefined"!=typeof process&&"process"==be(process),v_=pt,I_=Fo,y_=Ue,A_=gi("species"),b_=me,w_=TypeError,O_=hs,N_=Lt,D_=TypeError,P_=dn,L_=function(e){if(O_(e))return e;throw D_(N_(e)+" is not a constructor")},k_=Ze,M_=gi("species"),U_=function(e,t){var i,n=P_(e).constructor;return void 0===n||k_(i=P_(n)[M_])?t:L_(i)},x_=TypeError,V_=/(?:ipad|iphone|ipod).*applewebkit/i.test(_t),F_=ge,B_=ve,j_=nn,G_=ke,W_=ri,H_=de,K_=to,Y_=nd,q_=Pi,J_=function(e,t){if(e<t)throw x_("Not enough arguments");return e},z_=V_,X_=C_,Q_=F_.setImmediate,Z_=F_.clearImmediate,$_=F_.process,eE=F_.Dispatch,tE=F_.Function,iE=F_.MessageChannel,nE=F_.String,rE=0,sE={},oE="onreadystatechange";H_((function(){g_=F_.location}));var aE=function(e){if(W_(sE,e)){var t=sE[e];delete sE[e],t()}},cE=function(e){return function(){aE(e)}},dE=function(e){aE(e.data)},lE=function(e){F_.postMessage(nE(e),g_.protocol+"//"+g_.host)};Q_&&Z_||(Q_=function(e){J_(arguments.length,1);var t=G_(e)?e:tE(e),i=Y_(arguments,1);return sE[++rE]=function(){B_(t,void 0,i)},S_(rE),rE},Z_=function(e){delete sE[e]},X_?S_=function(e){$_.nextTick(cE(e))}:eE&&eE.now?S_=function(e){eE.now(cE(e))}:iE&&!z_?(R_=(T_=new iE).port2,T_.port1.onmessage=dE,S_=j_(R_.postMessage,R_)):F_.addEventListener&&G_(F_.postMessage)&&!F_.importScripts&&g_&&"file:"!==g_.protocol&&!H_(lE)?(S_=lE,F_.addEventListener("message",dE,!1)):S_=oE in q_("script")?function(e){K_.appendChild(q_("script"))[oE]=function(){K_.removeChild(this),aE(e)}}:function(e){setTimeout(cE(e),0)});var hE={set:Q_,clear:Z_},uE=function(){this.head=null,this.tail=null};uE.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var pE,_E,EE,mE,fE,gE=uE,SE=/ipad|iphone|ipod/i.test(_t)&&"undefined"!=typeof Pebble,TE=/web0s(?!.*chrome)/i.test(_t),RE=ge,CE=nn,vE=Me.f,IE=hE.set,yE=gE,AE=V_,bE=SE,wE=TE,OE=C_,NE=RE.MutationObserver||RE.WebKitMutationObserver,DE=RE.document,PE=RE.process,LE=RE.Promise,kE=vE(RE,"queueMicrotask"),ME=kE&&kE.value;if(!ME){var UE=new yE,xE=function(){var e,t;for(OE&&(e=PE.domain)&&e.exit();t=UE.get();)try{t()}catch(e){throw UE.head&&pE(),e}e&&e.enter()};AE||OE||wE||!NE||!DE?!bE&&LE&&LE.resolve?((mE=LE.resolve(void 0)).constructor=LE,fE=CE(mE.then,mE),pE=function(){fE(xE)}):OE?pE=function(){PE.nextTick(xE)}:(IE=CE(IE,RE),pE=function(){IE(xE)}):(_E=!0,EE=DE.createTextNode(""),new NE(xE).observe(EE,{characterData:!0}),pE=function(){EE.data=_E=!_E}),ME=function(e){UE.head||pE(),UE.add(e)}}var VE=ME,FE=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},BE=ge.Promise,jE="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,GE=!jE&&!C_&&"object"==typeof window&&"object"==typeof document,WE=ge,HE=BE,KE=ke,YE=Zi,qE=Qr,JE=gi,zE=GE,XE=jE,QE=Rt,ZE=HE&&HE.prototype,$E=JE("species"),em=!1,tm=KE(WE.PromiseRejectionEvent),im=YE("Promise",(function(){var e=qE(HE),t=e!==String(HE);if(!t&&66===QE)return!0;if(!ZE.catch||!ZE.finally)return!0;if(!QE||QE<51||!/native code/.test(e)){var i=new HE((function(e){e(1)})),n=function(e){e((function(){}),(function(){}))};if((i.constructor={})[$E]=n,!(em=i.then((function(){}))instanceof n))return!0}return!t&&(zE||XE)&&!tm})),nm={CONSTRUCTOR:im,REJECTION_EVENT:tm,SUBCLASSING:em},rm={},sm=xt,om=TypeError,am=function(e){var t,i;this.promise=new e((function(e,n){if(void 0!==t||void 0!==i)throw om("Bad Promise constructor");t=e,i=n})),this.resolve=sm(t),this.reject=sm(i)};rm.f=function(e){return new am(e)};var cm,dm,lm=Mn,hm=C_,um=ge,pm=Fe,_m=xo,Em=da,mm=function(e){var t=v_(e);y_&&t&&!t[A_]&&I_(t,A_,{configurable:!0,get:function(){return this}})},fm=xt,gm=ke,Sm=at,Tm=function(e,t){if(b_(t,e))return e;throw w_("Incorrect invocation")},Rm=U_,Cm=hE.set,vm=VE,Im=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(e){}},ym=FE,Am=gE,bm=ya,wm=BE,Om=nm,Nm=rm,Dm="Promise",Pm=Om.CONSTRUCTOR,Lm=Om.REJECTION_EVENT,km=bm.getterFor(Dm),Mm=bm.set,Um=wm&&wm.prototype,xm=wm,Vm=Um,Fm=um.TypeError,Bm=um.document,jm=um.process,Gm=Nm.f,Wm=Gm,Hm=!!(Bm&&Bm.createEvent&&um.dispatchEvent),Km="unhandledrejection",Ym=function(e){var t;return!(!Sm(e)||!gm(t=e.then))&&t},qm=function(e,t){var i,n,r,s=t.value,o=1==t.state,a=o?e.ok:e.fail,c=e.resolve,d=e.reject,l=e.domain;try{a?(o||(2===t.rejection&&Zm(t),t.rejection=1),!0===a?i=s:(l&&l.enter(),i=a(s),l&&(l.exit(),r=!0)),i===e.promise?d(Fm("Promise-chain cycle")):(n=Ym(i))?pm(n,i,c,d):c(i)):d(s)}catch(e){l&&!r&&l.exit(),d(e)}},Jm=function(e,t){e.notified||(e.notified=!0,vm((function(){for(var i,n=e.reactions;i=n.get();)qm(i,e);e.notified=!1,t&&!e.rejection&&Xm(e)})))},zm=function(e,t,i){var n,r;Hm?((n=Bm.createEvent("Event")).promise=t,n.reason=i,n.initEvent(e,!1,!0),um.dispatchEvent(n)):n={promise:t,reason:i},!Lm&&(r=um["on"+e])?r(n):e===Km&&Im("Unhandled promise rejection",i)},Xm=function(e){pm(Cm,um,(function(){var t,i=e.facade,n=e.value;if(Qm(e)&&(t=ym((function(){hm?jm.emit("unhandledRejection",n,i):zm(Km,i,n)})),e.rejection=hm||Qm(e)?2:1,t.error))throw t.value}))},Qm=function(e){return 1!==e.rejection&&!e.parent},Zm=function(e){pm(Cm,um,(function(){var t=e.facade;hm?jm.emit("rejectionHandled",t):zm("rejectionhandled",t,e.value)}))},$m=function(e,t,i){return function(n){e(t,n,i)}},ef=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Jm(e,!0))},tf=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw Fm("Promise can't be resolved itself");var n=Ym(t);n?vm((function(){var i={done:!1};try{pm(n,t,$m(tf,i,e),$m(ef,i,e))}catch(t){ef(i,t,e)}})):(e.value=t,e.state=1,Jm(e,!1))}catch(t){ef({done:!1},t,e)}}};Pm&&(Vm=(xm=function(e){Tm(this,Vm),fm(e),pm(cm,this);var t=km(this);try{e($m(tf,t),$m(ef,t))}catch(e){ef(t,e)}}).prototype,(cm=function(e){Mm(this,{type:Dm,done:!1,notified:!1,parent:!1,reactions:new Am,rejection:!1,state:0,value:void 0})}).prototype=_m(Vm,"then",(function(e,t){var i=km(this),n=Gm(Rm(this,xm));return i.parent=!0,n.ok=!gm(e)||e,n.fail=gm(t)&&t,n.domain=hm?jm.domain:void 0,0==i.state?i.reactions.add(n):vm((function(){qm(n,i)})),n.promise})),dm=function(){var e=new cm,t=km(e);this.promise=e,this.resolve=$m(tf,t),this.reject=$m(ef,t)},Nm.f=Gm=function(e){return e===xm||void 0===e?new dm(e):Wm(e)}),lm({global:!0,constructor:!0,wrap:!0,forced:Pm},{Promise:xm}),Em(xm,Dm,!1,!0),mm(Dm);var nf=gi("iterator"),rf=!1;try{var sf=0,of={next:function(){return{done:!!sf++}},return:function(){rf=!0}};of[nf]=function(){return this},Array.from(of,(function(){throw 2}))}catch(t){}var af=BE,cf=function(e,t){if(!t&&!rf)return!1;var i=!1;try{var n={};n[nf]=function(){return{next:function(){return{done:i=!0}}}},e(n)}catch(e){}return i},df=nm.CONSTRUCTOR||!cf((function(e){af.all(e).then(void 0,(function(){}))})),lf=Fe,hf=xt,uf=rm,pf=FE,_f=$p;Mn({target:"Promise",stat:!0,forced:df},{all:function(e){var t=this,i=uf.f(t),n=i.resolve,r=i.reject,s=pf((function(){var i=hf(t.resolve),s=[],o=0,a=1;_f(e,(function(e){var c=o++,d=!1;a++,lf(i,t,e).then((function(e){d||(d=!0,s[c]=e,--a||n(s))}),r)})),--a||n(s)}));return s.error&&r(s.value),i.promise}});var Ef=Mn,mf=nm.CONSTRUCTOR;BE&&BE.prototype,Ef({target:"Promise",proto:!0,forced:mf,real:!0},{catch:function(e){return this.then(void 0,e)}});var ff=Fe,gf=xt,Sf=rm,Tf=FE,Rf=$p;Mn({target:"Promise",stat:!0,forced:df},{race:function(e){var t=this,i=Sf.f(t),n=i.reject,r=Tf((function(){var r=gf(t.resolve);Rf(e,(function(e){ff(r,t,e).then(i.resolve,n)}))}));return r.error&&n(r.value),i.promise}});var Cf=Fe,vf=rm;Mn({target:"Promise",stat:!0,forced:nm.CONSTRUCTOR},{reject:function(e){var t=vf.f(this);return Cf(t.reject,void 0,e),t.promise}});var If=dn,yf=at,Af=rm,bf=function(e,t){if(If(e),yf(t)&&t.constructor===e)return t;var i=Af.f(e);return(0,i.resolve)(t),i.promise},wf=Mn,Of=BE,Nf=nm.CONSTRUCTOR,Df=bf,Pf=pt("Promise"),Lf=!Nf;wf({target:"Promise",stat:!0,forced:!0},{resolve:function(e){return Df(Lf&&this===Pf?Of:this,e)}});var kf=Fe,Mf=xt,Uf=rm,xf=FE,Vf=$p;Mn({target:"Promise",stat:!0,forced:df},{allSettled:function(e){var t=this,i=Uf.f(t),n=i.resolve,r=i.reject,s=xf((function(){var i=Mf(t.resolve),r=[],s=0,o=1;Vf(e,(function(e){var a=s++,c=!1;o++,kf(i,t,e).then((function(e){c||(c=!0,r[a]={status:"fulfilled",value:e},--o||n(r))}),(function(e){c||(c=!0,r[a]={status:"rejected",reason:e},--o||n(r))}))})),--o||n(r)}));return s.error&&r(s.value),i.promise}});var Ff=Fe,Bf=xt,jf=pt,Gf=rm,Wf=FE,Hf=$p,Kf="No one promise resolved";Mn({target:"Promise",stat:!0,forced:df},{any:function(e){var t=this,i=jf("AggregateError"),n=Gf.f(t),r=n.resolve,s=n.reject,o=Wf((function(){var n=Bf(t.resolve),o=[],a=0,c=1,d=!1;Hf(e,(function(e){var l=a++,h=!1;c++,Ff(n,t,e).then((function(e){h||d||(d=!0,r(e))}),(function(e){h||d||(h=!0,o[l]=e,--c||s(new i(o,Kf)))}))})),--c||s(new i(o,Kf))}));return o.error&&s(o.value),n.promise}});var Yf=Mn,qf=BE,Jf=de,zf=pt,Xf=ke,Qf=U_,Zf=bf,$f=qf&&qf.prototype;Yf({target:"Promise",proto:!0,real:!0,forced:!!qf&&Jf((function(){$f.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Qf(this,zf("Promise")),i=Xf(e);return this.then(i?function(i){return Zf(t,e()).then((function(){return i}))}:e,i?function(i){return Zf(t,e()).then((function(){throw i}))}:e)}});var eg=ct.Promise,tg=z(eg);const ig=()=>{};function ng(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:ig};return e.promise=new tg(((t,i)=>{e.resolve=i=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(i),e.value=i)},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,i(t))}})),e}const rg=new Map,sg=new Map,og=new Map;var ag,cg;!function(e){e.WIN_10="Windows 10",e.WIN_81="Windows 8.1",e.WIN_8="Windows 8",e.WIN_7="Windows 7",e.WIN_VISTA="Windows Vista",e.WIN_SERVER_2003="Windows Server 2003",e.WIN_XP="Windows XP",e.WIN_2000="Windows 2000",e.ANDROID="Android",e.HARMONY_OS="HarmonyOS",e.OPEN_BSD="Open BSD",e.SUN_OS="Sun OS",e.LINUX="Linux",e.IOS="iOS",e.MAC_OS="Mac OS",e.QNX="QNX",e.UNIX="UNIX",e.BEOS="BeOS",e.OS_2="OS/2",e.SEARCH_BOT="Search Bot"}(ag||(ag={})),function(e){e.CHROME="Chrome",e.SAFARI="Safari",e.EDGE="Edge",e.FIREFOX="Firefox",e.OPERA="OPR",e.QQ="QQBrowser",e.WECHAT="MicroMessenger"}(cg||(cg={}));var dg={exports:{}};!function(e,t){!function(i,n){var r="function",s="undefined",o="object",a="string",c="major",d="model",l="name",h="type",u="vendor",p="version",_="architecture",E="console",m="mobile",f="tablet",g="smarttv",S="wearable",T="embedded",R="Amazon",C="Apple",v="ASUS",I="BlackBerry",y="Browser",A="Chrome",b="Firefox",w="Google",O="Huawei",N="LG",D="Microsoft",P="Motorola",L="Opera",k="Samsung",M="Sharp",U="Sony",x="Xiaomi",V="Zebra",F="Facebook",B="Chromium OS",j="Mac OS",G=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},W=function(e,t){return typeof e===a&&-1!==H(t).indexOf(H(e))},H=function(e){return e.toLowerCase()},K=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===s?e:e.substring(0,350)},Y=function(e,t){for(var i,s,a,c,d,l,h=0;h<t.length&&!d;){var u=t[h],p=t[h+1];for(i=s=0;i<u.length&&!d&&u[i];)if(d=u[i++].exec(e))for(a=0;a<p.length;a++)l=d[++s],typeof(c=p[a])===o&&c.length>0?2===c.length?typeof c[1]==r?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==r||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):n:this[c[0]]=l?c[1].call(this,l,c[2]):n:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):n):this[c]=l||n;h+=2}},q=function(e,t){for(var i in t)if(typeof t[i]===o&&t[i].length>0){for(var r=0;r<t[i].length;r++)if(W(t[i][r],e))return"?"===i?n:i}else if(W(t[i],e))return"?"===i?n:i;return e},J={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},z={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,p],[/opios[\/ ]+([\w\.]+)/i],[p,[l,L+" Mini"]],[/\bopr\/([\w\.]+)/i],[p,[l,L]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[l,p],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[l,"UC"+y]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[p,[l,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[p,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[l,"IE"]],[/yabrowser\/([\w\.]+)/i],[p,[l,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+y],p],[/\bfocus\/([\w\.]+)/i],[p,[l,b+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[l,L+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[l,L+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[l,"MIUI "+y]],[/fxios\/([-\w\.]+)/i],[p,[l,b]],[/\bqihu|(qi?ho?o?|360)browser/i],[[l,"360 "+y]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1 "+y],p],[/(comodo_dragon)\/([\w\.]+)/i],[[l,/_/g," "],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[l,p],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,F],p],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[l,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[l,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[l,A+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,A+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[l,"Android "+y]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[p,q,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[l,b+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[l,p],[/(cobalt)\/([\w\.]+)/i],[l,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[_,"amd64"]],[/(ia32(?=;))/i],[[_,H]],[/((?:i[346]|x)86)[;\)]/i],[[_,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[_,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[_,"armhf"]],[/windows (ce|mobile); ppc;/i],[[_,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[_,/ower/,"",H]],[/(sun4\w)[;\)]/i],[[_,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[_,H]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[u,k],[h,f]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[d,[u,k],[h,m]],[/\((ip(?:hone|od)[\w ]*);/i],[d,[u,C],[h,m]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[u,C],[h,f]],[/(macintosh);/i],[d,[u,C]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[u,M],[h,m]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[u,O],[h,f]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[u,O],[h,m]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[d,/_/g," "],[u,x],[h,m]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[u,x],[h,f]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[u,"OPPO"],[h,m]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[u,"Vivo"],[h,m]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[d,[u,"Realme"],[h,m]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[u,P],[h,m]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[u,P],[h,f]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[u,N],[h,f]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[u,N],[h,m]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[u,"Lenovo"],[h,f]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[u,"Nokia"],[h,m]],[/(pixel c)\b/i],[d,[u,w],[h,f]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[u,w],[h,m]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[u,U],[h,m]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[u,U],[h,f]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[u,"OnePlus"],[h,m]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[u,R],[h,f]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[u,R],[h,m]],[/(playbook);[-\w\),; ]+(rim)/i],[d,u,[h,f]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[u,I],[h,m]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[u,v],[h,f]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[u,v],[h,m]],[/(nexus 9)/i],[d,[u,"HTC"],[h,f]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[u,[d,/_/g," "],[h,m]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[u,"Acer"],[h,f]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[u,"Meizu"],[h,m]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[u,d,[h,m]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[u,d,[h,f]],[/(surface duo)/i],[d,[u,D],[h,f]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[u,"Fairphone"],[h,m]],[/(u304aa)/i],[d,[u,"AT&T"],[h,m]],[/\bsie-(\w*)/i],[d,[u,"Siemens"],[h,m]],[/\b(rct\w+) b/i],[d,[u,"RCA"],[h,f]],[/\b(venue[\d ]{2,7}) b/i],[d,[u,"Dell"],[h,f]],[/\b(q(?:mv|ta)\w+) b/i],[d,[u,"Verizon"],[h,f]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[u,"Barnes & Noble"],[h,f]],[/\b(tm\d{3}\w+) b/i],[d,[u,"NuVision"],[h,f]],[/\b(k88) b/i],[d,[u,"ZTE"],[h,f]],[/\b(nx\d{3}j) b/i],[d,[u,"ZTE"],[h,m]],[/\b(gen\d{3}) b.+49h/i],[d,[u,"Swiss"],[h,m]],[/\b(zur\d{3}) b/i],[d,[u,"Swiss"],[h,f]],[/\b((zeki)?tb.*\b) b/i],[d,[u,"Zeki"],[h,f]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[u,"Dragon Touch"],d,[h,f]],[/\b(ns-?\w{0,9}) b/i],[d,[u,"Insignia"],[h,f]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[u,"NextBook"],[h,f]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[u,"Voice"],d,[h,m]],[/\b(lvtel\-)?(v1[12]) b/i],[[u,"LvTel"],d,[h,m]],[/\b(ph-1) /i],[d,[u,"Essential"],[h,m]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[u,"Envizen"],[h,f]],[/\b(trio[-\w\. ]+) b/i],[d,[u,"MachSpeed"],[h,f]],[/\btu_(1491) b/i],[d,[u,"Rotor"],[h,f]],[/(shield[\w ]+) b/i],[d,[u,"Nvidia"],[h,f]],[/(sprint) (\w+)/i],[u,d,[h,m]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[u,D],[h,m]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[u,V],[h,f]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[u,V],[h,m]],[/smart-tv.+(samsung)/i],[u,[h,g]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[u,k],[h,g]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[u,N],[h,g]],[/(apple) ?tv/i],[u,[d,C+" TV"],[h,g]],[/crkey/i],[[d,A+"cast"],[u,w],[h,g]],[/droid.+aft(\w)( bui|\))/i],[d,[u,R],[h,g]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[u,M],[h,g]],[/(bravia[\w ]+)( bui|\))/i],[d,[u,U],[h,g]],[/(mitv-\w{5}) bui/i],[d,[u,x],[h,g]],[/Hbbtv.*(technisat) (.*);/i],[u,d,[h,g]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[u,K],[d,K],[h,g]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,g]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[u,d,[h,E]],[/droid.+; (shield) bui/i],[d,[u,"Nvidia"],[h,E]],[/(playstation [345portablevi]+)/i],[d,[u,U],[h,E]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[u,D],[h,E]],[/((pebble))app/i],[u,d,[h,S]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[u,C],[h,S]],[/droid.+; (glass) \d/i],[d,[u,w],[h,S]],[/droid.+; (wt63?0{2,3})\)/i],[d,[u,V],[h,S]],[/(quest( 2| pro)?)/i],[d,[u,F],[h,S]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[u,[h,T]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[d,[h,m]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[h,f]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,f]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,m]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[u,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[l,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[l,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,p],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[l,[p,q,J]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[l,"Windows"],[p,q,J]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,j],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,p],[/\(bb(10);/i],[p,[l,I]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[l,b+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[l,A+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,B],p],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,p],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[l,p]]},X=function(e,t){if(typeof e===o&&(t=e,e=n),!(this instanceof X))return new X(e,t).getResult();var E=typeof i!==s&&i.navigator?i.navigator:n,g=e||(E&&E.userAgent?E.userAgent:""),S=E&&E.userAgentData?E.userAgentData:n,T=t?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(z,t):z;return this.getBrowser=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,T.browser),e[c]=function(e){return typeof e===a?e.replace(/[^\d\.]/g,"").split(".")[0]:n}(e[p]),E&&E.brave&&typeof E.brave.isBrave==r&&(e[l]="Brave"),e},this.getCPU=function(){var e={};return e[_]=n,Y.call(e,g,T.cpu),e},this.getDevice=function(){var e={};return e[u]=n,e[d]=n,e[h]=n,Y.call(e,g,T.device),!e[h]&&S&&S.mobile&&(e[h]=m),"Macintosh"==e[d]&&E&&typeof E.standalone!==s&&E.maxTouchPoints&&E.maxTouchPoints>2&&(e[d]="iPad",e[h]=f),e},this.getEngine=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,T.engine),e},this.getOS=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,T.os),!e[l]&&S&&"Unknown"!=S.platform&&(e[l]=S.platform.replace(/chrome os/i,B).replace(/macos/i,j)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return g},this.setUA=function(e){return g=typeof e===a&&e.length>350?K(e,350):e,this},this.setUA(g),this};X.VERSION="0.7.34",X.BROWSER=G([l,p,c]),X.CPU=G([_]),X.DEVICE=G([d,u,h,E,m,g,f,S,T]),X.ENGINE=X.OS=G([l,p]),e.exports&&(t=e.exports=X),t.UAParser=X;var Q=typeof i!==s&&(i.jQuery||i.Zepto);if(Q&&!Q.ua){var Z=new X;Q.ua=Z.getResult(),Q.ua.get=function(){return Z.getUA()},Q.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)Q.ua[i]=t[i]}}}("object"==typeof window?window:J)}(dg,dg.exports);const lg=new(z(dg.exports));let hg=lg.getResult(),ug=null;function pg(e){if(!ug){e&&lg.setUA(e),hg=lg.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return cg.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return cg.CHROME;case"Safari":case"Mobile Safari":return cg.SAFARI;case"Edge":return cg.EDGE;case"Firefox":return cg.FIREFOX;case"QQBrowser":return cg.QQ;case"Opera":return cg.OPERA;case"WeChat":return cg.WECHAT;default:return e.browser.name||""}}(hg),i=function(e){let t;return t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"",t.split(".")[0]}(hg),n=function(e){return"Windows"===e.os.name?e.os.version?e.os.name+" "+e.os.version:e.os.name:e.os.name||""}(hg),r=hg.os.version;if(!(t&&i&&n&&r))return{name:t,version:i,os:n,osVersion:r};ug={name:t,version:i,os:n,osVersion:r}}return ug}function _g(){return pg().os}function Eg(){const e=pg();return"".concat(e.os," ").concat(e.osVersion)}function mg(){const e=pg();return!!("WebKit"===hg.engine.name&&e.os===ag.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==cg.SAFARI||Cg()&&e.name!==cg.SAFARI)}function fg(){const e=pg();if(mg()){if(e.os===ag.MAC_OS)return!0;if(e.os===ag.IOS){const e=hg.os.version&&hg.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3)return!0;if(e&&Number(e[0])>14)return!0}}return!1}function gg(){return"WebKit"===hg.engine.name}function Sg(){return pg().name===cg.CHROME}function Tg(){return pg().name===cg.SAFARI}function Rg(){return pg().name===cg.FIREFOX}function Cg(){return pg().os===ag.IOS}function vg(e){const t=pg();return!(t.name!==cg.CHROME||!t.osVersion)&&Number(t.version)>=e}function Ig(e){const t=pg();return!(t.name!==cg.EDGE||!t.osVersion)&&Number(t.version)>=e}function yg(e){const t=pg();return!(t.name!==cg.OPERA||!t.osVersion)&&Number(t.version)>=e}function Ag(){const e=pg();return!(e.name!==cg.CHROME||!e.osVersion)&&Number(e.version)<=90}function bg(){const e=pg();if(e.os!==ag.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function wg(){const e=pg();if(e.os!==ag.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function Og(){const e=pg();if(e.os!==ag.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 16===Number(t[0])}function Ng(){const e=pg();if(e.os!==ag.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function Dg(){return Tg()&&navigator.maxTouchPoints>0}function Pg(){return pg().name===cg.WECHAT}function Lg(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function kg(){const e=pg();return e.name!==cg.EDGE&&e.name!==cg.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function Mg(){return _g()===ag.ANDROID}function Ug(){const e=pg();return Mg()&&(e.name===cg.CHROME||e.name===cg.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}var xg;!function(e){e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.TIMEOUT="TIMEOUT",e.INVALID_PARAMS="INVALID_PARAMS",e.NOT_READABLE="NOT_READABLE",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INVALID_OPERATION="INVALID_OPERATION",e.OPERATION_ABORTED="OPERATION_ABORTED",e.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",e.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",e.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",e.DATACHANNEL_FAILED="DATACHANNEL_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.NETWORK_TIMEOUT="NETWORK_TIMEOUT",e.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",e.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",e.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.ELECTRON_IS_NULL="ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",e.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",e.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",e.TRACK_IS_DISABLED="TRACK_IS_DISABLED",e.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",e.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",e.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",e.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",e.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",e.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",e.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",e.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",e.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",e.UID_CONFLICT="UID_CONFLICT",e.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",e.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",e.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",e.INVALID_TRACK="INVALID_TRACK",e.SENDER_NOT_FOUND="SENDER_NOT_FOUND",e.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",e.SET_ANSWER_FAILED="SET_ANSWER_FAILED",e.ICE_FAILED="ICE_FAILED",e.PC_CLOSED="PC_CLOSED",e.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",e.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",e.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",e.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",e.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",e.INVALID_REMOTE_USER="INVALID_REMOTE_USER",e.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",e.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",e.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",e.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",e.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",e.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",e.WS_ABORT="WS_ABORT",e.WS_DISCONNECT="WS_DISCONNECT",e.WS_ERR="WS_ERR",e.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",e.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",e.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",e.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",e.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",e.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",e.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",e.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",e.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",e.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",e.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",e.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",e.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",e.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",e.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",e.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",e.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",e.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",e.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",e.INVALID_PLUGIN="INVALID_PLUGIN",e.DISCONNECT_P2P="DISCONNECT_P2P",e.INIT_WEBSOCKET_TIMEOUT="INIT_WEBSOCKET_TIMEOUT",e.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",e.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",e.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",e.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",e.PROHIBITED_OPERATION="PROHIBITED_OPERATION",e.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED"}(xg||(xg={}));let Vg=class extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(t),nu(this,"code",void 0),nu(this,"message",void 0),nu(this,"data",void 0),nu(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=i}toString(){return this.data?"data: ".concat(JSON.stringify(this.data),"\n").concat(this.stack):"".concat(this.stack)}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error",t=arguments.length>1?arguments[1]:void 0;return"error"===e&&(t||console).error(this.toString()),"warning"===e&&(t||console).warn(this.toString()),this}throw(e){throw this.print("error",e),this}};function Fg(e,t){if("boolean"!=typeof e)throw new Vg(xg.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function Bg(e,t,i){if(!Lr(i).call(i,e))throw new Vg(xg.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)))}function jg(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(e<i||e>n||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return"number"==typeof e&&e%1==0}(e))throw new Vg(xg.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(n,"]. integer only"))}function Gg(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new Vg(xg.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&jg(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&jg(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&jg(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&jg(e.ideal,"".concat(t,".ideal"),1,1/0)}else jg(e,t,1,1/0)}function Wg(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new Vg(xg.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!Yg(e,i,n,r))throw new Vg(xg.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""))}function Hg(e,t){if(!Array.isArray(e))throw new Vg(xg.INVALID_PARAMS,"".concat(t," should be an array"))}function Kg(e){return null==e}function Yg(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return"string"==typeof e&&e.length<=i&&e.length>=t&&(!n||function(e){if("string"!=typeof e)return!1;for(let t=0;t<e.length;t+=1){const i=e.charCodeAt(t);if(i<0||i>255)return!1}return!0}(e))}function qg(e,t,i){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,i);const n=e.getUint32(t,i),r=e.getUint32(t+4,i),s=Number(!!i),o=Number(!i);return BigInt(n*o+r*s)<<BigInt(32)|BigInt(n*s+r*o)}function Jg(e,t,i,n){if("setBigUint64"in DataView.prototype)return e.setBigUint64(t,i,n);const r=Number(i>>BigInt(32)),s=Number(i&BigInt(4294967295));n?(e.setUint32(t+4,r,n),e.setUint32(t,s,n)):(e.setUint32(t,r,n),e.setUint32(t+4,s,n))}var zg,Xg;!function(e){e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE"}(zg||(zg={})),function(e){e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT"}(Xg||(Xg={}));const Qg=new class{constructor(){nu(this,"_clientSize",null),nu(this,"getClientWidth",(()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth)),nu(this,"getClientHeight",(()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight)),nu(this,"getStyle",(e=>window.getComputedStyle(e,null))),nu(this,"checkCssVisibleProperty",(e=>{var t;let i=!0;const n=this.getStyle(e),{display:r,visibility:s,opacity:o,filter:a}=n;return("none"===r||Lr(t=["hidden","collapse"]).call(t,s)||Number(o)<.1)&&(i=!1),!!i&&(a&&a.split(" ").filter((e=>{var t;const i=e.split("(")[0];return Lr(t=["brightness","blur","opacity"]).call(t,i)})).map((e=>{const[t,i]=e.split(/\(|\)/);return[t,Number(i.match(/^[0-9\.]+/))]})).forEach((e=>{const[t,n]=e;switch(t){case"brightness":(n<.1||n>3)&&(i=!1);break;case"blur":n>3&&(i=!1);break;case"opacity":n<.1&&(i=!1)}})),i)})),nu(this,"checkPropertyUpToAllParentNodes",((e,t)=>{let i=!0,n=!0;const r=e=>t(e);let s=e;for(;s&&n;)r(s)||(i=!1,n=!1),s=s.parentElement,s||(n=!1);return i})),nu(this,"checkActualCssVisibleIncludeInherit",(e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty))),nu(this,"getSizeAboutClient",(e=>{const{width:t,height:i,left:n,right:r,top:s,bottom:o}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return{width:t,height:i,left:n,right:r,top:s,bottom:o,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)}})),nu(this,"checkActualSize",(()=>{const{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i)})),nu(this,"elementFromPoint",((e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null)),nu(this,"checkCoverForAPoint",((e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i})),nu(this,"getPointPositionList",(()=>{const{width:e,height:t,left:i,top:n}=this._clientSize,r=e/6,s=t/6,o=[],a=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const c=(i*a+(0===e?.1:4===e?(r*e*a-1e5)/a:r*e)*a)/a,d=(n*a+(0===t?.1:4===t?(s*t*a-1e5)/a:s*t)*a)/a;o.push({x:c,y:d})}return[...o]})),nu(this,"checkElementCover",(e=>this.getPointPositionList().map((t=>this.checkCoverForAPoint(t.x,t.y,e))).filter((e=>!!e)).length>6)),nu(this,"checkSizeIsVisible",((e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10))),nu(this,"checkSizeOfPartInClient",(()=>{const{left:e,right:t,top:i,bottom:n,clientHeight:r,clientWidth:s,clientMin:o}=this._clientSize;let a,c,d,l;if(e<0)a=0;else{if(!(e<s))return!1;a=e}if(t<0)return!1;if(c=t<s?t:s,i<0)d=0;else{if(!(i<r))return!1;d=i}if(n<0)return!1;l=n<r?n:r;const h=c-a,u=l-d;return this.checkSizeIsVisible(h,u,o)})),nu(this,"returnHiddenResult",(e=>(this._clientSize=null,{visible:!1,reason:e}))),nu(this,"checkOneElementVisible",(e=>{if(e instanceof HTMLElement){if(this.checkElementIsMountedOnDom(e)){if(this.checkActualCssVisibleIncludeInherit(e)){if(this._clientSize=this.getSizeAboutClient(e),this.checkElementCover(e))return this.returnHiddenResult(zg.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(zg.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(zg.SIZE)}}return this.returnHiddenResult(zg.STYLE)}return this.returnHiddenResult(Xg.UNMOUNTED)}return this.returnHiddenResult(Xg.INVALID_HTML_ELEMENT)})),nu(this,"checkElementIsMountedOnDom",(e=>this.checkPropertyUpToAllParentNodes(e,(e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))))}};function Zg(e){return(new TextEncoder).encode(e)}const $g=function(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i},eS=async e=>{const t=function(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i}("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),i=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),n=Zg(e),r=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},i,n);return function(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}(new Uint8Array(r))},tS=async e=>function(e,t){let i="";return new Uint8Array(e).forEach((e=>{i+=e.toString(t).padStart(2,"0")})),i}(await crypto.subtle.digest("SHA-256",Zg(e)),16);class iS{constructor(){nu(this,"_events",{}),nu(this,"addListener",this.on)}getListeners(e){return this._events[e]?this._events[e].map((e=>e.listener)):[]}on(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const i=this._events[e],n=this._indexOfListener(i,t);-1!==n&&i.splice(n,1),0===this._events[e].length&&delete this._events[e]}removeAllListeners(e){e?delete this._events[e]:this._events={}}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map((e=>e));for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];for(let i=0;i<t.length;i+=1){const r=t[i];r.once&&this.off(e,r.listener),r.listener.apply(this,n||[])}}safeEmit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];[...this._events[e]||[]].forEach((t=>{t.once&&this.off(e,t.listener);try{t.listener.apply(this,i)}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()))}}))}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return-1}}let nS=null;function rS(){if(nS)return nS;if(window.electron)return nS=window.electron;if(!window.require)return null;try{return nS=window.require("electron"),nS}catch(e){return null}}var sS,oS,aS,cS,dS,lS,hS,uS;function pS(e){return jg(e.timeout,"config.timeout",0,1e5),jg(e.timeoutFactor,"config.timeoutFactor",0,100,!1),jg(e.maxRetryCount,"config.maxRetryConfig",0,1/0),jg(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}function _S(e){if(!Array.isArray(e)||e.length<1)return!1;try{e.forEach((e=>{if(!e.urls)throw Error()}))}catch(e){return!1}return!0}function ES(e){return Wg(e.turnServerURL,"turnServerURL"),Wg(e.username,"username"),Wg(e.password,"password"),e.udpport&&jg(e.udpport,"udpport",1,99999,!0),e.forceturn&&Fg(e.forceturn,"forceturn"),e.security&&Fg(e.security,"security"),e.tcpport&&jg(e.tcpport,"tcpport",1,99999,!0),!0}function mS(e){return void 0!==e.level&&Bg(e.level,"level",[1,2,3]),void 0!==e.delay&&jg(e.delay,"delay",0,3e3,!0),!0}function fS(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return 0===e.getListeners(t).length?tg.reject(new Vg(xg.UNEXPECTED_ERROR,"can not emit promise")):new tg(((i,r)=>{e.emit(t,...n,i,r)}))}function gS(e,t){if(0===e.getListeners(t).length)return tg.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return fS(e,t,...n)}function SS(e,t){if(0===e.getListeners(t).length)return null;for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return TS(e,t,...n)}function TS(e,t){let i=null,n=null;for(var r=arguments.length,s=new Array(r>2?r-2:0),o=2;o<r;o++)s[o-2]=arguments[o];if(e.emit(t,...s,(e=>{i=e}),(e=>{n=e})),null!==n)throw n;if(null===i)throw new Vg(xg.UNEXPECTED_ERROR,"handler is not sync");return i}!function(e){e.CREATE_CLIENT="createClient",e.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",e.SET_AREA="setArea",e.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",e.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",e.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",e.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",e.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",e.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",e.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",e.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",e.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",e.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",e.START_PROXY_SERVER="Client.startProxyServer",e.STOP_PROXY_SERVER="Client.stopProxyServer",e.SET_PROXY_SERVER="Client.setProxyServer",e.SET_TURN_SERVER="Client.setTurnServer",e.SET_CLIENT_ROLE="Client.setClientRole",e.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",e.ENABLE_DUAL_STREAM="Client.enableDualStream",e.DISABLE_DUAL_STREAM="Client.disableDualStream",e.JOIN="Client.join",e.LEAVE="Client.leave",e.PUBLISH="Client.publish",e.UNPUBLISH="Client.unpublish",e.SUBSCRIBE="Client.subscribe",e.MASS_SUBSCRIBE="Client.massSubscribe",e.MASS_UNSUBSCRIBE="Client.massUnsubscribe",e.UNSUBSCRIBE="Client.unsubscribe",e.RENEW_TOKEN="Client.renewToken",e.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",e.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",e.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",e.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",e.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",e.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",e.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",e.DATACHANNEL_FAILBACK="Client._datachannelFailback",e.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",e.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",e.START_LIVE_STREAMING="Client.startLiveStreaming",e.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",e.STOP_LIVE_STREAMING="Client.stopLiveStreaming",e.ADD_INJECT_STREAM_URL="Client.addInjectStreamUrl",e.REMOVE_INJECT_STREAM_URL="Client.removeInjectStreamUrl",e.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",e.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",e.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",e.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",e.SET_CONFIG_DISTRIBUTE="_configDistribute",e.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",e.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",e.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",e.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",e.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",e.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",e.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",e.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",e.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",e.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",e.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",e.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",e.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",e.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",e.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",e.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",e.STREAM_TYPE_CHANGE="streamTypeChange",e.CONNECTION_STATE_CHANGE="connectionStateChange",e.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",e.IMAGE_MODERATION_UPLOAD="imageModerationUpload"}(sS||(sS={})),function(e){e.TRACER="tracer"}(oS||(oS={})),function(e){e[e.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",e[e.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",e[e.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY"}(aS||(aS={})),function(e){e.LEAVE="LEAVE",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.UID_BANNED="UID_BANNED",e.IP_BANNED="IP_BANNED",e.CHANNEL_BANNED="CHANNEL_BANNED",e.FALLBACK="FALLBACK",e.LICENSE_MISSING="LICENSE_MISSING",e.LICENSE_EXPIRED="LICENSE_EXPIRED",e.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",e.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",e.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",e.LICENSE_ILLEGAL="LICENSE_ILLEGAL",e.TOKEN_EXPIRE="TOKEN_EXPIRE"}(cS||(cS={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.MEDIA_RECONNECT_START="media-reconnect-start",e.MEDIA_RECONNECT_END="media-reconnect-end",e.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",e.USER_JOINED="user-joined",e.USER_LEAVED="user-left",e.USER_PUBLISHED="user-published",e.USER_UNPUBLISHED="user-unpublished",e.USER_INFO_UPDATED="user-info-updated",e.CLIENT_BANNED="client-banned",e.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",e.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",e.VOLUME_INDICATOR="volume-indicator",e.CRYPT_ERROR="crypt-error",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGED="stream-type-changed",e.STREAM_FALLBACK="stream-fallback",e.RECEIVE_METADATA="receive-metadata",e.STREAM_MESSAGE="stream-message",e.LIVE_STREAMING_ERROR="live-streaming-error",e.LIVE_STREAMING_WARNING="live-streaming-warning",e.INJECT_STREAM_STATUS="stream-inject-status",e.EXCEPTION="exception",e.ERROR="error",e.P2P_LOST="p2p_lost",e.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",e.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",e.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",e.PUBLISHED_USER_LIST="published-user-list",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",e.CONTENT_INSPECT_ERROR="content-inspect-error",e.CONTENT_INSPECT_RESULT="content-inspect-result",e.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change"}(dS||(dS={})),function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK"}(lS||(lS={})),function(e){e.ONLINE="ONLINE",e.OFFLINE="OFFLINE"}(hS||(hS={})),function(e){e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE"}(uS||(uS={}));const RS=new class extends iS{set networkState(e){this.emit(uS.NETWORK_STATE_CHANGE,e,this._networkState),e===hS.ONLINE?this.emit(uS.ONLINE):e===hS.OFFLINE&&(this.onlineWaiter=new tg((e=>{this.once(uS.ONLINE,(()=>{this.onlineWaiter=void 0,e(hS.ONLINE)}))})),this.emit(uS.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===hS.ONLINE}constructor(){super(),nu(this,"_moduleName","network-indicator"),nu(this,"_networkState",hS.ONLINE),nu(this,"onlineWaiter",void 0),window.addEventListener("online",(()=>{this.networkState=hS.ONLINE})),window.addEventListener("offline",(()=>{this.networkState=hS.OFFLINE}))}};function CS(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function vS(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?CS(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):CS(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function IS(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1)}function yS(e){const t=[];return e.forEach((e=>{-1===t.indexOf(e)&&t.push(e)})),t}function AS(e){void 0!==tg?tg.resolve().then(e):setTimeout(e,0)}function bS(e){return JSON.parse(JSON.stringify(e))}function wS(e){try{return bS(e)}catch(t){return e}}const OS={};function NS(e,t){OS[t]||(OS[t]=!0,e())}function DS(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i}function PS(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}function LS(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function kS(e){let t=0;return/DingTalk/i.test(navigator.userAgent)&&e.realFormData&&(e=e.realFormData),e.forEach((e=>{t+="string"==typeof e?LS(e):e.size})),t+138}function MS(e){const t=new Vg(xg.TIMEOUT,"timeout");return new tg(((i,n)=>{window.setTimeout((()=>n(t)),e)}))}function US(e){return new tg((t=>{window.setTimeout(t,e)}))}function xS(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const i=Math.random().toString(16).substr(2,e).toLowerCase();return i.length===e?"".concat(t).concat(i):"".concat(t).concat(i)+xS(e-i.length,"")}function VS(){return xS(32,"").toUpperCase()}const FS=()=>{},BS=new class{constructor(){nu(this,"fnMap",new Map)}throttleByKey(e,t,i,n){for(var r=arguments.length,s=new Array(r>4?r-4:0),o=4;o<r;o++)s[o-4]=arguments[o];if(this.fnMap.has(t)){const r=this.fnMap.get(t);if(r.threshold!==i){r.fn(...r.args),clearTimeout(r.timer);const o=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:o,args:s,skipFn:n})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,vS(vS({},r),{},{fn:e,args:s,skipFn:n}))}else{const r=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),i);this.fnMap.set(t,{fn:e,threshold:i,timer:r,args:s,skipFn:n})}}},jS=BS.throttleByKey.bind(BS);function GS(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}function WS(e,t){if(!GS(e)||!GS(t))return t;if(Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const i=[...e];for(let n=0;n<t.length;n++)i[n]=WS(e[n],t[n]);return i}{const i=vS({},e);for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(Object.prototype.hasOwnProperty.call(e,n)?i[n]=WS(e[n],t[n]):i[n]=t[n]);return i}}let HS=1,KS=console;class YS{static setLogger(e){KS=e}constructor(e){nu(this,"lockingPromise",tg.resolve()),nu(this,"locks",0),nu(this,"name",""),nu(this,"lockId",void 0),this.lockId=HS++,e&&(this.name=e),KS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is created."))}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,KS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:""));const i=new tg((i=>{t=()=>{this.locks-=1,KS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is not locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:"")),i()}})),n=this.lockingPromise.then((()=>t));return this.lockingPromise=this.lockingPromise.then((()=>i)),n}}function qS(e,t){return function(i,n,r){const s=r.value;if("function"!=typeof s)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const i=this[t];if(!i)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await i.lock("From ".concat(e,".").concat(n));try{for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return await s.apply(this,a)}finally{r()}},r}}const JS={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function zS(e,t){const i=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,i)}function XS(e,t,i,n){const r=Object.assign({},JS,n);let s=r.timeout;const o=async()=>{await function(e){return new tg((t=>{window.setTimeout(t,e)}))}(s),s*=r.timeoutFactor,s=Math.min(r.maxRetryTimeout,s)};let a=!1;const c=new tg((async(n,s)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;c<r.maxRetryCount;c+=1){if(a)return s(new Vg(xg.OPERATION_ABORTED));try{const i=await e();if(!t(i,c))return n(i);if(c+1===r.maxRetryCount)return n(i);await o()}catch(e){if(!i(e,c))return s(e);if(c+1===r.maxRetryCount)return s(e);await o()}}}));return c.cancel=()=>a=!0,c}var QS=xt,ZS=ti,$S=Qe,eT=qn,tT=TypeError,iT=function(e){return function(t,i,n,r){QS(i);var s=ZS(t),o=$S(s),a=eT(s),c=e?a-1:0,d=e?-1:1;if(n<2)for(;;){if(c in o){r=o[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw tT("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=d)c in o&&(r=i(r,o[c],c,s));return r}},nT=[iT(!1),iT(!0)][0];Mn({target:"Array",proto:!0,forced:!C_&&Rt>79&&Rt<83||!Ru("reduce")},{reduce:function(e){var t=arguments.length;return nT(this,e,t,t>1?arguments[1]:void 0)}});var rT=tr("Array").reduce,sT=me,oT=rT,aT=Array.prototype,cT=z((function(e){var t=e.reduce;return e===aT||sT(aT,e)&&t===aT.reduce?oT:t}));let dT=class{constructor(e){nu(this,"input",[]),nu(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}mean(){var e;return 0===this.input.length?0:cT(e=this.input).call(e,((e,t)=>e+t))/this.input.length}};var lT,hT={exports:{}},uT=function(e,t){return function(){for(var i=new Array(arguments.length),n=0;n<i.length;n++)i[n]=arguments[n];return e.apply(t,i)}},pT=uT,_T=Object.prototype.toString,ET=(lT=Object.create(null),function(e){var t=_T.call(e);return lT[t]||(lT[t]=t.slice(8,-1).toLowerCase())});function mT(e){return e=e.toLowerCase(),function(t){return ET(t)===e}}function fT(e){return Array.isArray(e)}function gT(e){return void 0===e}var ST=mT("ArrayBuffer");function TT(e){return null!==e&&"object"==typeof e}function RT(e){if("object"!==ET(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var CT=mT("Date"),vT=mT("File"),IT=mT("Blob"),yT=mT("FileList");function AT(e){return"[object Function]"===_T.call(e)}var bT=mT("URLSearchParams");function wT(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),fT(e))for(var i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.call(null,e[r],r,e)}var OT,NT=(OT="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return OT&&e instanceof OT}),DT={isArray:fT,isArrayBuffer:ST,isBuffer:function(e){return null!==e&&!gT(e)&&null!==e.constructor&&!gT(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){var t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||_T.call(e)===t||AT(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&ST(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:TT,isPlainObject:RT,isUndefined:gT,isDate:CT,isFile:vT,isBlob:IT,isFunction:AT,isStream:function(e){return TT(e)&&AT(e.pipe)},isURLSearchParams:bT,isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:wT,merge:function e(){var t={};function i(i,n){RT(t[n])&&RT(i)?t[n]=e(t[n],i):RT(i)?t[n]=e({},i):fT(i)?t[n]=i.slice():t[n]=i}for(var n=0,r=arguments.length;n<r;n++)wT(arguments[n],i);return t},extend:function(e,t,i){return wT(t,(function(t,n){e[n]=i&&"function"==typeof t?pT(t,i):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},inherits:function(e,t,i,n){e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,i&&Object.assign(e.prototype,i)},toFlatObject:function(e,t,i){var n,r,s,o={};t=t||{};do{for(r=(n=Object.getOwnPropertyNames(e)).length;r-- >0;)o[s=n[r]]||(t[s]=e[s],o[s]=!0);e=Object.getPrototypeOf(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:ET,kindOfTest:mT,endsWith:function(e,t,i){e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;var n=e.indexOf(t,i);return-1!==n&&n===i},toArray:function(e){if(!e)return null;var t=e.length;if(gT(t))return null;for(var i=new Array(t);t-- >0;)i[t]=e[t];return i},isTypedArray:NT,isFileList:yT},PT=DT;function LT(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var kT=function(e,t,i){if(!t)return e;var n;if(i)n=i(t);else if(PT.isURLSearchParams(t))n=t.toString();else{var r=[];PT.forEach(t,(function(e,t){null!=e&&(PT.isArray(e)?t+="[]":e=[e],PT.forEach(e,(function(e){PT.isDate(e)?e=e.toISOString():PT.isObject(e)&&(e=JSON.stringify(e)),r.push(LT(t)+"="+LT(e))})))})),n=r.join("&")}if(n){var s=e.indexOf("#");-1!==s&&(e=e.slice(0,s)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e},MT=DT;function UT(){this.handlers=[]}UT.prototype.use=function(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1},UT.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},UT.prototype.forEach=function(e){MT.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var xT,VT,FT=UT,BT=DT;function jT(){if(VT)return xT;VT=1;var e=DT;function t(e,t,i,n,r){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r)}e.inherits(t,Error,{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,status:this.response&&this.response.status?this.response.status:null}}});var i=t.prototype,n={};return["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach((function(e){n[e]={value:e}})),Object.defineProperties(t,n),Object.defineProperty(i,"isAxiosError",{value:!0}),t.from=function(n,r,s,o,a,c){var d=Object.create(i);return e.toFlatObject(n,d,(function(e){return e!==Error.prototype})),t.call(d,n.message,r,s,o,a),d.name=n.name,c&&Object.assign(d,c),d},xT=t}var GT,WT,HT,KT,YT,qT,JT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};function zT(){if(WT)return GT;WT=1;var e=DT;return GT=function(t,i){i=i||new FormData;var n=[];function r(t){return null===t?"":e.isDate(t)?t.toISOString():e.isArrayBuffer(t)||e.isTypedArray(t)?"function"==typeof Blob?new Blob([t]):Buffer.from(t):t}return function t(s,o){if(e.isPlainObject(s)||e.isArray(s)){if(-1!==n.indexOf(s))throw Error("Circular reference detected in "+o);n.push(s),e.forEach(s,(function(n,s){if(!e.isUndefined(n)){var a,c=o?o+"."+s:s;if(n&&!o&&"object"==typeof n)if(e.endsWith(s,"{}"))n=JSON.stringify(n);else if(e.endsWith(s,"[]")&&(a=e.toArray(n)))return void a.forEach((function(t){!e.isUndefined(t)&&i.append(c,r(t))}));t(n,c)}})),n.pop()}else i.append(o,r(s))}(t),i},GT}function XT(){if(KT)return HT;KT=1;var e=jT();return HT=function(t,i,n){var r=n.config.validateStatus;n.status&&r&&!r(n.status)?i(new e("Request failed with status code "+n.status,[e.ERR_BAD_REQUEST,e.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):t(n)}}function QT(){if(qT)return YT;qT=1;var e=DT;return YT=e.isStandardBrowserEnv()?{write:function(t,i,n,r,s,o){var a=[];a.push(t+"="+encodeURIComponent(i)),e.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),e.isString(r)&&a.push("path="+r),e.isString(s)&&a.push("domain="+s),!0===o&&a.push("secure"),document.cookie=a.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(){}},YT}var ZT,$T,eR,tR,iR,nR,rR,sR,oR,aR,cR,dR,lR=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},hR=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},uR=function(e,t){return e&&!lR(t)?hR(e,t):t};function pR(){if($T)return ZT;$T=1;var e=DT,t=["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"];return ZT=function(i){var n,r,s,o={};return i?(e.forEach(i.split("\n"),(function(i){if(s=i.indexOf(":"),n=e.trim(i.substr(0,s)).toLowerCase(),r=e.trim(i.substr(s+1)),n){if(o[n]&&t.indexOf(n)>=0)return;o[n]="set-cookie"===n?(o[n]?o[n]:[]).concat([r]):o[n]?o[n]+", "+r:r}})),o):o},ZT}function _R(){if(tR)return eR;tR=1;var e=DT;return eR=e.isStandardBrowserEnv()?function(){var t,i=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function r(e){var t=e;return i&&(n.setAttribute("href",t),t=n.href),n.setAttribute("href",t),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return t=r(window.location.href),function(i){var n=e.isString(i)?r(i):i;return n.protocol===t.protocol&&n.host===t.host}}():function(){return!0}}function ER(){if(nR)return iR;nR=1;var e=jT();function t(t){e.call(this,null==t?"canceled":t,e.ERR_CANCELED),this.name="CanceledError"}return DT.inherits(t,e,{__CANCEL__:!0}),iR=t}function mR(){return sR||(sR=1,rR=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}),rR}function fR(){if(aR)return oR;aR=1;var e=DT,t=XT(),i=QT(),n=kT,r=uR,s=pR(),o=_R(),a=JT,c=jT(),d=ER(),l=mR();return oR=function(h){return new Promise((function(u,p){var _,E=h.data,m=h.headers,f=h.responseType;function g(){h.cancelToken&&h.cancelToken.unsubscribe(_),h.signal&&h.signal.removeEventListener("abort",_)}e.isFormData(E)&&e.isStandardBrowserEnv()&&delete m["Content-Type"];var S=new XMLHttpRequest;if(h.auth){var T=h.auth.username||"",R=h.auth.password?unescape(encodeURIComponent(h.auth.password)):"";m.Authorization="Basic "+btoa(T+":"+R)}var C=r(h.baseURL,h.url);function v(){if(S){var e="getAllResponseHeaders"in S?s(S.getAllResponseHeaders()):null,i={data:f&&"text"!==f&&"json"!==f?S.response:S.responseText,status:S.status,statusText:S.statusText,headers:e,config:h,request:S};t((function(e){u(e),g()}),(function(e){p(e),g()}),i),S=null}}if(S.open(h.method.toUpperCase(),n(C,h.params,h.paramsSerializer),!0),S.timeout=h.timeout,"onloadend"in S?S.onloadend=v:S.onreadystatechange=function(){S&&4===S.readyState&&(0!==S.status||S.responseURL&&0===S.responseURL.indexOf("file:"))&&setTimeout(v)},S.onabort=function(){S&&(p(new c("Request aborted",c.ECONNABORTED,h,S)),S=null)},S.onerror=function(){p(new c("Network Error",c.ERR_NETWORK,h,S,S)),S=null},S.ontimeout=function(){var e=h.timeout?"timeout of "+h.timeout+"ms exceeded":"timeout exceeded",t=h.transitional||a;h.timeoutErrorMessage&&(e=h.timeoutErrorMessage),p(new c(e,t.clarifyTimeoutError?c.ETIMEDOUT:c.ECONNABORTED,h,S)),S=null},e.isStandardBrowserEnv()){var I=(h.withCredentials||o(C))&&h.xsrfCookieName?i.read(h.xsrfCookieName):void 0;I&&(m[h.xsrfHeaderName]=I)}"setRequestHeader"in S&&e.forEach(m,(function(e,t){void 0===E&&"content-type"===t.toLowerCase()?delete m[t]:S.setRequestHeader(t,e)})),e.isUndefined(h.withCredentials)||(S.withCredentials=!!h.withCredentials),f&&"json"!==f&&(S.responseType=h.responseType),"function"==typeof h.onDownloadProgress&&S.addEventListener("progress",h.onDownloadProgress),"function"==typeof h.onUploadProgress&&S.upload&&S.upload.addEventListener("progress",h.onUploadProgress),(h.cancelToken||h.signal)&&(_=function(e){S&&(p(!e||e&&e.type?new d:e),S.abort(),S=null)},h.cancelToken&&h.cancelToken.subscribe(_),h.signal&&(h.signal.aborted?_():h.signal.addEventListener("abort",_))),E||(E=null);var y=l(C);y&&-1===["http","https","file"].indexOf(y)?p(new c("Unsupported protocol "+y+":",c.ERR_BAD_REQUEST,h)):S.send(E)}))},oR}var gR=DT,SR=function(e,t){BT.forEach(e,(function(i,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=i,delete e[n])}))},TR=jT(),RR=JT,CR=zT(),vR={"Content-Type":"application/x-www-form-urlencoded"};function IR(e,t){!gR.isUndefined(e)&&gR.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var yR,AR={transitional:RR,adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(yR=fR()),yR),transformRequest:[function(e,t){if(SR(t,"Accept"),SR(t,"Content-Type"),gR.isFormData(e)||gR.isArrayBuffer(e)||gR.isBuffer(e)||gR.isStream(e)||gR.isFile(e)||gR.isBlob(e))return e;if(gR.isArrayBufferView(e))return e.buffer;if(gR.isURLSearchParams(e))return IR(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var i,n=gR.isObject(e),r=t&&t["Content-Type"];if((i=gR.isFileList(e))||n&&"multipart/form-data"===r){var s=this.env&&this.env.FormData;return CR(i?{"files[]":e}:e,s&&new s)}return n||"application/json"===r?(IR(t,"application/json"),function(e,t,i){if(gR.isString(e))try{return(t||JSON.parse)(e),gR.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||AR.transitional,i=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,r=!i&&"json"===this.responseType;if(r||n&&gR.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw TR.from(e,TR.ERR_BAD_RESPONSE,this,null,this.response);throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:dR?cR:(dR=1,cR=null)},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};gR.forEach(["delete","get","head"],(function(e){AR.headers[e]={}})),gR.forEach(["post","put","patch"],(function(e){AR.headers[e]=gR.merge(vR)}));var bR,wR,OR=AR,NR=DT,DR=OR;function PR(){return wR?bR:(wR=1,bR=function(e){return!(!e||!e.__CANCEL__)})}var LR=DT,kR=function(e,t,i){var n=this||DR;return NR.forEach(i,(function(i){e=i.call(n,e,t)})),e},MR=PR(),UR=OR,xR=ER();function VR(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new xR}var FR,BR,jR=DT,GR=function(e,t){t=t||{};var i={};function n(e,t){return jR.isPlainObject(e)&&jR.isPlainObject(t)?jR.merge(e,t):jR.isPlainObject(t)?jR.merge({},t):jR.isArray(t)?t.slice():t}function r(i){return jR.isUndefined(t[i])?jR.isUndefined(e[i])?void 0:n(void 0,e[i]):n(e[i],t[i])}function s(e){if(!jR.isUndefined(t[e]))return n(void 0,t[e])}function o(i){return jR.isUndefined(t[i])?jR.isUndefined(e[i])?void 0:n(void 0,e[i]):n(void 0,t[i])}function a(i){return i in t?n(e[i],t[i]):i in e?n(void 0,e[i]):void 0}var c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a};return jR.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=c[e]||r,n=t(e);jR.isUndefined(n)&&t!==a||(i[e]=n)})),i};function WR(){return BR?FR:(BR=1,FR={version:"0.27.2"})}var HR=WR().version,KR=jT(),YR={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){YR[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));var qR={};YR.transitional=function(e,t,i){function n(e,t){return"[Axios v"+HR+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return function(i,r,s){if(!1===e)throw new KR(n(r," has been removed"+(t?" in "+t:"")),KR.ERR_DEPRECATED);return t&&!qR[r]&&(qR[r]=!0,console.warn(n(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,r,s)}};var JR,zR,XR,QR,ZR,$R,eC={assertOptions:function(e,t,i){if("object"!=typeof e)throw new KR("options must be an object",KR.ERR_BAD_OPTION_VALUE);for(var n=Object.keys(e),r=n.length;r-- >0;){var s=n[r],o=t[s];if(o){var a=e[s],c=void 0===a||o(a,s,e);if(!0!==c)throw new KR("option "+s+" must be "+c,KR.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new KR("Unknown option "+s,KR.ERR_BAD_OPTION)}},validators:YR},tC=DT,iC=kT,nC=FT,rC=function(e){return VR(e),e.headers=e.headers||{},e.data=kR.call(e,e.data,e.headers,e.transformRequest),e.headers=LR.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),LR.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||UR.adapter)(e).then((function(t){return VR(e),t.data=kR.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return MR(t)||(VR(e),t&&t.response&&(t.response.data=kR.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},sC=GR,oC=uR,aC=eC,cC=aC.validators;function dC(e){this.defaults=e,this.interceptors={request:new nC,response:new nC}}dC.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=sC(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var i=t.transitional;void 0!==i&&aC.assertOptions(i,{silentJSONParsing:cC.transitional(cC.boolean),forcedJSONParsing:cC.transitional(cC.boolean),clarifyTimeoutError:cC.transitional(cC.boolean)},!1);var n=[],r=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(r=r&&e.synchronous,n.unshift(e.fulfilled,e.rejected))}));var s,o=[];if(this.interceptors.response.forEach((function(e){o.push(e.fulfilled,e.rejected)})),!r){var a=[rC,void 0];for(Array.prototype.unshift.apply(a,n),a=a.concat(o),s=Promise.resolve(t);a.length;)s=s.then(a.shift(),a.shift());return s}for(var c=t;n.length;){var d=n.shift(),l=n.shift();try{c=d(c)}catch(e){l(e);break}}try{s=rC(c)}catch(e){return Promise.reject(e)}for(;o.length;)s=s.then(o.shift(),o.shift());return s},dC.prototype.getUri=function(e){e=sC(this.defaults,e);var t=oC(e.baseURL,e.url);return iC(t,e.params,e.paramsSerializer)},tC.forEach(["delete","get","head","options"],(function(e){dC.prototype[e]=function(t,i){return this.request(sC(i||{},{method:e,url:t,data:(i||{}).data}))}})),tC.forEach(["post","put","patch"],(function(e){function t(t){return function(i,n,r){return this.request(sC(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}dC.prototype[e]=t(),dC.prototype[e+"Form"]=t(!0)}));var lC=DT,hC=uT,uC=dC,pC=GR,_C=function e(t){var i=new uC(t),n=hC(uC.prototype.request,i);return lC.extend(n,uC.prototype,i),lC.extend(n,i),n.create=function(i){return e(pC(t,i))},n}(OR);_C.Axios=uC,_C.CanceledError=ER(),_C.CancelToken=function(){if(zR)return JR;zR=1;var e=ER();function t(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var i;this.promise=new Promise((function(e){i=e}));var n=this;this.promise.then((function(e){if(n._listeners){var t,i=n._listeners.length;for(t=0;t<i;t++)n._listeners[t](e);n._listeners=null}})),this.promise.then=function(e){var t,i=new Promise((function(e){n.subscribe(e),t=e})).then(e);return i.cancel=function(){n.unsubscribe(t)},i},t((function(t){n.reason||(n.reason=new e(t),i(n.reason))}))}return t.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},t.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},t.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},t.source=function(){var e;return{token:new t((function(t){e=t})),cancel:e}},JR=t}(),_C.isCancel=PR(),_C.VERSION=WR().version,_C.toFormData=zT(),_C.AxiosError=jT(),_C.Cancel=_C.CanceledError,_C.all=function(e){return Promise.all(e)},_C.spread=QR?XR:(QR=1,XR=function(e){return function(t){return e.apply(null,t)}}),_C.isAxiosError=function(){if($R)return ZR;$R=1;var e=DT;return ZR=function(t){return e.isObject(t)&&!0===t.isAxiosError}}(),hT.exports=_C,hT.exports.default=_C;var EC=z(hT.exports);function mC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function fC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?mC(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):mC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let gC,SC=0,TC=0;function RC(e,t,i,n){return new tg(((r,s)=>{t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),SC+=LS(t.data)):i&&(t.data.size?SC+=t.data.size:t.data instanceof FormData?SC+=kS(t.data):SC+=LS(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,EC.request(t).then((e=>{"string"==typeof e.data?TC+=LS(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?TC+=e.data.byteLength:TC+=LS(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{EC.isCancel(e)?s(new Vg(xg.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new Vg(xg.NETWORK_TIMEOUT,e.message)):e.response?s(new Vg(xg.NETWORK_RESPONSE_ERROR,e.response.status)):s(new Vg(xg.NETWORK_ERROR,e.message))}))}))}async function CC(e,t){const i=new Blob([t.data],{type:"buffer"});return await RC(e,fC(fC({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)}const vC=()=>"HTTPS"===(gC||gC||(gC=(window.location.protocol.split(":")[0]||"").toUpperCase(),gC)),IC=()=>void 0!==window.isSecureContext;function yC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function AC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?yC(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):yC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}var bC;!function(e){e.SET_SESSION_ID="SET_SESSION_ID",e.SET_P2P_ID="SET_P2P_id",e.SET_DC_ID="SET_DC_id",e.SET_UID="SET_UID",e.SET_PUB_ID="SET_PUB_ID",e.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",e.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",e.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",e.AVOID_JOIN_START="AVOID_JOIN_START",e.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",e.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",e.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",e.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",e.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",e.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",e.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",e.KEY_METRIC_DESCRIPTION_START="KEY_METRIC_DESCRIPTION_START",e.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",e.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",e.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",e.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",e.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",e.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",e.RESET_KEY_METRICS="RESET_KEY_METRICS",e.SET_USE_DATACHANNEL="SET_USE_DATACHANNEL",e.SET_USE_P2P="SET_USE_P2P"}(bC||(bC={}));class wC{constructor(e,t,i,n){nu(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:i,clientId:n,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,avoidJoinStart:0,keyMetrics:{publish:[],subscribe:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useDataChannel:!1,useP2P:!1}}dispatch(e){this.state=function(e,t){switch(t.type){case bC.SET_SESSION_ID:return AC(AC({},e),{},{sessionId:t.sessionId});case bC.SET_P2P_ID:return AC(AC({},e),{},{p2pId:t.p2pId});case bC.SET_UID:return AC(AC({},e),{},{uid:t.uid});case bC.SET_PUB_ID:return AC(AC({},e),{},{pubId:t.pubId});case bC.KEY_METRIC_CLIENT_CREATED:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{clientCreated:t.metric})});case bC.KEY_METRIC_JOIN_START:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{joinStart:t.metric})});case bC.AVOID_JOIN_START:return AC(AC({},e),{},{avoidJoinStart:t.avoidJoinStart});case bC.KEY_METRIC_JOIN_END:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{joinEnd:t.metric})});case bC.KEY_METRIC_REQUEST_AP_START:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{requestAPStart:t.metric})});case bC.KEY_METRIC_REQUEST_AP_END:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{requestAPEnd:t.metric})});case bC.KEY_METRIC_JOIN_GATEWAY_START:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case bC.KEY_METRIC_JOIN_GATEWAY_END:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case bC.KEY_METRIC_PEER_CONNECTION_START:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case bC.KEY_METRIC_PEER_CONNECTION_END:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case bC.KEY_METRIC_DESCRIPTION_START:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{descriptionStart:t.metric})});case bC.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case bC.KEY_METRIC_ICE_CONNECTION_END:return AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case bC.KEY_METRIC_PUBLISH:{const i=e.keyMetrics.publish,n=i.findIndex((e=>e.trackId===t.metric.trackId));return-1!==n?(i[n]=AC(AC({},i[n]),t.metric),AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{publish:[...i]})})):AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case bC.KEY_METRIC_SUBSCRIBE:{const i=e.keyMetrics.subscribe,n=i.findIndex((e=>e.userId===t.metric.userId&&e.type===t.metric.type));return-1!==n?(i[n]=AC(AC({},i[n]),t.metric),AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{subscribe:[...i]})})):AC(AC({},e),{},{keyMetrics:AC(AC({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case bC.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case bC.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=AC(AC({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case bC.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case bC.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[]},e;case bC.SET_USE_DATACHANNEL:return AC(AC({},e),{},{useDataChannel:t.val});case bC.SET_USE_P2P:return AC(AC({},e),{},{useP2P:t.val});default:return e}}(this.state,e)}set sessionId(e){this.dispatch({type:bC.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}get codec(){return this.state.codec}get audioCodec(){return this.state.audioCodec}get clientId(){return this.state.clientId}set p2pId(e){this.dispatch({type:bC.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:bC.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:bC.SET_UID,uid:e})}get uid(){return this.state.uid}set pubId(e){this.dispatch({type:bC.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:bC.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useDataChannel(e){this.dispatch({type:bC.SET_USE_DATACHANNEL,val:e})}get useDataChannel(){return this.state.useDataChannel}set useP2P(e){this.dispatch({type:bC.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}clientCreated(){this.dispatch({type:bC.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:bC.KEY_METRIC_JOIN_START,metric:Date.now()})}joinEnd(){this.dispatch({type:bC.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:bC.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:bC.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:bC.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:bC.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:bC.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:bC.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}descriptionStart(){this.dispatch({type:bC.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:bC.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:bC.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,n){this.dispatch({type:bC.KEY_METRIC_PUBLISH,metric:AC(AC({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})})}subscribe(e,t,i,n,r,s,o){this.dispatch({type:bC.KEY_METRIC_SUBSCRIBE,metric:AC(AC(AC(AC(AC({userId:e,type:t},i&&{subscribeStart:i}),n&&{subscribeEnd:n}),r&&{firstFrame:r}),s&&{streamAdded:s}),o&&{firstDecoded:o})})}massSubscribe(e,t,i,n){e.forEach((e=>{this.dispatch({type:bC.KEY_METRIC_SUBSCRIBE,metric:AC(AC(AC({userId:e.userId,type:e.type},t&&{subscribeStart:t}),i&&{subscribeEnd:i}),n&&{firstFrame:n})})}))}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(e,t){"gateway"===e.service&&Array.isArray(e.urls)&&(e.urls=e.urls.map((e=>e.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2"))));try{return"number"!=typeof t?(this.dispatch({type:bC.RECORD_JOIN_CHANNEL_SERVICE,record:AC(AC({},e),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(t<0||t>=this.state.joinChannelServiceRecords.length||this.dispatch({type:bC.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:bC.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:bC.RESET_KEY_METRICS})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}get avoidJoinStart(){return this.state.avoidJoinStart}set avoidJoinStart(e){this.dispatch({type:bC.AVOID_JOIN_START,avoidJoinStart:e})}}const OC=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-alpha\.([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],i=t[2];return"".concat(e,".").concat(i)}const i=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-special\.([0-9]+)/);if(i&&i[1]&&i[2]){const e=i[1],t=i[2];return"".concat(e,".").concat(100*(Number(t)+1))}return"4.0.0.999"}("4.19.1"),NC=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}(),DC="v4.19.1-0-g605286cc(10/11/2023, 2:37:03 PM)",PC={PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",ENABLE_EVENT_REPORT:!0,GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],SUBSCRIBE_TWCC:!1,PUBLISH_TWCC:!1,PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],WORKER_DOMAIN:"edge.agora.io",TURN_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,PRELOAD_MEDIA_COUNT:0,USE_PUB_RTX:!1,USE_SUB_RTX:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:"",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:["agora.io","sd-rtn.com"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!0,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,ENABLE_PUBLISHED_USER_LIST:!0,MAX_SUBSCRIPTION:50,X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:["data-reporting.agora.io","data-reporting.agora.io"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,VIDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,DISABLE_FEC:void 0,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,DISABLE_DUAL_STREAM_USE_ENCODING:!1,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,NEW_ICE_RESTART:!1,ENABLE_USER_LICENSE_CHECK:!0,SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,FINGERPRINT:null,DC_JOIN_WITH_FAILBACK:5e3,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,AP_AREA:!0,SVC:[],ENABLE_ENCODED_TRANSFORM:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,RTM2_FLAG:void 0,AP_RTM:!1,ENABLE_DATASTREAM_2:!1,DATASTREAM_MAX_RETRANSMITS:10,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_INSTANT_VIDEO:!1,ENABLE_NTP_REPORT:!1,USE_XR:!1,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:1e4,P2P:!1,SHOW_P2P_LOG:!1,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0}};function LC(e,t,i){var n,r;Lr(n=Object.keys(PC)).call(n,e)&&(!i&&Lr(r=Object.keys(MC)).call(r,e)||(PC[e]=t))}function kC(e){return PC[e]}const MC={},UC=new class extends iS{reportLogUploadError(e){this.emit("REPORT_LOG_UPLOAD",e)}};class xC{constructor(e){nu(this,"logger",void 0),nu(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.debug(...this.prefixLists,...t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.info(...this.prefixLists,...t)}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.warning(...this.prefixLists,...t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.error(...this.prefixLists,...t)}prefix(e){return this.prefixLists.push(e),this}popPrefix(){return this.prefixLists.pop(),this}}function VC(){const e=new Date;return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function FC(){const e=new Date,t=/((\d+:){2}\d+)/.exec((new Date).toUTCString());return t?(null==t?void 0:t[0])+":"+e.getUTCMilliseconds():e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}const BC={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},jC=Date.now(),GC=e=>{for(const t in BC)if(Object.prototype.hasOwnProperty.call(BC,t)&&BC[t]===e)return t;return"DEFAULT"},WC=new class{constructor(){nu(this,"proxyServerURL",void 0),nu(this,"logLevel",BC.DEBUG),nu(this,"uploadState","collecting"),nu(this,"uploadLogWaitingList",[]),nu(this,"uploadLogUploadingList",[]),nu(this,"uploadErrorCount",0),nu(this,"currentLogID",0),nu(this,"url",void 0),nu(this,"extLog",((e,t)=>{this.appendLogToWaitingList(e,...t)}))}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[BC.DEBUG].concat(t);this.log.apply(this,n)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[BC.INFO].concat(t);this.log.apply(this,n)}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[BC.WARNING].concat(t);this.log.apply(this,n)}warn(){this.warning(...arguments)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[BC.ERROR].concat(t);this.log.apply(this,n)}upload(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[BC.DEBUG].concat(t);this.uploadLog.apply(this,n)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){LC("UPLOAD_LOG",!0)}disableLogUpload(){LC("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new xC(this).prefix(e)}log(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-jC<100)return void setTimeout((()=>{this.log(...t)}),Date.now()-jC);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=VC()+" Agora-SDK [".concat(GC(n),"]:"),this.appendLogToWaitingList(n,...t),n<this.logLevel)return;const r=VC()+" %cAgora-SDK [".concat(GC(n),"]:");let s=[];if(!kC("USE_NEW_LOG"))switch(n){case BC.DEBUG:s=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,s);break;case BC.INFO:s=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,s);break;case BC.WARNING:s=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,s);break;case BC.ERROR:s=[r,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,s)}}uploadLog(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-jC<100)return void setTimeout((()=>{this.uploadLog(...t)}),Date.now()-jC);const n=Math.max(0,Math.min(4,t[0]));t[0]=VC()+" Agora-SDK [".concat(GC(n),"]:"),this.appendLogToWaitingList(n,...t)}appendLogToWaitingList(e){if(!kC("UPLOAD_LOG"))return;for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];Array.isArray(i[0])?i[0][0]=FC()+" Agora-SDK [".concat(GC(e),"]:"):i[0]=FC()+" Agora-SDK [".concat(GC(e),"]:");let r="";i.forEach((e=>{"object"==typeof e&&(e=JSON.stringify(e)),r+="".concat(e," ")})),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}startUpload(){this.uploadState="uploading",0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:OC,process_id:kC("PROCESS_ID"),payload:JSON.stringify(e)};return XS((async()=>{const e=await EC.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(kC("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(kC("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if("OK"!==e.data){const t=new Error("unexpected upload log response");throw t.response=e,t}}),(()=>(this.uploadLogUploadingList=[],!1)),(e=>(e.response?UC.reportLogUploadError({status:e.response.status,data:e.response.data,headers:e.response.headers,message:e.message}):e.request?UC.reportLogUploadError({status:e.request.status,message:e.message}):UC.reportLogUploadError({status:-1,message:e.message}),!0)),{timeout:kC("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:kC("UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL")})}uploadLogInterval(){0===this.uploadLogUploadingList.length&&0===this.uploadLogWaitingList.length||(0===this.uploadLogUploadingList.length&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,kC("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then((()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout((()=>this.uploadLogInterval()),kC("UPLOAD_LOG_INTERVAL"))})).catch((e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout((()=>this.uploadLogInterval()),kC("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout((()=>this.uploadLogInterval()),kC("UPLOAD_LOG_RETRY_INTERVAL_V1"))})))}};var HC,KC;function YC(e){return Wg(e.reportId,"params.reportId",0,100,!1),Wg(e.category,"params.category",0,100,!1),Wg(e.event,"params.event",0,100,!1),Wg(e.label,"params.label",0,100,!1),jg(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}!function(e){e.FREE="free",e.UPLOADING="uploading"}(HC||(HC={})),function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="PUBLIC_API"}(KC||(KC={}));const qC={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};var JC,zC,XC,QC;function ZC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function $C(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ZC(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ZC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe",e.WS_COMPRESSOR_INIT="ws_compressor_init",e.SESSION_INIT="session_init",e.JOIN_CHOOSE_SERVER="join_choose_server",e.REQ_USER_ACCOUNT="req_user_account",e.JOIN_GATEWAY="join_gateway",e.REJOIN_GATEWAY="rejoin_gateway",e.STREAM_SWITCH="stream_switch",e.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",e.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",e.FIRST_VIDEO_RECEIVED="first_video_received",e.FIRST_AUDIO_RECEIVED="first_audio_received",e.FIRST_VIDEO_DECODE="first_video_decode",e.FIRST_AUDIO_DECODE="first_audio_decode",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_UPDATE_STREAM="on_update_stream",e.ON_REMOVE_STREAM="on_remove_stream",e.USER_ANALYTICS="req_user_analytics",e.PC_STATS="pc_stats"}(JC||(JC={})),function(e){e.SESSION="io.agora.pb.Wrtc.Session",e.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",e.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",e.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",e.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",e.PUBLISH="io.agora.pb.Wrtc.Publish",e.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",e.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",e.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",e.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",e.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",e.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",e.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",e.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",e.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",e.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",e.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",e.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",e.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",e.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",e.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",e.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",e.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",e.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",e.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",e.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",e.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",e.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",e.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",e.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",e.PC_STATS="io.agora.pb.Wrtc.PCStats"}(zC||(zC={})),function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"}(XC||(XC={})),function(e){e[e.SESSION=26]="SESSION",e[e.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",e[e.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",e[e.JOIN_GATEWAY=28]="JOIN_GATEWAY",e[e.PUBLISH=30]="PUBLISH",e[e.SUBSCRIBE=29]="SUBSCRIBE",e[e.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",e[e.STREAM_SWITCH=32]="STREAM_SWITCH",e[e.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",e[e.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",e[e.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",e[e.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",e[e.API_INVOKE=41]="API_INVOKE",e[e.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",e[e.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",e[e.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",e[e.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",e[e.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",e[e.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",e[e.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",e[e.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",e[e.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",e[e.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",e[e.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",e[e.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",e[e.USER_ANALYTICS=1e4]="USER_ANALYTICS",e[e.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED"}(QC||(QC={}));class ev{constructor(){nu(this,"baseInfoMap",new Map),nu(this,"proxyServer",void 0),nu(this,"eventUploadTimer",void 0),nu(this,"setSessionIdTimer",void 0),nu(this,"url",void 0),nu(this,"backupUrl",void 0),nu(this,"_appId",void 0),nu(this,"keyEventUploadPendingItems",[]),nu(this,"normalEventUploadPendingItems",[]),nu(this,"apiInvokeUploadPendingItems",[]),nu(this,"apiInvokeCount",0),nu(this,"ltsList",[]),nu(this,"lastSendNormalEventTime",Date.now()),nu(this,"customReportCounterTimer",void 0),nu(this,"customReportCount",0),nu(this,"extApiInvoke",(async e=>{for(const t of e){const e=$C($C({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:oS.TRACER});this.sendApiInvoke(e)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),kC("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),kC("EVENT_REPORT_SEND_INTERVAL"))}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e)}adjustSessionStartTime(e){if(!this.baseInfoMap.has(e)&&!this.baseInfoMap.get(e))return void WC.error("adjust session ".concat(e," start time, sid is not exist or info is undefined"));const t=this.baseInfoMap.get(e),i=Date.now(),n=t.startTime;t.startTime=i,WC.debug("rewrite session ".concat(e," startTime: ").concat(i," , ").concat(i-n,"ms")),this.baseInfoMap.set(e,t)}setAppId(e){this._appId=e}reportApiInvoke(e,t,i){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const n=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,s=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:n,options:t.options,states:t.states||null}),o=!!kC("SHOW_REPORT_INVOKER_LOG");o&&WC.info("".concat(t.name," start"),t.options);let a=!1;US(t.timeout).then((()=>{a||(this.sendApiInvoke($C($C({},s()),{},{error:xg.API_INVOKE_TIMEOUT,success:!1})),WC.debug("".concat(t.name," timeout")))}));const c=new Vg(xg.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const n=()=>{if(a)throw c;return a=!0,this.sendApiInvoke($C($C({},s()),{},{success:!0},t.reportResult&&{result:e})),o&&WC.info("".concat(t.name," onSuccess")),e};return i?jS(n,t.name+"Success",i,(()=>a=!0)):n()},onError:e=>{const n=()=>{if(a)throw e;a=!0,this.sendApiInvoke($C($C({},s()),{},{success:!1,error:e})),o&&WC.info("".concat(t.name," onFailure"),e.toString())};return i?jS(n,t.name+"Error",i,(()=>a=!0)):n()}}}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const i=Date.now(),n=this.createBaseInfo(e,i);n.cname=t.cname;const r=Object.assign({},{willUploadConsoleLog:kC("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:NC?"global":"oversea",areas:kC("AREAS")&&kC("AREAS").join(",")},t.extend),s=Date.now(),o=$C($C({},n),{},{eventType:JC.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,build:DC,lts:s,elapse:s-i,extend:JSON.stringify(r),mode:t.mode,process:kC("PROCESS_ID"),appType:kC("APP_TYPE"),success:!0,version:OC});this.send({type:zC.SESSION,data:o},!0)}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.JOIN_CHOOSE_SERVER,lts:r,eventElapse:r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-i.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||"",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3});this.send({type:zC.JOIN_CHOOSE_SERVER,data:s},!0)}reqUserAccount(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:r-i.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:zC.REQ_USER_ACCOUNT,data:s},!0)}joinGateway(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info;t.vid&&(n.vid=t.vid),n.uid=t.uid,n.cid=t.cid;const r=Date.now(),{firstSuccess:s,avoidJoinStartTime:o,isProxy:a,addr:c}=t,d=r-(s&&o?o:i.startTime),l=$C($C({},n),{},{eventType:JC.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,elapse:d,eventElapse:r-t.lts,firstSuccess:s,signalChannel:t.signalChannel}),h=l.success?1:0;if(t.succ&&(i.lastJoinSuccessTime=r),s)this.send({type:zC.JOIN_GATEWAY,data:l},!0);else{let e;if(c)if(a){const t=c.match(/h=(\d{1,3}-){3}\d{1,3}/g),i=c.match(/p=[0-9]{1,6}/g);e={isSuccess:h,gatewayIp:t&&t.length?t[0].split("=")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split("=")[1]:"",isProxy:a?1:0}}else{const t=c.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),i=c.match(/(:|p=)[0-9]{1,6}/g);e={isSuccess:h,gatewayIp:t&&t.length?t[0].split("//")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split(/:|p=/g)[1]:"",isProxy:a?1:0}}else e={isSuccess:h,gatewayIp:"",port:"",isProxy:a?1:0};delete l.success,delete l.eventType,delete l.firstSuccess,l.vid=Number(l.vid);const t=Object.assign({},l,e,{eventType:JC.REJOIN_GATEWAY});this.send({type:zC.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=$C($C({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:zC.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-i.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:zC.PUBLISH,data:s},!0)}subscribe(e,t,i){const n=this.baseInfoMap.get(e);if(!n)return;const r=n.info,s=Date.now(),o=$C($C({},r),{},{eventType:JC.SUBSCRIBE,lts:s,eventElapse:t.eventElapse,elapse:s-n.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid},i&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?o.peerSuid=t.peerid:o.peer=t.peerid,this.send({type:zC.SUBSCRIBE,data:o},!0)}wsCompressorInit(e){var t;const i=[...hu(t=this.baseInfoMap).call(t)],n=i.length?i[0]:"UnableToGetSid",r=this.baseInfoMap.get(n);if(!r)return;const s=r.info,o=Date.now(),a=$C($C({},s),{},{eventType:JC.WS_COMPRESSOR_INIT,lts:o,eventElapse:e.eventElapse,elapse:o-r.startTime,status:e.status?1:2});this.send({type:zC.WS_COMPRESSOR_INIT,data:a},!0)}firstRemoteVideoDecode(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=$C($C($C({},s),n),{},{elapse:o-r.startTime,eventType:t,lts:o,firstDecodeFrame:Math.max(o-r.startTime,0),apEnd:Math.max(n.apEnd-r.startTime,0),apStart:Math.max(n.apStart-r.startTime,0),joinGwEnd:Math.max(n.joinGwEnd-r.startTime,0),joinGwStart:Math.max(n.joinGwStart-r.startTime,0),pcEnd:Math.max(n.pcEnd-r.startTime,0),pcStart:Math.max(n.pcStart-r.startTime,0),subscriberEnd:Math.max(n.subscriberEnd-r.startTime,0),subscriberStart:Math.max(n.subscriberStart-r.startTime,0),videoAddNotify:Math.max(n.videoAddNotify-r.startTime,0)});this.send({type:i,data:a},!0)}firstRemoteFrame(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=$C($C($C({},s),n),{},{elapse:o-r.startTime,eventType:t,lts:o});this.send({type:i,data:a},!0)}pcStats(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C($C({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:JC.PC_STATS,lts:r});this.send({type:zC.PC_STATS,data:s},!0)}onGatewayStream(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=$C($C($C({},s),n),{},{eventType:t,lts:o});this.send({type:i,data:a},!0)}streamSwitch(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:zC.STREAM_SWITCH,data:s},!0)}requestProxyAppCenter(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:zC.REQUEST_PROXY_APPCENTER,data:s},!0)}requestProxyWorkerManager(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{eventType:JC.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:zC.REQUEST_PROXY_WORKER_MANAGER,data:s},!0)}setProxyServer(e){this.proxyServer=e,e?WC.debug("reportProxyServerurl: ".concat(e)):WC.debug("disable reportProxyServerurl: ".concat(e))}peerPublishStatus(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C({},n),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:r,elapse:r-i.startTime,joinChannelSuccessElapse:r-(i.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:zC.PEER_PUBLISH_STATUS,data:s},!0)}workerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=function(e,t,i){const n=e[t];if(!n||"string"!=typeof n)return[e];e[t]="";const r=LS(JSON.stringify(e));let s=0;const o=[];let a=0;for(let c=0;c<n.length;c++)a+=n.charCodeAt(c)<=127?1:3,a<=i-r||(o[o.length]=vS(vS({},e),{},{[t]:n.substring(s,c)}),s=c,a=n.charCodeAt(c)<=127?1:3);return s!==n.length-1&&(o[o.length]=vS(vS({},e),{},{[t]:n.substring(s)})),o}($C($C($C({},n),t),{},{elapse:r-i.startTime,lts:r,productType:"WebRTC"}),"payload",1300);s.forEach((e=>this.send({type:zC.WORKER_EVENT,data:e},!0)))}apworkerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C($C({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:zC.AP_WORKER_EVENT,data:s},!0)}joinWebProxyAP(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C($C({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:zC.JOIN_WEB_PROXY_AP,data:s},!0)}WebSocketQuit(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=$C($C($C({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:zC.WEBSOCKET_QUIT,data:s},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>kC("CUSTOM_REPORT_LIMIT"))throw new Vg(xg.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval((()=>{this.customReportCount=0}),5e3));const i=Date.now(),n=t.map((t=>({type:zC.USER_ANALYTICS,data:$C($C({sid:e},t),{},{lts:i})})));try{kC("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n)}catch(e){throw WC.error("send custom report message failed",e.toString()),new Vg(xg.CUSTOM_REPORT_SEND_FAILED,e.message)}}sendApiInvoke(e){const t=kC("NOT_REPORT_EVENT");if(e.tag&&Lr(t)&&Lr(t).call(t,e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const i=this.baseInfoMap.get(e.sid);if(!i)return this.apiInvokeUploadPendingItems.push(e),!1;const{cname:n,uid:r,cid:s}=i.info;let o;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof Vg){const{code:t,message:i}=e.error;o=t||i||e.error.toString()}else o=e.error.toString();const a={invokeId:e.invokeId,sid:e.sid,cname:n,cid:s,uid:r,lts:e.lts,success:e.success,elapse:e.lts-i.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?o:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:zC.API_INVOKE,data:a},!1),!0}appendSessionId(){ev.__CLIENT_LIST__.forEach((e=>{if(e._sessionId){const t=this.apiInvokeUploadPendingItems.length;for(let i=0;i<t;i++){const t=this.apiInvokeUploadPendingItems.shift();t&&(t.sid=e._sessionId,this.sendApiInvoke(Object.assign({},t)))}}}))}send(e,t){if(t)return this.keyEventUploadPendingItems.push(e),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(e),this.normalEventUploadPendingItems.length>kC("NORMAL_EVENT_QUEUE_CAPACITY")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1)}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1)}sendItems(e,t){const i=[],n=[];for(;e.length;){const t=e.shift();i.length<20?i.push(t):n.push(t)}e.push(...n);for(const e of[...i]){var r;-1!==this.ltsList.indexOf(e.data.lts)?(e.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(e.data.lts)):(this.ltsList.push(e.data.lts),Zu(r=this.ltsList).call(r,((e,t)=>e-t)))}return t||(this.lastSendNormalEventTime=Date.now()),kC("ENABLE_EVENT_REPORT")?(i.length&&(kC("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{kC("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>kC("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-kC("NORMAL_EVENT_QUEUE_CAPACITY")),WC.warning("report: drop normal events"))))})(i)),e):e}async postDataToStatsCollector2(e){RS.networkState===hS.OFFLINE&&await tg.race([RS.onlineWaiter,US(2*JS.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach((e=>{const i=Zg(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(zC).forEach((i=>{let[n,r]=i;r===e.type&&(t=EventNameToID[n])})),t})(e),s=new DataView(n);s.setUint16(0,i.byteLength,!0),s.setUint8(2,255&r),s.setUint8(3,r>>>8&255),s.setUint8(4,r>>>16&255),t=$g(t,new Uint8Array(n)),t=$g(t,i)})),t},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(kC("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(kC("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(i);for(let r=0;r<2;r+=1){1===r&&(n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(kC("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(kC("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await RC(n,{timeout:1e4,data:t(e),headers:$C($C({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0)}catch(e){if(1===r)throw e;continue}return}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map((e=>JSON.stringify(e))),vid:(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0])};RS.networkState===hS.OFFLINE&&await tg.race([RS.onlineWaiter,US(2*JS.maxRetryTimeout)]);const n=t?"/events/proto-raws":"/events/messages";let r=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(kC("EVENT_REPORT_DOMAIN"),"&p=").concat(kC("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(kC("EVENT_REPORT_DOMAIN"),":").concat(kC("STATS_COLLECTOR_PORT")).concat(n));for(let e=0;e<2;e+=1){1===e&&(r=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(kC("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(kC("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(kC("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(kC("STATS_COLLECTOR_PORT")).concat(n)));try{t?await CC(r,{timeout:1e4,data:i}):await RC(r,{timeout:1e4,data:i})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const i=Object.assign({},qC);return i.sid=e,this.baseInfoMap.set(e,{info:i,startTime:t}),i}reportResourceTiming(e,t){const i=performance.getEntriesByName(e),n=i[i.length-1];n&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:n,tag:oS.TRACER}).onSuccess()}}function tv(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,i,n){const r=n.value;if("function"==typeof r){const s=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);n.value=function(){for(var t=arguments.length,n=new Array(t),o=0;o<t;o++)n[o]=arguments[o];let a=n;if(e.argsMap)try{a=e.argsMap(this,...n)}catch(e){WC.warning(e),a=[]}try{JSON.stringify(a)}catch(e){WC.warning("arguments for method ".concat(s,".").concat(String(i)," not serializable for apiInvoke.")),a=[]}const c=(e.report||iv).reportApiInvoke(this._sessionId||null,{name:"".concat(s,".").concat(String(i)),options:a,tag:oS.TRACER,reportResult:e.reportResult},e.throttleTime);try{const t=r.apply(this,n);return t instanceof tg?t.then((t=>(c.onSuccess(e.reportResult&&t),t))).catch((e=>{throw c.onError(e),e})):(c.onSuccess(e.reportResult&&t),t)}catch(e){throw c.onError(e),e}}}return n}}nu(ev,"__CLIENT_LIST__",[]);const iv=new ev;UC.on("REPORT_LOG_UPLOAD",(e=>{e.networkState=RS.networkState,iv.reportApiInvoke(null,{name:"logUploadError",options:e,tag:oS.TRACER})}));const nv=["CHINA","GLOBAL"],rv=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),i=["t","s","t"];i.splice(1,0,"e");const n=i.join(""),r=[];for(let e=0;e<6;e++)r.push("1");const s=r.join(""),o={};return o[e]=n,o[t]=s,Object.assign(o,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=rv,NC||(PC.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],PC.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],PC.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],PC.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],PC.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],PC.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],PC.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",PC.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",PC.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",PC.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",PC.AREAS=["NORTH_AMERICA","OVERSEA"]);const sv=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],ov=[];function av(e,t){return!!t&&ov.some((i=>i.uid===e&&i.channelName===t))}ev.__CLIENT_LIST__=ov;var cv,dv,lv,hv,uv,pv,_v,Ev,mv,fv,gv,Sv,Tv,Rv,Cv,vv,Iv,yv=tr("Array").values,Av=mr,bv=ri,wv=me,Ov=yv,Nv=Array.prototype,Dv={DOMTokenList:!0,NodeList:!0},Pv=z((function(e){var t=e.values;return e===Nv||wv(Nv,e)&&t===Nv.values||bv(Dv,Av(e))?Ov:t}));function Lv(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o}function kv(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}!function(e){e.L1T1="L1T1",e.L1T2="L1T2",e.L1T3="L1T3",e.L2T1_KEY="L2T1_KEY",e.L2T2_KEY="L2T2_KEY",e.L2T3_KEY="L2T3_KEY",e.L3T1_KEY="L3T1_KEY",e.L3T2_KEY="L3T2_KEY",e.L3T3_KEY="L3T3_KEY"}(cv||(cv={})),function(e){e.CERTIFICATE="certificate",e.CODEC="codec",e.CANDIDATE_PAIR="candidate-pair",e.LOCAL_CANDIDATE="local-candidate",e.REMOTE_CANDIDATE="remote-candidate",e.INBOUND="inbound-rtp",e.TRACK="track",e.OUTBOUND="outbound-rtp",e.PC="peer-connection",e.REMOTE_INBOUND="remote-inbound-rtp",e.REMOTE_OUTBOUND="remote-outbound-rtp",e.TRANSPORT="transport",e.CSRC="csrc",e.DATA_CHANNEL="data-channel",e.STREAM="stream",e.SENDER="sender",e.RECEIVER="receiver"}(dv||(dv={})),function(e){e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR"}(lv||(lv={})),function(e){e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR"}(hv||(hv={})),function(e){e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND"}(uv||(uv={})),function(e){e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV"}(pv||(pv={})),function(e){e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY"}(_v||(_v={})),function(e){e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed"}(Ev||(Ev={})),function(e){e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_WAITTING_FINISH="ws_reconnect_waitting_finish",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_REJOIN_INFO="req_rejoin_info",e.IS_P2P_DISCONNECTED="is_p2p_dis",e.DISCONNECT_P2P="dis_p2p",e.ABORT_P2P_EXECUTION="abort_p2p_execution",e.NEED_RENEW_SESSION="need-sid",e.REPORT_JOIN_GATEWAY="report_join_gateway",e.REQUEST_TIMEOUT="request_timeout",e.REQUEST_SUCCESS="request_success",e.JOIN_RESPONSE="join_response",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_CONNECTING="datachannel_connecting",e.DATACHANNEL_FAILBACK="datachannel_failback",e.P2P_START="p2p_start",e.P2P_CONNECTION="p2p_connection",e.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",e.P2P_SUBSCRIBE="p2p_subscribe",e.P2P_UNSUBSCRIBE="p2p_unsubscribe",e.P2P_EXCHANGE_SDP="p2p_exchange_sdp",e.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",e.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream"}(mv||(mv={})),function(e){e.PING="ping",e.PING_BACK="ping_back",e.JOIN="join_v3",e.REJOIN="rejoin_v3",e.LEAVE="leave",e.SET_CLIENT_ROLE="set_client_role",e.PUBLISH="publish",e.PUBLISH_DATASTREAM="publish_datastream",e.UNPUBLISH="unpublish",e.UNPUBLISH_DATASTREAM="unpublish_datastream",e.SUBSCRIBE="subscribe",e.SUBSCRIBE_DATASTREAM="subscribe_datastream",e.SUBSCRIBE_STREAMS="subscribe_streams",e.UNSUBSCRIBE="unsubscribe",e.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",e.UNSUBSCRIBE_STREAMS="unsubscribe_streams",e.SUBSCRIBE_CHANGE="subscribe_change",e.TRAFFIC_STATS="traffic_stats",e.RENEW_TOKEN="renew_token",e.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",e.GATEWAY_INFO="gateway_info",e.CONTROL="control",e.SEND_METADATA="send_metadata",e.DATA_STREAM="data_stream",e.PICK_SVC_LAYER="pick_svc_layer",e.RESTART_ICE="restart_ice",e.CONNECT_PC="connect_pc",e.SET_VIDEO_PROFILE="set_video_profile",e.SET_PARAMETER="set_parameter",e.SET_RTM2_FLAG="set_rtm2_flag"}(fv||(fv={})),function(e){e.PUBLISH_STATS="publish_stats",e.PUBLISH_RELATED_STATS="publish_related_stats",e.SUBSCRIBE_STATS="subscribe_stats",e.SUBSCRIBE_RELATED_STATS="subscribe_related_stats",e.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",e.DENOISER_STATS="denoiser_stats",e.TRANSPORT_STATS="transport_stats",e.EXTENSION_USAGE_STATS="extension_usage_stats"}(gv||(gv={})),function(e){e.ON_USER_ONLINE="on_user_online",e.ON_USER_OFFLINE="on_user_offline",e.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",e.ON_PUBLISH_STREAM="on_publish_stream",e.ON_UPLINK_STATS="on_uplink_stats",e.ON_P2P_LOST="on_p2p_lost",e.ON_REMOVE_STREAM="on_remove_stream",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",e.ON_USER_BANNED="on_user_banned",e.ON_USER_LICENSE_BANNED="on_user_license_banned",e.ON_NOTIFICATION="on_notification",e.ON_CRYPT_ERROR="on_crypt_error",e.MUTE_AUDIO="mute_audio",e.MUTE_VIDEO="mute_video",e.UNMUTE_AUDIO="unmute_audio",e.UNMUTE_VIDEO="unmute_video",e.ON_P2P_OK="on_p2p_ok",e.RECEIVE_METADATA="receive_metadata",e.ON_DATA_STREAM="on_data_stream",e.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",e.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",e.ENABLE_LOCAL_VIDEO="enable_local_video",e.DISABLE_LOCAL_VIDEO="disable_local_video",e.ENABLE_LOCAL_AUDIO="enable_local_audio",e.DISABLE_LOCAL_AUDIO="disable_local_audio",e.ON_PUBLISHED_USER_LIST="on_published_user_list"}(Sv||(Sv={})),function(e){e.CONNECTION_STATE_CHANGE="CONNECTION_STATE_CHANGE",e.NEED_ANSWER="NEED_ANSWER",e.NEED_RENEGOTIATE="NEED_RENEGOTIATE",e.P2P_LOST="P2P_LOST",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NEED_UNPUB="NEED_UNPUB",e.NEED_UNSUB="NEED_UNSUB",e.NEED_UPLOAD="NEED_UPLOAD",e.NEED_CONTROL="NEED_CONTROL",e.START_RECONNECT="START_RECONNECT",e.END_RECONNECT="END_RECONNECT",e.NEED_SIGNAL_RTT="NEED_SIGNAL_RTT"}(Tv||(Tv={})),function(e){e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY"}(Rv||(Rv={})),function(e){e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_WAITTING_FINISH="websocket:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire"}(Cv||(Cv={}));class Mv extends Vg{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),nu(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,WC)}throw(){super.throw(WC)}}function Uv(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw WC.error("Invalid Channel Name ".concat(e)),new Mv(xg.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function xv(e){if(!("number"==typeof(t=e)&&Math.floor(t)===t&&0<=t&&t<=4294967295||Yg(e,1,255)))throw new Mv(xg.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;"string"==typeof e&&WC.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}!function(e){e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e.INJECT="inject_streaming"}(vv||(vv={})),function(e){e[e.INJECT_STREAM_STATUS_START_SUCCESS=0]="INJECT_STREAM_STATUS_START_SUCCESS",e[e.INJECT_STREAM_STATUS_START_ALREADY_EXISTS=1]="INJECT_STREAM_STATUS_START_ALREADY_EXISTS",e[e.INJECT_STREAM_STATUS_START_UNAUTHORIZED=2]="INJECT_STREAM_STATUS_START_UNAUTHORIZED",e[e.INJECT_STREAM_STATUS_START_TIMEOUT=3]="INJECT_STREAM_STATUS_START_TIMEOUT",e[e.INJECT_STREAM_STATUS_START_FAILED=4]="INJECT_STREAM_STATUS_START_FAILED",e[e.INJECT_STREAM_STATUS_STOP_SUCCESS=5]="INJECT_STREAM_STATUS_STOP_SUCCESS",e[e.INJECT_STREAM_STATUS_STOP_NOT_FOUND=6]="INJECT_STREAM_STATUS_STOP_NOT_FOUND",e[e.INJECT_STREAM_STATUS_STOP_UNAUTHORIZED=7]="INJECT_STREAM_STATUS_STOP_UNAUTHORIZED",e[e.INJECT_STREAM_STATUS_STOP_TIMEOUT=8]="INJECT_STREAM_STATUS_STOP_TIMEOUT",e[e.INJECT_STREAM_STATUS_STOP_FAILED=9]="INJECT_STREAM_STATUS_STOP_FAILED",e[e.INJECT_STREAM_STATUS_BROKEN=10]="INJECT_STREAM_STATUS_BROKEN"}(Iv||(Iv={}));const Vv={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},Fv={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function Bv(e,t){Wg(e.url,"".concat(t,".url"),1,1e3,!1),Kg(e.x)||jg(e.x,"".concat(t,".x"),0,1e4),Kg(e.y)||jg(e.y,"".concat(t,".y"),0,1e4),Kg(e.width)||jg(e.width,"".concat(t,".width"),0,1e4),Kg(e.height)||jg(e.height,"".concat(t,".height"),0,1e4),Kg(e.zOrder)||jg(e.zOrder,"".concat(t,".zOrder"),0,255),Kg(e.alpha)||jg(e.alpha,"".concat(t,".alpha"),0,1,!1)}const jv={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""},Gv={audioBitrate:48,audioChannels:2,audioVolume:100,audioSampleRate:48e3,height:0,width:0,videoBitrate:400,videoFramerate:15,videoGop:30};var Wv,Hv,Kv,Yv,qv,Jv,zv,Xv,Qv,Zv,$v,eI,tI,iI;function nI(e){if(!e.channelName)throw new Mv(xg.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new Mv(xg.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&Wg(e.token,"info.token",1,2047),xv(e.uid),Uv(e.channelName),!0}!function(e){e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.INJECT_STREAM_STATUS="@live_uap-inject-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address"}(Wv||(Wv={})),function(e){e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager"}(Hv||(Hv={})),function(e){e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN"}(Kv||(Kv={})),function(e){e.CONNECT_FAILED="connect failed",e.CONNECT_TIMEOUT="connect timeout",e.WS_DISCONNECTED="websocket disconnected",e.REQUEST_TIMEOUT="request timeout",e.REQUEST_FAILED="request failed",e.WAIT_STATUS_TIMEOUT="wait status timeout",e.WAIT_STATUS_ERROR="wait status error",e.BAD_STATE="bad state",e.WS_ABORT="ws abort",e.AP_REQUEST_TIMEOUT="AP request timeout",e.AP_JSON_PARSE_ERROR="AP json parse error",e.AP_REQUEST_ERROR="AP request error",e.AP_REQUEST_ABORT="AP request abort"}(Yv||(Yv={})),function(e){e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile"}(qv||(qv={})),function(e){e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE"}(Jv||(Jv={})),function(e){e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE"}(zv||(zv={})),function(e){e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED"}(Xv||(Xv={})),function(e){e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low"}(Qv||(Qv={})),function(e){e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.REQUEST_DC_CONNECTION_PARAMS="request-dc-connection-params",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_FAILBACK="datachannel_failback",e.RESET_SIGNAL="reset-signal"}(Zv||(Zv={})),function(e){e.P2P_DISCONNECTED="P2P_DISCONNECTED",e.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",e.TIMEOUT="TIMEOUT",e.UNKNOWN_REASON="UNKNOWN_REASON"}($v||($v={})),function(e){e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LwoVideo=2]="LwoVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7"}(eI||(eI={})),function(e){e[e.websocket=0]="websocket",e[e.datachannel=1]="datachannel"}(tI||(tI={})),function(e){e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS"}(iI||(iI={}));const rI=[iI.AFRICA,iI.ASIA,iI.CHINA,iI.EUROPE,iI.GLOBAL,iI.INDIA,iI.JAPAN,iI.NORTH_AMERICA,iI.OCEANIA,iI.OVERSEA,iI.SOUTH_AMERICA];var sI;!function(e){e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL"}(sI||(sI={}));const oI={CHINA:{},ASIA:{CODE:sI.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:sI.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:sI.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:sI.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","\tuap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:sI.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:sI.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:sI.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:sI.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:sI.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:sI.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:sI.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:sI.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:sI.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};var aI,cI,dI,lI,hI,uI,pI,_I,EI,mI,fI,gI,SI,TI,RI,CI,vI,II,yI,AI,bI,wI;NC&&(oI.CHINA={CODE:sI.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]}),function(e){e.UPDATE_BITRATE_LIMIT="update_bitrate_limit"}(aI||(aI={}));class OI extends iS{constructor(e,t){super(),nu(this,"onICEConnectionStateChange",void 0),nu(this,"onConnectionStateChange",void 0),nu(this,"onDTLSTransportStateChange",void 0),nu(this,"onDTLSTransportError",void 0),nu(this,"onICETransportStateChange",void 0),nu(this,"onFirstAudioReceived",void 0),nu(this,"onFirstVideoReceived",void 0),nu(this,"onFirstAudioDecoded",void 0),nu(this,"onFirstVideoDecoded",void 0),nu(this,"onFirstVideoDecodedTimeout",void 0),nu(this,"onSelectedLocalCandidateChanged",void 0),nu(this,"onSelectedRemoteCandidateChanged",void 0)}}class NI extends OI{constructor(e,t){super(e,t)}}!function(e){e.SEND="sendonly",e.RECV="recvonly",e.SENDRECV="sendrecv",e.INACTIVE="inactive"}(cI||(cI={})),function(e){e.VIDEO="video",e.AUDIO="audio"}(dI||(dI={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.RELAY=2]="RELAY"}(lI||(lI={})),function(e){e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.TCP_RESTART=1]="TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",e[e.OLD_RESTART=11]="OLD_RESTART",e[e.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED"}(hI||(hI={})),function(e){e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack"}(uI||(uI={})),function(e){e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected"}(pI||(pI={})),function(e){e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestRePublishDataChannel="requestRePublishDataChannel",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState",e.LocalCandidate="LocalCandidate",e.RequestP2PMuteLocal="requestP2PMuteLocal",e.RequestP2PPublish="RequestP2PPublish",e.RequestP2PUnPublish="RequestP2PUnPublish",e.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",e.RequestP2PMuteRemote="RequestP2PMuteRemote",e.RequestP2PRestartICE="RequestP2PRestartICE"}(_I||(_I={})),function(e){e.MUTE_LOCAL_VIDEO="mute_local_video",e.MUTE_LOCAL_AUDIO="mute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.MUTE_REMOTE_VIDEO="mute_remote_video",e.MUTE_REMOTE_AUDIO="mute_remote_audio",e.UNMUTE_REMOTE_VIDEO="unmute_remote_video",e.UNMUTE_REMOTE_AUDIO="unmute_remote_audio"}(EI||(EI={})),function(e){e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED"}(mI||(mI={})),function(e){e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED"}(fI||(fI={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url"}(gI||(gI={})),function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK"}(SI||(SI={})),function(e){e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_WAITTING_FINISH="transmitter:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback"}(TI||(TI={})),function(e){e.CAMERA_CHANGED="camera-changed",e.MICROPHONE_CHANGED="microphone-changed",e.PLAYBACK_DEVICE_CHANGED="playback-device-changed",e.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",e.AUTOPLAY_FAILED="autoplay-failed",e.SECURITY_POLICY_VIOLATION="security-policy-violation"}(RI||(RI={})),function(e){e[e.APP_TYPE_INVALID_VALUE=-1]="APP_TYPE_INVALID_VALUE",e[e.APP_TYPE_NATIVE=0]="APP_TYPE_NATIVE",e[e.APP_TYPE_NATIVE_COCOS=1]="APP_TYPE_NATIVE_COCOS",e[e.APP_TYPE_NATIVE_UNITY=2]="APP_TYPE_NATIVE_UNITY",e[e.APP_TYPE_NATIVE_ELECTRON=3]="APP_TYPE_NATIVE_ELECTRON",e[e.APP_TYPE_NATIVE_FLUTTER=4]="APP_TYPE_NATIVE_FLUTTER",e[e.APP_TYPE_NATIVE_UNREAL=5]="APP_TYPE_NATIVE_UNREAL",e[e.APP_TYPE_NATIVE_XAMARIN=6]="APP_TYPE_NATIVE_XAMARIN",e[e.APP_TYPE_NATIVE_API_CLOUD=7]="APP_TYPE_NATIVE_API_CLOUD",e[e.APP_TYPE_NATIVE_REACT_NATIVE=8]="APP_TYPE_NATIVE_REACT_NATIVE",e[e.APP_TYPE_NATIVE_PYTHON=9]="APP_TYPE_NATIVE_PYTHON",e[e.APP_TYPE_NATIVE_COCOS_CREATOR=10]="APP_TYPE_NATIVE_COCOS_CREATOR",e[e.APP_TYPE_NATIVE_RUST=11]="APP_TYPE_NATIVE_RUST",e[e.APP_TYPE_NATIVE_C_SHARP=12]="APP_TYPE_NATIVE_C_SHARP",e[e.APP_TYPE_NATIVE_CEF=13]="APP_TYPE_NATIVE_CEF",e[e.APP_TYPE_NATIVE_UNI_APP=14]="APP_TYPE_NATIVE_UNI_APP",e[e.APP_TYPE_WEBRTC=1e3]="APP_TYPE_WEBRTC",e[e.APP_TYPE_WEBRTC_REACT=1001]="APP_TYPE_WEBRTC_REACT",e[e.APP_TYPE_WEBRTC_VUE=1002]="APP_TYPE_WEBRTC_VUE",e[e.APP_TYPE_WEBRTC_ANGULAR=1003]="APP_TYPE_WEBRTC_ANGULAR"}(CI||(CI={})),function(e){e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED"}(vI||(vI={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url"}(II||(II={})),function(e){e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED"}(yI||(yI={})),function(e){e.CALL="call",e.CANDIDATE="candidate",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.SUBSCRIBE="subscribe",e.UNSUBSCRIBE="unsubscribe",e.CONTROL="control",e.RESTART_ICE="restart_ice",e.ACK="ack",e.JOIN="join",e.EXCHANGE_SDP="exchange_sdp",e.DO_SUBSCRIBE="do_subscribe",e.DO_UNSUBSCRIBE="do_unsubscribe"}(AI||(AI={})),function(e){e.MUTE_LOCAL_AUDIO="mute_local_audio",e.MUTE_LOCAL_VIDEO="mute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video"}(bI||(bI={})),function(e){e[e.SUCCESS=1]="SUCCESS",e[e.FAILED=0]="FAILED"}(wI||(wI={}));const DI={[lv.ACCESS_POINT]:{[pv.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[pv.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[pv.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[pv.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[pv.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[pv.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[pv.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[lv.UNILBS]:{[uv.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[uv.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[uv.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[uv.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[uv.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[uv.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[uv.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[uv.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[uv.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[uv.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[uv.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[uv.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[lv.STRING_UID_ALLOCATOR]:{[hv.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[hv.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[hv.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function PI(e){const t=DI[Math.floor(e/1e4)];if(!t)return{desc:"unkonw error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===lv.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unkonw error",retry:!1}}return i}const LI={[_v.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[_v.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[_v.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[_v.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[_v.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[_v.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[_v.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[_v.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[_v.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[_v.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[_v.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[_v.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[_v.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[_v.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[_v.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[_v.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[_v.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[_v.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[_v.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[_v.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[_v.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[_v.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[_v.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[_v.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[_v.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[_v.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[_v.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[_v.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[_v.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[_v.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[_v.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[_v.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[_v.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[_v.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[_v.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[_v.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[_v.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[_v.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[_v.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[_v.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[_v.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[_v.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[_v.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[_v.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[_v.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[_v.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[_v.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[_v.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[_v.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[_v.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[_v.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[_v.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[_v.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[_v.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[_v.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[_v.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[_v.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[_v.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[_v.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[_v.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[_v.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[_v.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[_v.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function kI(e){return LI[e]||{desc:"UNKNOW_ERROR_".concat(e),action:"failed"}}function MI(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function UI(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?MI(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):MI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function xI(e){return e.every((e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING))}function VI(e,t){if("string"==typeof e)return e;const{proxy:i,host:n,port:r}=e;if(t){const e=kC("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(n,"/ws/?p=").concat(Number(r)+150):"wss://".concat(n,":").concat(e,"/ws/?p=").concat(Number(r)+150)}return i?"wss://".concat(i,"/ws/?h=").concat(n,"&p=").concat(r):"wss://".concat(n,":").concat(r)}const FI=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,BI=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,jI=/wss:\/\/(.+):([0-9]+)\/?/,GI=/wss:\/\/(.[^\/]+)\/?/;let WI=0;class HI{constructor(e,t){nu(this,"id",0),nu(this,"store",void 0),nu(this,"recordIndex",void 0),nu(this,"websockets",[]),nu(this,"try443PortDuration",2e3),nu(this,"forceCloseWSDuration",5e3),nu(this,"try443PortTimeout",null),nu(this,"forceCloseTimeout",null),nu(this,"isTry443PortFailed",!1),nu(this,"isNormalPortFailed",!1),nu(this,"useDoubleDomain",!1),nu(this,"useProxy",!1),nu(this,"startTime",Date.now()),this.id=++WI,this.try443PortDuration=kC("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t}closeAllWebsockets(){this.websockets.forEach((e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close()})),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout)}logger(){var e;const t=Date.now()-this.startTime;for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];WC.debug("[choose-best-ws ".concat(null===(e=this.store)||void 0===e?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...n)}createWebSocket(e,t,i){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:i});const n=kC("GATEWAY_DOMAINS"),r=Date.now(),s=[],o=n.find((t=>{var i;return Lr(i=e.host).call(i,t)}));o||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)n.forEach((i=>{a.push(VI(UI(UI({},e),{},{host:e.host.replace(o,i)}),t))}));else{const i=UI({},e);if(t&&o){const e=n.find((e=>e!==o));e&&(i.host=i.host.replace(o,e))}a.push(VI(i,t))}try{a.forEach((e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",s.push(t),this.logger("ws is connecting:",t.url)}))}catch(n){if(this.logger("ws create failed"),s.forEach((e=>e.close())),s.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,i);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,i);throw new Mv(xg.WS_ERR,"init websocket failed! Error: ".concat(n.toString()))}const c=ng();return this.store&&this.store.recordJoinChannelService({urls:s.map((e=>e.url)),service:"gateway"},this.recordIndex),s.forEach((e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-r,"ms")),this.websockets.forEach((t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)))})),this.websockets.length=0,c.resolve(e)},e.onclose=i=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-r,"ms state: ").concat(e.readyState)),t?this.isTry443PortFailed=xI(s):this.isNormalPortFailed=xI(s),this.logger("443: ".concat(this.useProxy?"not try":this.isTry443PortFailed?"failed":"trying"," 47xx: ").concat(this.isNormalPortFailed?"failed":"trying")),(t&&this.isTry443PortFailed||!t&&(this.isTry443PortFailed||this.useProxy)&&this.isNormalPortFailed)&&(this.logger("onclose: all websocket is closed, ".concat(i.reason)),c.reject({code:i.code,reason:$v.A_ROUND_WS_FAILED}))},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data))})),this.websockets.push(...s),i||(()=>{const i=()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))};if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{if(this.logger("2s timeout, isWebsocket created: ",c.isResolved),c.isResolved)return i();pg().os===ag.MAC_OS&&Rg()&&i(),this.createWebSocket(e,!0,!0).then((e=>c.resolve(e))).catch((e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed")})),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration)}),this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,i,n){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,i,n;return[,t,i,n]=e.match(FI)||[],t||([,i,n]=e.match(BI)||[]),i&&n||([,i,n]=e.match(jI)||[]),i&&n||([,i]=e.match(GI)||[]),i||WC.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"}}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(WC.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally((()=>this.clearTimeout()))}}function KI(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class YI extends iS{get url(){return this.websocket&&this.websocket.url||null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Lr(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(Cv.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(Cv.CONNECTED):"closed"===this._state?this.emit(Cv.CLOSED):"failed"===this._state&&this.emit(Cv.FAILED))}resetReconnectCount(e){WC.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;super(),nu(this,"connectionID",0),nu(this,"currentURLIndex",0),nu(this,"urls",[]),nu(this,"_reconnectMode","tryNext"),nu(this,"reconnectReason",void 0),nu(this,"_initMutex",new YS("websocket")),nu(this,"name",void 0),nu(this,"_state","closed"),nu(this,"reconnectInterrupter",void 0),nu(this,"websocket",void 0),nu(this,"retryConfig",void 0),nu(this,"reconnectCount",0),nu(this,"forceCloseTimeout",5e3),nu(this,"onlineReconnectListener",void 0),nu(this,"useCompress",void 0),nu(this,"tryDoubleDomain",!1),nu(this,"use443PortOnly",!1),nu(this,"wsInflateLength",0),nu(this,"wsDeflateLength",0),nu(this,"closeEstablishingWs",(()=>{})),nu(this,"store",void 0),nu(this,"joinGatewayRecordIndex",void 0),this.store=s,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?KI(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):KI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t),this.useCompress=i,this.tryDoubleDomain=n,this.use443PortOnly=r;const{timeout:o,timeoutFactor:a}=t,c=Math.max(300,Math.floor(3*o/5)),d=Math.max(1.2,Math.floor(8*a)/10);hS.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),RS.on(uS.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===hS.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=o,this.retryConfig.timeoutFactor=a))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=await this._initMutex.lock();this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=ng(),t=this.urls[this.currentURLIndex];this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(Cv.CLOSED,(()=>{e.reject(new Vg(xg.WS_DISCONNECT))})),this.once(Cv.CONNECTED,e.resolve),await e.promise}catch(e){}finally{i()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void WC.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),WC.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Vg(xg.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new Vg(xg.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var t;const i=ng();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),WC.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},r=async e=>{var t;if(WC.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)i.reject(new Vg(xg.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=SS(this,Cv.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void WC.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return i.reject(new Vg(xg.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve()}},s=e=>{this.emit(Cv.ON_MESSAGE,e)},o=e=>{WC.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),kC("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=kC("GATEWAY_WSS_ADDRESS")),WC.debug("[".concat(this.name,"] start connect, url:"),e);const a=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,n&&n(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=s,this.websocket.onerror=o,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this.joinGatewayRecordIndex=a}catch(e){const t="closed"===this.state,n=e instanceof Vg,s=n&&e.code===xg.WS_ABORT,o=n&&e.code===xg.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());WC.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:s?"aborted":"error",errors:[e]},a),t||o?(i.reject(t?new Vg(xg.WS_DISCONNECT,"websocket is closed: ".concat(c)):new Vg(xg.WS_ERR,"init websocket failed: ".concat(c))),o&&WC.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(e)}return i.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;WC.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||RS.isOnline||!RS.onlineWaiter||(this.onlineReconnectListener=RS.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=zS(this.reconnectCount,this.retryConfig);WC.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await tg.race([US(t),this.onlineReconnectListener||new tg((()=>{}))])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(Cv.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(Cv.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);WC.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(Cv.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(WC.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(Cv.RECONNECT_WAITTING_FINISH,e),this.urls=await fS(this,Cv.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(i){var r;WC.error("[".concat(this.name,"] reconnect failed ").concat(i&&i.toString()));const n=null==i||null===(r=i.data)||void 0===r?void 0:r.desc;return Array.isArray(n)&&Lr(n).call(n,"dynamic key expired")?(this.emit(Cv.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class qI extends YI{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){const i=ng(),n=function(e,t){return new HI(e,t)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{WC.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new Vg(xg.WS_ABORT,"choose best websocket aborted"))};const r=kC("GATEWAY_DOMAINS");return WC.debug("[choose-best-ws] currentDomain: ",e,", domains: ",r,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),n.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(i.resolve).catch(i.reject),i.promise.finally((()=>{this.closeEstablishingWs=void 0}))}}class JI extends YI{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){return new tg(((i,n)=>{let r=!1;const s=[];this.closeEstablishingWs=()=>{WC.debug("[choose-best-ws] close establishing websockets"),s.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),n(new Vg(xg.WS_ABORT,"choose best websocket aborted"))};const o=kC("GATEWAY_DOMAINS");let a;const c=e.indexOf("?h="),d=o.find((t=>-1!==c?Lr(e).call(e,t,c):Lr(e).call(e,t)));WC.debug("[choose-best-ws] currentDomain: ",d,", domains: ",o);let l=!this.tryDoubleDomain||!d;if(!l&&d){var h;const u=Date.now();try{o.forEach((t=>{const i=-1===c?e.replace(d,t):e.substr(0,c)+e.substr(c).replace(d,t),n=new WebSocket(i);n.binaryType="arraybuffer",s.push(n),WC.debug("[choose-best-ws] ws is connecting:",n.url)}))}catch(e){for(WC.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEach((e=>e.close()));s.length;)s.pop();l=!0}null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:s.map((e=>e.url)),service:"gateway"},t),s.forEach((e=>{e.onopen=()=>{if(r)return;const t=Date.now()-u;WC.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),s.filter((t=>t!==e)).forEach((e=>{WC.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),r=!0,i(e)},e.onclose=e=>{a=e,r||s.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(WC.debug("[choose-best-ws] all websocket is closed"),r=!0,n(a))},e.onmessage=t=>{WC.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),US(this.forceCloseTimeout).then((()=>{s.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(l){var u;let r;WC.debug("[choose-best-ws] use single url: ",e),null===(u=this.store)||void 0===u||u.recordJoinChannelService({urls:[e],service:"gateway"},t);try{r=new WebSocket(e),s.push(r),r.binaryType="arraybuffer"}catch(e){const t=new Vg(xg.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return WC.error("[".concat(this.name,"]").concat(t)),void n(t)}r.onopen=()=>{i(r)},r.onclose=e=>{n(e)},r.onmessage=e=>{WC.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data))},US(this.forceCloseTimeout).then((()=>{r&&r.readyState!==WebSocket.OPEN&&r.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class zI extends iS{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Ev.CONNECTED?this.emit(mv.WS_CONNECTED):e===Ev.RECONNECTING?this.emit(mv.WS_RECONNECTING,this._websocketReconnectReason):e===Ev.CLOSED&&this.emit(mv.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),nu(this,"_disconnectedReason",void 0),nu(this,"_websocketReconnectReason",void 0),nu(this,"_connectionState",Ev.CLOSED),nu(this,"reconnectToken",void 0),nu(this,"websocket",void 0),nu(this,"openConnectionTime",void 0),nu(this,"clientId",void 0),nu(this,"lastMsgTime",Date.now()),nu(this,"uploadCache",[]),nu(this,"uploadCacheInterval",void 0),nu(this,"rttRolling",new dT(5)),nu(this,"pingpongTimer",void 0),nu(this,"wsInflateDataTimer",void 0),nu(this,"pingpongTimeoutCount",0),nu(this,"joinResponse",void 0),nu(this,"multiIpOption",void 0),nu(this,"initError",void 0),nu(this,"spec",void 0),nu(this,"store",void 0),nu(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(mv.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){if(this.emit(t._type,t._message),t._type===Sv.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Sv.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(cS.UID_BANNED);break;case 15:this.close(cS.IP_BANNED);break;case 16:this.close(cS.CHANNEL_BANNED)}if(t._type===Sv.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case _v.ERR_LICENSE_MISSING:this.close(cS.LICENSE_MISSING);break;case _v.ERR_LICENSE_EXPIRED:this.close(cS.LICENSE_EXPIRED);break;case _v.ERR_LICENSE_MINUTES_EXCEEDED:this.close(cS.LICENSE_MINUTES_EXCEEDED);break;case _v.ERR_LICENSE_PERIOD_INVALID:this.close(cS.LICENSE_PERIOD_INVALID);break;case _v.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(cS.LICENSE_MULTIPLE_SDK_SERVICE);break;case _v.ERR_LICENSE_ILLEGAL:this.close(cS.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new qI("gateway-".concat(this.clientId),this.spec.retryConfig,!0,kC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),kC("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===Ev.CONNECTED&&this.reconnect("retry",lS.OFFLINE)}))}async request(e,t,i,n){const r=xS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new tg(((t,i)=>{if(this.connectionState===Ev.CONNECTED)return t();const n=()=>{this.off(mv.WS_CLOSED,r),t()},r=()=>{this.off(mv.WS_CONNECTED,n),i(new Mv(xg.WS_ABORT))};this.once(mv.WS_CONNECTED,n),this.once(mv.WS_CLOSED,r),e!==fv.PUBLISH&&e!==fv.SUBSCRIBE&&e!==fv.UNSUBSCRIBE&&e!==fv.UNPUBLISH&&e!==fv.CONTROL&&e!==fv.RESTART_ICE||this.once(mv.DISCONNECT_P2P,(()=>{i(new Mv(xg.DISCONNECT_P2P))})),e!==fv.PUBLISH&&e!==fv.RESTART_ICE||this.once(mv.ABORT_P2P_EXECUTION,(()=>{i(new Mv(xg.DISCONNECT_P2P))}))}));if(this.connectionState!==Ev.CONNECTING&&this.connectionState!==Ev.RECONNECTING||e===fv.JOIN||e===fv.REJOIN||await a(),this.websocket.sendMessage(s,!0),n)return;const c=new tg(((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.emit(mv.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new Mv(xg.WS_ABORT,"type: ".concat(e))),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(mv.WS_CLOSED,c),this.once(mv.WS_RECONNECTING,c),US(kC("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==o||s||(WC.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(mv.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===Ev.CLOSED||e===fv.LEAVE)throw new Mv(xg.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===fv.JOIN||e===fv.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),h=kI(l),u=new Mv(xg.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===h.action?d.message:(WC.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(h.desc,", action: ").concat(h.action)),l===_v.ERR_TOO_MANY_BROADCASTERS?e===fv.JOIN||e===fv.REJOIN?(this.initError=u,this.close(),u.throw()):u.throw():"failed"===h.action?u.throw():"quit"===h.action?(this.initError=u,this.close(),u.throw()):(l===_v.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,WC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",lS.MULTI_IP)):this.reconnect(h.action,lS.SERVER_ERROR),e===fv.JOIN||e===fv.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new tg((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=kC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==Ev.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),kC("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new tg(((t,i)=>{this.once(mv.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(mv.WS_CLOSED,(()=>i(this.initError||new Mv(xg.WS_ABORT)))),this.connectionState=Ev.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||cS.LEAVE,this.connectionState=Ev.CLOSED,WC.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===cS.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new qI("gateway-".concat(this.clientId),this.spec.retryConfig,!0,kC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),kC("JOIN_GATEWAY_USE_443PORT_ONLY"),this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(mv.ABORT_P2P_EXECUTION);const e=await fS(this,mv.REQUEST_JOIN_INFO),t=await this.request(fv.JOIN,e);if(!t)return this.emit(mv.REPORT_JOIN_GATEWAY,$v.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(mv.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new Mv(xg.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=TS(this,mv.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(fv.REJOIN,e);return!!t&&(this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(Sv.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(Sv.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(Sv.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(Sv.MUTE_AUDIO,{uid:e.uid}):this.emit(Sv.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(Sv.MUTE_VIDEO,{uid:e.uid}):this.emit(Sv.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(Sv.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(Sv.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(Sv.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(Sv.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(Sv.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleNotification(e){WC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kI(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(cS.UID_BANNED),void this.close()):void this.reconnect(t.action,lS.SERVER_ERROR);WC.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=kC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(WC.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>kC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",lS.TIMEOUT):this.request(fv.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),kC("REPORT_STATS")&&this.send(fv.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(gv.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(Cv.RECONNECT_WAITTING_FINISH,(e=>{this.emit(mv.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(Cv.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(mv.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(Cv.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Cv.CLOSED,(()=>{this.connectionState=Ev.CLOSED})),this.websocket.on(Cv.FAILED,(()=>{this._disconnectedReason=cS.NETWORK_ERROR,this.connectionState=Ev.CLOSED})),this.websocket.on(Cv.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Ev.CONNECTED?this.connectionState=Ev.RECONNECTING:this.connectionState=Ev.CONNECTING})),this.websocket.on(Cv.WILL_RECONNECT,((e,t,i)=>{const n=TS(this,mv.IS_P2P_DISCONNECTED),r=n||"retry"!==e;n&&"retry"===e&&(WC.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=$v.P2P_DISCONNECTED),r&&(WC.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(mv.REPORT_JOIN_GATEWAY,t||$v.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(mv.NEED_RENEW_SESSION),this.emit(mv.DISCONNECT_P2P)),i(e)})),this.websocket.on(Cv.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{WC.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",lS.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(mv.REPORT_JOIN_GATEWAY,e.message||e.code||$v.UNKNOWN_REASON,this.url||""),e instanceof Mv&&e.code===xg.UNEXPECTED_RESPONSE&&e.data.code===_v.ERR_NO_AUTHORIZED)return WC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",lS.SERVER_ERROR);WC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",lS.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(Cv.REQUEST_NEW_URLS,((e,t)=>{fS(this,mv.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(Cv.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(Sv.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}var XI="\t\n\v\f\r                 \u2028\u2029\ufeff",QI=tt,ZI=Sr,$I=XI,ey=Ee("".replace),ty=RegExp("^["+$I+"]+"),iy=RegExp("(^|[^"+$I+"])["+$I+"]+$"),ny=function(e){return function(t){var i=ZI(QI(t));return 1&e&&(i=ey(i,ty,"")),2&e&&(i=ey(i,iy,"$1")),i}},ry={start:ny(1),end:ny(2),trim:ny(3)},sy=zd.PROPER,oy=de,ay=XI,cy=ry.trim;Mn({target:"String",proto:!0,forced:function(e){return oy((function(){return!!ay[e]()||"​…᠎"!=="​…᠎"[e]()||sy&&ay[e].name!==e}))}("trim")},{trim:function(){return cy(this)}});var dy,ly,hy=tr("String").trim,uy=me,py=hy,_y=String.prototype,Ey=z((function(e){var t=e.trim;return"string"==typeof e||e===_y||uy(_y,e)&&t===_y.trim?py:t}));function my(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function fy(e,t,i,n,r){return{width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r}}function gy(e,t,i,n,r){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r}}function Sy(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}!function(e){e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK"}(dy||(dy={})),function(e){e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change"}(ly||(ly={}));const Ty={"90p":fy(160,90),"90p_1":fy(160,90),"120p":fy(160,120,15,30,65),"120p_1":fy(160,120,15,30,65),"120p_3":fy(120,120,15,30,50),"120p_4":fy(212,120),"180p":fy(320,180,15,30,140),"180p_1":fy(320,180,15,30,140),"180p_3":fy(180,180,15,30,100),"180p_4":fy(240,180,15,30,120),"240p":fy(320,240,15,40,200),"240p_1":fy(320,240,15,40,200),"240p_3":fy(240,240,15,40,140),"240p_4":fy(424,240,15,40,220),"360p":fy(640,360,15,80,400),"360p_1":fy(640,360,15,80,400),"360p_3":fy(360,360,15,80,260),"360p_4":fy(640,360,30,80,600),"360p_6":fy(360,360,30,80,400),"360p_7":fy(480,360,15,80,320),"360p_8":fy(480,360,30,80,490),"360p_9":fy(640,360,15,80,800),"360p_10":fy(640,360,24,80,800),"360p_11":fy(640,360,24,80,1e3),"480p":fy(640,480,15,100,500),"480p_1":fy(640,480,15,100,500),"480p_2":fy(640,480,30,100,1e3),"480p_3":fy(480,480,15,100,400),"480p_4":fy(640,480,30,100,750),"480p_6":fy(480,480,30,100,600),"480p_8":fy(848,480,15,100,610),"480p_9":fy(848,480,30,100,930),"480p_10":fy(640,480,10,100,400),"720p":fy(1280,720,15,120,1130),"720p_1":fy(1280,720,15,120,1130),"720p_2":fy(1280,720,30,120,2e3),"720p_3":fy(1280,720,30,120,1710),"720p_5":fy(960,720,15,120,910),"720p_6":fy(960,720,30,120,1380),"1080p":fy(1920,1080,15,120,2080),"1080p_1":fy(1920,1080,15,120,2080),"1080p_2":fy(1920,1080,30,120,3e3),"1080p_3":fy(1920,1080,30,120,3150),"1080p_5":fy(1920,1080,60,120,4780),"1440p":fy(2560,1440,30,120,4850),"1440p_1":fy(2560,1440,30,120,4850),"1440p_2":fy(2560,1440,60,120,7350),"4k":fy(3840,2160,30,120,8910),"4k_1":fy(3840,2160,30,120,8910),"4k_3":fy(3840,2160,60,120,13500)},Ry={"480p":gy(640,480,5),"480p_1":gy(640,480,5),"480p_2":gy(640,480,30),"480p_3":gy(640,480,15),"720p":gy(1280,720,5),"720p_1":gy(1280,720,5),"720p_2":gy(1280,720,30),"720p_3":gy(1280,720,15),"1080p":gy(1920,1080,5),"1080p_1":gy(1920,1080,5),"1080p_2":gy(1920,1080,30),"1080p_3":gy(1920,1080,15)},Cy={"1SL1TL":Sy(1,1),"3SL3TL":Sy(3,3),"2SL3TL":Sy(2,3)};function vy(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},Ty[e]):e}function Iy(e){return"string"==typeof e?Object.assign({},Ry[e]):e}function yy(e){return"string"==typeof e?Object.assign({},Cy[e]):e}const Ay={speech_low_quality:my(16e3,!1),speech_standard:my(32e3,!1,18),music_standard:my(48e3,!1),standard_stereo:my(48e3,!0,56),high_quality:my(48e3,!1,128),high_quality_stereo:my(48e3,!0,192)};function by(e){return"string"==typeof e?Object.assign({},Ay[e]):e}const wy=[];function Oy(e){return Bg(e,"mediaSource",["screen","window","application"]),!0}var Ny,Dy,Py,Ly,ky,My,Uy,xy,Vy,Fy;!function(e){e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track"}(Ny||(Ny={})),function(e){e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream"}(Dy||(Dy={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM"}(Py||(Py={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM"}(Ly||(Ly={})),function(e){e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY"}(ky||(ky={})),function(e){e.TRANSCEIVER_UPDATED="transceiver-updated"}(My||(My={})),function(e){e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed"}(Uy||(Uy={})),function(e){e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status"}(xy||(xy={})),function(e){e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source"}(Vy||(Vy={})),function(e){e.UPDATE_TRACK_SOURCE="update-track-source"}(Fy||(Fy={}));const By={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},jy={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},Gy={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},Wy={uplinkNetworkQuality:0,downlinkNetworkQuality:0},Hy={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};var Ky,Yy,qy,Jy,zy;!function(e){e.ON_TRACK="on_track",e.ON_NODE="on_node"}(Ky||(Ky={})),function(e){e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints"}(Yy||(Yy={})),function(e){e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND"}(qy||(qy={})),function(e){e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged"}(Jy||(Jy={})),function(e){e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata"}(zy||(zy={}));const Xy={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};var Qy;!function(e){e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error"}(Qy||(Qy={}));class Zy extends iS{constructor(e,t){super(),nu(this,"_ID",void 0),nu(this,"_rtpTransceiver",void 0),nu(this,"_lowRtpTransceiver",void 0),nu(this,"_hints",[]),nu(this,"_isClosed",!1),nu(this,"_originMediaStreamTrack",void 0),nu(this,"_mediaStreamTrack",void 0),nu(this,"_external",{}),this._ID=t||xS(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,function(e){Lr(wy).call(wy,e)||wy.push(e)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){if(!e){const e=iv.reportApiInvoke(null,{name:sS.GET_MEDIA_STREAM_TRACK,options:[],tag:oS.TRACER});this._mediaStreamTrack&&"string"==typeof this._mediaStreamTrack.label?e.onSuccess(this._mediaStreamTrack.label):e.onSuccess("")}return this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===Py.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){const t=wy.indexOf(e);-1!==t&&wy.splice(t,1)}(this),this.emit(Uy.CLOSED)}_updateRtpTransceiver(e,t){if(t===Py.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(My.TRANSCEIVER_UPDATED,e,t)}}class $y extends Zy{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}constructor(e,t){super(e,t),nu(this,"_enabled",!0),nu(this,"_muted",!1),nu(this,"_isExternalTrack",!1),nu(this,"_isClosed",!1),nu(this,"_enabledMutex",void 0),nu(this,"processor",void 0),nu(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new YS("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,WC.debug("[".concat(this.getTrackId(),"] close")),this.emit(Ny.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gS(this,Ny.NEED_REPLACE_TRACK,this),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){WC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Uy.TRACK_ENDED)}stateCheck(e,t){if(WC.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),Fg(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new Vg(xg.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",WC);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new Vg(xg.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",WC)}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}function eA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const tA=window.AudioContext||window.webkitAudioContext;let iA=null;const nA=new class extends iS{constructor(){super(...arguments),nu(this,"prevState",void 0),nu(this,"curState",void 0),nu(this,"currentTime",void 0),nu(this,"currentTimeStuckAt",void 0),nu(this,"interruptDetectorTrack",void 0),nu(this,"onLocalAudioTrackMute",(()=>{WC.info("ios15-interruption-start"),this.emit(ly.IOS_15_16_INTERRUPTION_START)})),nu(this,"onLocalAudioTrackUnmute",(async()=>{WC.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?WC.info("ios15-interruption-end-canceled"):(iA&&await iA.suspend(),this.emit(ly.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){WC.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){WC.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function rA(){if(!tA)return void WC.error("your browser is not support web audio");WC.info("create audio context");const e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?eA(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):eA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},kC("WEBAUDIO_INIT_OPTIONS"));WC.debug("audio context init option:",JSON.stringify(e)),iA=new tA(e),nA.curState=iA.state,iA.onstatechange=()=>{nA.prevState=nA.curState,nA.curState=iA?iA.state:void 0;const{prevState:e,curState:t}=nA,i="running"===t,n="interrupted"===t,r="running"===e,s="suspended"===e,o="interrupted"===e,a=pg().osVersion;(Cg()||Dg())&&r&&n&&(WC.info("ios".concat(a,"-interruption-start")),nA.emit(ly.IOS_INTERRUPTION_START)),(Cg()||Dg())&&(s||o)&&i&&(WC.info("ios".concat(a,"-interruption-end")),nA.emit(ly.IOS_INTERRUPTION_END)),e!==t&&(WC.debug("AudioContext State Change","".concat(e,"=>").concat(t)),nA.emit(ly.STATE_CHANGE))},setInterval((()=>{var e;const t=null===(e=iA)||void 0===e?void 0:e.currentTime;nA.currentTime!==t?(nA.currentTimeStuckAt&&(WC.debug("AudioContext current time resume at ".concat(t)),nA.currentTimeStuckAt=void 0),nA.currentTime=t):(t!==nA.currentTimeStuckAt&&(iv.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:oS.TRACER}).onSuccess(),WC.warning("AudioContext current time stuck at ".concat(t))),nA.currentTimeStuckAt=t)}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,n=!1,r=!1,s=!1;function o(t){"running"===e.state?a(!1):Cg()||Dg()?"suspended"===e.state&&(a(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(a(!0),t&&e.resume().then(d,d))}function a(e){if(n!==e){n=e;for(let i=0,n=t;i<n.length;i+=1){const t=n[i];e?window.addEventListener(t,l,{capture:!0,passive:!0}):window.removeEventListener(t,l,{capture:!0,passive:!0})}}}function c(){o(!0)}function d(){o(!1)}function l(){o(!0)}function h(e){if(!s)if(i.paused)if(e){let t;u(!1),s=!0;try{t=i.play(),t?t.then(p,p):(i.addEventListener("playing",p),i.addEventListener("abort",p),i.addEventListener("error",p))}catch(e){p()}}else u(!0);else u(!1)}function u(e){if(r!==e){r=e;for(let i=0,n=t;i<n.length;i++){const t=n[i];e?window.addEventListener(t,_,{capture:!0,passive:!0}):window.removeEventListener(t,_,{capture:!0,passive:!0})}}}function p(){i.removeEventListener("playing",p),i.removeEventListener("abort",p),i.removeEventListener("error",p),s=!1,h(!1)}function _(){h(!0)}if(Cg()){const t=e.createMediaStreamDestination(),n=document.createElement("div");n.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=n.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,h(!0)}nA.on(ly.STATE_CHANGE,c),o(!1)}(iA)}function sA(){if(!iA){if(rA(),!iA)throw new Vg(xg.NOT_SUPPORTED,"can not create audio context");return iA}return iA}function oA(){return!!iA}function aA(e){if(function(){if(null!==cA)return cA;const e=sA(),t=e.createBufferSource(),i=e.createGain(),n=e.createGain();t.connect(i),t.connect(n),t.disconnect(i);let r=!1;try{t.disconnect(i)}catch(e){r=!0}return t.disconnect(),cA=r,r}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>{var s;return e._inputNodes||(e._inputNodes=[]),Lr(s=e._inputNodes).call(s,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,n,r)):t.call(e,i,n)),e},e.disconnect=(n,r,s)=>{i.call(e),n?IS(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}let cA=null;function dA(e,t){let i=!1;const n=1/t;if(kC("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{i?window.clearInterval(t):e(performance.now()/1e3)}),1e3*n)}else{const t=sA();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const s=()=>{if(i)return void(r=null);const o=t.createOscillator();o.onended=s,o.connect(r),o.start(0),o.stop(t.currentTime+n),e(t.currentTime)};s()}return()=>{i=!0}}const lA={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1};function hA(){return lA}class uA{constructor(){nu(this,"context",void 0),nu(this,"analyserNode",void 0),nu(this,"sourceNode",void 0),this.context=sA(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||Cg()||Dg()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;i<e.length;++i)e[i]=t[i]/128-1}const t=cT(e).call(e,((e,t)=>e+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){WC.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class pA extends iS{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),nu(this,"outputNode",void 0),nu(this,"outputTrack",void 0),nu(this,"isPlayed",!1),nu(this,"context",void 0),nu(this,"audioBufferNode",void 0),nu(this,"destNode",void 0),nu(this,"audioOutputLevel",0),nu(this,"volumeLevelAnalyser",void 0),nu(this,"_processedNode",void 0),nu(this,"playNode",void 0),nu(this,"isDestroyed",!1),nu(this,"onNoAudioInput",void 0),nu(this,"isNoAudioInput",!1),nu(this,"_noAudioInputCount",0),this.context=sA(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),aA(this.outputNode),this.volumeLevelAnalyser=new uA}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit(Vy.ON_AUDIO_BUFFER,function(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const i=e.outputBuffer.getChannelData(t);for(let e=0;e<i.length;e+=1)i[e]=0}return e.inputBuffer}(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!hA().webAudioMediaStreamDest)throw new Vg(xg.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(e){"running"!==this.context.state&&AS((()=>{nA.emit("autoplay-failed")})),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(e){}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;Cg()||Dg()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let n=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(n=!0);return n?(this.isNoAudioInput=!1,!0):(await US(200),await this.checkHasAudioInput(e?e+1:1)&&n)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode),this.volumeLevelAnalyser.updateSource(this.outputNode)}}class _A extends pA{get isFreeze(){return!1}constructor(e,t,i){var n;if(super(),nu(this,"sourceNode",void 0),nu(this,"track",void 0),nu(this,"clonedTrack",void 0),nu(this,"audioElement",void 0),nu(this,"isCurrentTrackCloned",!1),nu(this,"isRemoteTrack",!1),nu(this,"originVolumeLevelAnalyser",void 0),nu(this,"rebuildWebAudio",(async()=>{if(WC.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void WC.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>WC.info("resume success"))),WC.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),aA(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),aA(this.outputNode),this.emit(Vy.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==e.kind)throw new Vg(xg.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),aA(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,WC.debug("create an unmuted track ".concat(e.id," from the original track ").concat(i.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));aA(t),this.originVolumeLevelAnalyser=new uA,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const s=pg();t&&s.os===ag.IOS&&Number(null===(n=s.osVersion)||void 0===n?void 0:n.split(".")[0])<15&&(nA.on(ly.STATE_CHANGE,(()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio()})),this.checkHasAudioInput().then((e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0)})))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),aA(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(Vy.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),nA.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),WC.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const i=this.context.createMediaStreamSource(new MediaStream([t]));aA(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function EA(e,t,i){const n=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:n(t.height,1080),maxWidth:n(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r)}async function mA(e,t){const i=await fA(e.mediaSource),{sourceId:n,audio:r}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new tg(((i,n)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const s=document.createElement("div");s.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const o=document.createElement("div");o.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",o.setAttribute("style","height: 12%;");const a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(u);const e=new Error("NotAllowedError");e.name="NotAllowedError",n(e)};let l=t;const h=document.createElement("div");if(t){const e=document.createElement("input");e.setAttribute("type","checkbox");const t=document.createElement("span");e.setAttribute("style","margin-right: 6px;"),t.innerText="Share audio",e.checked=l,e.onchange=()=>{l=e.checked},h.appendChild(e),h.appendChild(t)}c.appendChild(h),c.appendChild(d),s.appendChild(o),s.appendChild(a),s.appendChild(c);const u=document.createElement("div");u.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),u.appendChild(r),u.appendChild(s),document.body.appendChild(u),e.map((e=>{if(e.id){const t=document.createElement("div");t.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let n=e.thumbnail;try{const{width:e}=n.getSize();e>1920&&(n=n.resize({width:1920}))}catch(e){throw e&&e.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),e}t.innerHTML='<div style="height: 120px; display: table-cell; vertical-align: middle;"><img style="width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);" src='+n.toDataURL()+' /></div><span style="\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+e.name.replace(/[\u00A0-\u9999<>\&]/g,(function(e){return"&#"+e.charCodeAt(0)+";"}))+"</span>",t.onclick=()=>{document.body.removeChild(u),i({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(i,t);return await EA(n,e,r)}async function fA(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=rS();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new Vg(xg.ELECTRON_IS_NULL);let n=null;try{var r;n=(null===(r=i.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){n=null}n&&n.then||(n=new tg(((e,n)=>{i.desktopCapturer.getSources({types:t},((t,i)=>{t?n(t):e(i)}))})));try{return await n}catch(e){throw new Vg(xg.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}function gA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const SA=new YS("safari");let TA=!1,RA=!1;async function CA(e,t){let i=0,n=null;for(;i<2;)try{n=await vA(e,t,i>0);break}catch(e){if(e instanceof Vg)throw WC.error("[".concat(t,"] ").concat(e.toString())),e;const n=IA(e.name||e.code||e,e.message);if(n.code===xg.MEDIA_OPTION_INVALID){WC.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await US(500);continue}throw WC.error("[".concat(t,"] ").concat(n.toString())),n}if(!n)throw new Vg(xg.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n}async function vA(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Vg(xg.NOT_SUPPORTED,"can not find getUserMedia");i&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const n=hA(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return WC.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(rS())e.screen.sourceId?yA(r,await EA(e.screen.sourceId,e.screen,e.screenAudio)):yA(r,await mA(e.screen,e.screenAudio));else if(Sg()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new Vg(xg.NOT_SUPPORTED,"This browser does not support screen sharing");WC.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const i=await(o=e.screen.extensionId,a=t,new tg(((e,t)=>{try{chrome.runtime.sendMessage(o,{getStream:!0},(i=>{if(!i||!i.streamId)return WC.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new Vg(xg.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)}))}catch(e){WC.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(o,")"),e.toString()),t(new Vg(xg.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=i,yA(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(n.getDisplayMedia){var s;e.screen.mediaSource&&Oy(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(s=e.screen.displaySurface)&&void 0!==s?s:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},{selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a}=e.screen,c={selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a};!n&&delete c.selfBrowserSurface,!o&&delete c.surfaceSwitching,!a&&delete c.systemAudio,WC.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:!!e.screenAudio,controls:c}));const d=await navigator.mediaDevices.getDisplayMedia(function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?gA(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):gA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({video:i,audio:!!e.screenAudio},c));yA(r,d)}else{if(!Rg())throw WC.error("[".concat(t,"] This browser does not support screenSharing")),new Vg(xg.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&Oy(e.screen.mediaSource);const i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};WC.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i))),yA(r,await navigator.mediaDevices.getUserMedia(i))}}var o,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=kC("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=WS(c,d)}catch(e){}WC.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),pg();let l,h=null;(Tg()||Cg()||mg())&&(h=await SA.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw h&&h(),e}return c.audio&&(TA=!0),c.video&&(RA=!0),yA(r,l),h&&h(),r}function IA(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new Vg(xg.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new Vg(xg.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new Vg(xg.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new Vg(xg.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new Vg(xg.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new Vg(xg.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return WC.error("getUserMedia unexpected error",e),new Vg(xg.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function yA(e,t){const i=e.getVideoTracks()[0],n=e.getAudioTracks()[0],r=t.getVideoTracks()[0],s=t.getAudioTracks()[0];s&&(n&&e.removeTrack(n),e.addTrack(s)),r&&(i&&e.removeTrack(i),e.addTrack(r))}const AA=new class extends iS{get state(){return this._state}set state(e){e!==this._state&&(this.emit(Jy.STATE_CHANGE,e),this._state=e)}constructor(){super(),nu(this,"_state",qy.IDLE),nu(this,"isAccessMicrophonePermission",!1),nu(this,"isAccessCameraPermission",!1),nu(this,"lastAccessMicrophonePermission",!1),nu(this,"lastAccessCameraPermission",!1),nu(this,"checkdeviceMatched",!1),nu(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(kC("ENUMERATE_DEVICES_INTERVAL")||(Mg()||_g()===ag.HARMONY_OS)&&kg())&&this.updateDevicesInfo()}),kC("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>WC.error(e.toString())))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return new Vg(xg.NOT_SUPPORTED,"enumerateDevices() not supported.").throw();const n=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(n);let s=!this.isAccessMicrophonePermission&&e,o=!this.isAccessCameraPermission&&t;r.audio&&(s=!1),r.video&&(o=!1);let a=null,c=null,d=null;if(!i&&(s||o)){if(SA.isLocked&&(WC.debug("[device manager] wait GUM lock"),(await SA.lock())(),WC.debug("[device manager] GUM unlock")),TA&&(s=!1,this.isAccessMicrophonePermission=!0),RA&&(o=!1,this.isAccessCameraPermission=!0),WC.debug("[device manager] check media device permissions",e,t,s,o),s&&o){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=IA(e.name||e.code||e,e.message);if(t.code===xg.PERMISSION_DENIED)throw t;WC.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(s){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=IA(e.name||e.code||e,e.message);if(t.code===xg.PERMISSION_DENIED)throw t;WC.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(o){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=IA(e.name||e.code||e,e.message);if(t.code===xg.PERMISSION_DENIED)throw t;WC.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}WC.debug("[device manager] mic permission",e,"cam permission",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,e}catch(e){return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,new Vg(xg.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audioinput"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>"videoinput"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audiooutput"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((i=>{i.device.label===e&&(t=i.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new Vg(xg.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=qy.INITING;try{await this.updateDevicesInfo(),this.state=qy.INITEND}catch(e){throw WC.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=qy.IDLE,("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname)||new Vg(xg.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw(),e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),i=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&i?i.groupId===t.groupId?WC.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):WC.warning("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):WC.debug("[device-check] default input or output not found")}const n=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const n=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(n?n.state:"INACTIVE")){const n={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),n),i.push(n)}n&&(n.updateAt=t)})),this.deviceInfoMap.forEach(((e,n)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))})),this.state!==qy.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(Jy.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(Jy.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(Jy.PLAYOUT_DEVICE_CHANGED,e)}})),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),i=e.filter((e=>"videoinput"===e.kind)),n={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){n.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){n.video=!0;break}return n}};let bA=!1;const wA=new class extends iS{constructor(){super(...arguments),nu(this,"onAutoplayFailed",void 0),nu(this,"onAudioAutoplayFailed",void 0)}};function OA(){if(pg(),!bA){const e=t=>{t.preventDefault(),bA=!1,Ug()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};bA=!0,Ug()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),WC.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),wA.onAutoplayFailed?wA.onAutoplayFailed():wA.onAudioAutoplayFailed?WC.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):WC.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),wA.emit("autoplay-failed")}}function NA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function DA(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?NA(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):NA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function PA(e,t,i,n){if(!e)return;const r=iv.getBaseInfoBySessionId(e);if(!r)return;const s=r.info,o=Date.now(),a=DA(DA({},s),{},{vid:void 0===s.vid?0:Number(s.vid),lts:o,elapse:o-r.startTime,cbRegistered:wA.onAutoplayFailed||wA.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:n,extend:void 0});iv.send({type:zC.AUTOPLAY_FAILED,data:a},!0)}const LA=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],kA=new class{constructor(){nu(this,"onAutoplayFailed",void 0),nu(this,"elementMap",new Map),nu(this,"elementStateMap",new Map),nu(this,"elementsNeedToResume",[]),nu(this,"sinkIdMap",new Map),nu(this,"autoResumeAfterInterruption",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const n=this.elementStateMap.get(t),r=i.srcObject.getAudioTracks()[0];wg()?r&&"live"===r.readyState&&"running"===nA.curState&&(WC.debug("auto resume after interruption for iOS 15"),i.pause(),i.play()):n&&"paused"===n&&r&&"live"===r.readyState&&"running"===nA.curState&&(WC.debug("auto resume after interruption for iOS"),i.play())}))})),nu(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&"live"===n.readyState&&(WC.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())}))})),this.autoResumeAudioElement(),nA.on(ly.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),nA.on(ly.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),nA.on(ly.STATE_CHANGE,(()=>{Cg()&&"suspended"===nA.prevState&&"running"===nA.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new Vg(xg.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,n){if(this.elementMap.has(t))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,zy.INIT),this.setVolume(t,i);const s=this.sinkIdMap.get(t);if(s)try{r.setSinkId(s).catch((e=>{WC.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){WC.warning("[".concat(t,"] set sink id failed"),e.toString())}const o=r.play();o&&o.then&&o.catch((e=>{n&&PA(n,"audio",e.message,t),WC.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(WC.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),AS((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),OA()})))}))}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){LA.forEach((i=>{t.addEventListener(i,(i=>{const n=this.elementStateMap.get(e),r="pause"===i.type?"paused":i.type;if(WC.debug("[".concat(e,"] audio-element-status change ").concat(n," => ").concat(r)),"error"===i.type){const i=null==t?void 0:t.error;i&&WC.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message))}this.elementStateMap.set(e,r)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{WC.debug("Auto resume audio element success")})).catch((e=>{WC.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};new tg((e=>{document.body?e():window.addEventListener("load",(()=>e()))})).then((()=>{Ug()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function MA(){return function(e,t,i){const n=i.value;return"function"==typeof n&&(i.value=function(){this._isClosed&&new Vg(xg.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",WC);for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const r=n.apply(this,t);return r instanceof tg?new tg(((e,t)=>{r.then(e).catch(t)})):r}),i}}function UA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function xA(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?UA(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):UA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class VA extends iS{constructor(e){super(),nu(this,"name","VideoProcessorDestination"),nu(this,"ID","0"),nu(this,"_source",void 0),nu(this,"videoContext",void 0),nu(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new Vg(xg.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new Vg(xg.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(Ky.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(Ky.ON_TRACK,void 0)}}class FA extends iS{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),nu(this,"constraintsMap",new Map),nu(this,"statsRegistry",[]),nu(this,"usageRegistry",[]),nu(this,"trackId",void 0),nu(this,"direction",void 0),nu(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await fS(this,Yy.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return WC.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),gS(this,Yy.REQUEST_UPDATE_CONSTRAINTS,Array.from(Pv(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return WC.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),gS(this,Yy.REQUEST_UPDATE_CONSTRAINTS,Array.from(Pv(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const s=r();e.push({processorID:t,processorName:i,type:n,stats:s})}catch(e){WC.error(new Vg(xg.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof tg&&(i=await i),e.push(xA(xA({},i),{},{direction:this.direction}))}catch(e){WC.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class BA extends iS{constructor(e){super(),nu(this,"name","AudioProcessorDestination"),nu(this,"ID","0"),nu(this,"inputTrack",void 0),nu(this,"inputNode",void 0),nu(this,"audioProcessorContext",void 0),nu(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new Vg(xg.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new Vg(xg.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(Ky.ON_TRACK,void 0),this.emit(Ky.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(Ky.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(Ky.ON_NODE,this.inputNode))}}class jA extends iS{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),nu(this,"constraintsMap",new Map),nu(this,"statsRegistry",[]),nu(this,"audioContext",void 0),nu(this,"trackId",void 0),nu(this,"direction",void 0),nu(this,"usageRegistry",[]),nu(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return fS(this,Yy.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return WC.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),gS(this,Yy.REQUEST_UPDATE_CONSTRAINTS,Array.from(Pv(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),gS(this,Yy.REQUEST_UPDATE_CONSTRAINTS,Array.from(Pv(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){const i=this.statsRegistry.findIndex((i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t));-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const s=r();e.push({processorID:t,processorName:i,type:n,stats:s})}catch(e){WC.error(new Vg(xg.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof tg&&(i=await i),e.push(xA(xA({},i),{},{direction:this.direction}))}catch(e){WC.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class GA extends iS{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),nu(this,"context",void 0),nu(this,"processSourceNode",void 0),nu(this,"outputTrack",void 0),nu(this,"processedNode",void 0),nu(this,"clonedTrack",void 0),nu(this,"outputNode",void 0),this.outputNode=new WA}setVolume(){}createOutputTrack(){throw new Vg(xg.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class WA{disconnect(){}connect(){}}let HA=null;class KA{constructor(){nu(this,"state","open"),nu(this,"trigger",void 0),nu(this,"tasks",[]),WC.debug("[macro-task-queue] is created."),this.trigger=window.setTimeout((()=>{this.state="closed",WC.debug("[macro-task-queue] will be closed, all remaining tasks will execute. [".concat(this.tasks.map((e=>e.key)),"]")),this.trigger=void 0,this.tasks.forEach((e=>{let{func:t}=e;return t()})),this.tasks.length=0,WC.debug("[macro-task-queue] is closed.")}))}enqueue(e,t){"closed"!==this.state&&(this.tasks.push({key:e,func:t}),WC.debug("[macro-task-queue] is queued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")))}runTask(e){if("closed"===this.state)return;const t=this.tasks.findIndex((t=>t.key===e));if(-1!==t){const i=this.tasks.splice(t,1);WC.debug("[macro-task-queue] is unqueued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")),i[0].func()}}release(){this.trigger&&(this.state="closed",clearTimeout(this.trigger),this.trigger=void 0,this.tasks.length=0,WC.debug("[macro-task-queue] is closed."))}}function YA(e){return function(t,i,n){var r;const s=null!==(r=n.value)&&void 0!==r?r:n.get,o=function(){HA&&"open"===HA.state&&HA.runTask(e);for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return null==s?void 0:s.apply(this,...i)};return n.value?n.value=o:n.get=o,n}}function qA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function JA(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?qA(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):qA(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class zA extends $y{get _source(){return this._trackSource}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get processorDestination(){return this._processorDestination}set processorDestination(e){this._processorDestination=e}get isPlaying(){return this._useAudioElement?kA.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,n,r){super(e,i),nu(this,"trackMediaType","audio"),nu(this,"_encoderConfig",void 0),nu(this,"_trackSource",void 0),nu(this,"_enabled",!0),nu(this,"_volume",100),nu(this,"_useAudioElement",!1),nu(this,"_bypassWebAudio",!1),nu(this,"processor",void 0),nu(this,"_processorContext",void 0),nu(this,"_processorDestination",void 0),nu(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!n;const s=()=>{this.processorContext=new jA(this._source.context,this.getTrackId(),"local"),this.processorDestination=new BA(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Vy.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))},o=r&&Tg()&&!oA();kC("DISABLE_WEBAUDIO")?(this._source=new GA,this._useAudioElement=!0,this._bypassWebAudio=!0):o?this._source=new GA:(this._source=new _A(e,!1,this._getOriginVolumeLevel?e:void 0),kC("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0)),s(),!kC("DISABLE_WEBAUDIO")&&o&&(HA||(HA=new KA),HA).enqueue("INIT_WEBAUDIO",(()=>{this._source=new _A(e,!1,this._getOriginVolumeLevel?e:void 0),kC("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0),s(),this.emit(Fy.UPDATE_TRACK_SOURCE)}))}setVolume(e){jg(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&kA.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void WC.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,gS(this,Ny.NEED_REPLACE_TRACK,this).then((()=>{WC.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{WC.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e)})))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement)throw new Vg(xg.NOT_SUPPORTED,"your browser does not support setting the audio output device");await kA.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,i){return this._setEnabled(e,t,i)}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(WC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await gS(this,Ny.NEED_ENABLE_TRACK,this),WC.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),WC.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await gS(this,Ny.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),WC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,WC.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await gS(this,Ny.NEED_MUTE_TRACK,this):await gS(this,Ny.NEED_UNMUTE_TRACK,this))}getStats(){return NS((()=>{WC.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning"),SS(this,Ny.GET_STATS)||JA({},By)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Vy.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Vy.ON_AUDIO_BUFFER),this._source.on(Vy.ON_AUDIO_BUFFER,(t=>e(t)))}play(){WC.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(WC.debug("[".concat(this.getTrackId(),"] start audio playback in element")),kA.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){WC.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?kA.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];WC.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&kA.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this.processor.updateInput({track:e,context:this.processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gS(this,Ny.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return tg.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new Vg(xg.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new Vg(xg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Ky.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await gS(this,Ny.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gS(this,Ny.NEED_REPLACE_TRACK,this))})),this.processorDestination.on(Ky.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Ky.ON_TRACK),this.processorDestination.removeAllListeners(Ky.ON_NODE)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(Yy.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(Yy.REQUEST_CONSTRAINTS)}}Lv([YA("INIT_WEBAUDIO"),kv("design:type",Object),kv("design:paramtypes",[Object])],zA.prototype,"_source",null),Lv([YA("INIT_WEBAUDIO"),kv("design:type",jA),kv("design:paramtypes",[jA])],zA.prototype,"processorContext",null),Lv([YA("INIT_WEBAUDIO"),kv("design:type",BA),kv("design:paramtypes",[BA])],zA.prototype,"processorDestination",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",void 0)],zA.prototype,"setVolume",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],zA.prototype,"setPlaybackDevice",null),Lv([qS("LocalAudioTrack","_enabledMutex"),tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Object,Boolean]),kv("design:returntype",tg)],zA.prototype,"setEnabled",null),Lv([qS("LocalAudioTrack","_enabledMutex"),tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean]),kv("design:returntype",tg)],zA.prototype,"setMuted",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",Object)],zA.prototype,"getStats",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[Object,Number]),kv("design:returntype",void 0)],zA.prototype,"setAudioFrameCallback",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],zA.prototype,"play",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],zA.prototype,"stop",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],zA.prototype,"close",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t.name]}),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",Object)],zA.prototype,"pipe",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],zA.prototype,"unpipe",null);class XA extends zA{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,n){super(e,t.encoderConfig?by(t.encoderConfig):{},n,kC("GET_VOLUME_OF_MUTED_AUDIO_TRACK"),!0),nu(this,"_config",void 0),nu(this,"_deviceName","default"),nu(this,"_constraints",void 0),nu(this,"_originalConstraints",void 0),nu(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(wg()||Og())&&nA.bindInterruptDetectorTrack(this),this.on(Fy.UPDATE_TRACK_SOURCE,(()=>{this.bindProcessorContextEvents()})),oA()&&this.bindProcessorContextEvents()}async setDevice(e){if(WC.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await AA.getDeviceById(e),i={};i.audio=JA({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await CA(i,this.getTrackId())}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await CA({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await AA.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return WC.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(WC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){var n;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(n=this._source.clonedTrack)||void 0===n||n.stop(),i||(this._enabled=!1);try{await gS(this,Ny.NEED_DISABLE_TRACK,this)}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=JA({},this._constraints),s=AA.searchDeviceIdByName(this._deviceName);s&&!r.deviceId&&(r.deviceId=s);try{i||(this._enabled=!0);const e=await CA({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await gS(this,Ny.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),WC.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(wg()||Og())&&nA.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((Cg()||Dg())&&this._enabled&&!this._isClosed&&nA.duringInterruption){const e=async()=>{nA.off(ly.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(WC.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};nA.on(ly.IOS_INTERRUPTION_END,e)}else WC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Uy.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=AA.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await CA({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(){this.processorContext.on(Yy.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(Yy.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}}Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],XA.prototype,"setDevice",null),Lv([qS("MicrophoneAudioTrack","_enabledMutex"),tv({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Boolean,Boolean]),kv("design:returntype",tg)],XA.prototype,"setEnabled",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],XA.prototype,"close",null);class QA extends zA{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),nu(this,"source",void 0),nu(this,"_bufferSource",void 0),this.source=e,this._bufferSource=t,this._bufferSource.on(Vy.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(Uy.SOURCE_STATE_CHANGE,e)}));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){jg(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",void 0)],QA.prototype,"startProcessAudioBuffer",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],QA.prototype,"pauseProcessAudioBuffer",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",void 0)],QA.prototype,"seekAudioBuffer",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],QA.prototype,"resumeProcessAudioBuffer",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],QA.prototype,"stopProcessAudioBuffer",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],QA.prototype,"close",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",void 0)],QA.prototype,"setAudioBufferPlaybackSpeed",null);class ZA extends zA{get __className__(){return"MixingAudioTrack"}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){const e=sA().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,xS(8,"track-mix-")),nu(this,"trackList",void 0),nu(this,"destNode",void 0);try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return-1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(WC.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):WC.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){WC.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}IS(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach((t=>{t instanceof ZA?t.emit(My.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)})))}}function $A(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=vy(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!Lg()&&i.frameRate&&(t.frameRate=i.frameRate),pg().name===cg.EDGE&&"object"==typeof t.frameRate&&(t.frameRate.max=60),Rg()&&(t.frameRate={ideal:30,max:30}),t}function eb(e){const t={};if(Lg()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,Sg()&&e.ANS&&(t.googHighpassFilter=e.ANS))),e.encoderConfig){const i=by(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),Mg()&&(t.sampleRate=void 0),t}class tb extends pA{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(Vy.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),nu(this,"audioBuffer",void 0),nu(this,"sourceNode",void 0),nu(this,"startPlayTime",0),nu(this,"startPlayOffset",0),nu(this,"pausePlayTime",0),nu(this,"options",void 0),nu(this,"currentLoopCount",0),nu(this,"currentPlaybackSpeed",100),nu(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):WC.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(e){}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}}const ib=new Map;async function nb(e,t){let i=null;if("string"==typeof e){const t=ib.get(e);if(t)return WC.debug("use cached audio resource: ",e),t;try{i=(await XS((()=>EC.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new Vg(xg.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new tg(((t,i)=>{const n=new FileReader;n.onload=e=>{e.target?t(e.target.result):i(new Vg(xg.READ_LOCAL_AUDIO_FILE_ERROR))},n.onerror=()=>{i(new Vg(xg.READ_LOCAL_AUDIO_FILE_ERROR))},n.readAsArrayBuffer(e)}));i=await t}const n=await function(e){const t=sA();return new tg(((i,n)=>{t.decodeAudioData(e,(e=>{i(e)}),(e=>{n(new Vg(xg.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}(i);return"string"==typeof e&&t&&ib.set(e,n),n}const rb=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new tg(((i,n)=>{t.toBlob((async e=>{if(t.remove(),e){const n=await sb(e);i({buffer:n,width:t.width,height:t.height})}else n(new Vg(xg.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},sb=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)},ob=new class extends iS{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),nu(this,"_lastHiddenTime",0),nu(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),WC.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}};function ab(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function cb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ab(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ab(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class db{get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(WC.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}constructor(e){nu(this,"trackId",void 0),nu(this,"config",void 0),nu(this,"onFirstVideoFrameDecoded",void 0),nu(this,"freezeTimeCounterList",[]),nu(this,"renderFreezeAccTime",0),nu(this,"isKeepLastFrame",!1),nu(this,"timeUpdatedCount",0),nu(this,"freezeTime",0),nu(this,"playbackTime",0),nu(this,"lastTimeUpdatedTime",0),nu(this,"autoplayFailed",!1),nu(this,"videoTrack",void 0),nu(this,"videoElement",void 0),nu(this,"cacheVideoElement",void 0),nu(this,"videoElementCheckInterval",void 0),nu(this,"_videoElementStatus",zy.NONE),nu(this,"isGettingVideoDimensions",!1),nu(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return WC.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),nu(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===nA.curState&&(WC.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Eg())),Ng()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),nu(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=zy.PLAYING;break;case"loadeddata":if(this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=zy.CANPLAY;break;case"stalled":this.videoElementStatus=zy.STALLED;break;case"suspend":this.videoElementStatus=zy.SUSPEND;break;case"pause":this.videoElementStatus=zy.PAUSED,Cg()||Dg()||Tg()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(WC.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=zy.WAITING;break;case"abort":this.videoElementStatus=zy.ABORT;break;case"ended":this.videoElementStatus=zy.ENDED;break;case"emptied":this.videoElementStatus=zy.EMPTIED;break;case"error":{this.videoElementStatus=zy.ERROR;const e=this.videoElement.error;e&&WC.error("[".concat(this.trackId,"] media error, code: ").concat(e.code,", message: ").concat(e.message));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,ob.lastVisibleTime<ob.lastHiddenTime||i<ob.lastHiddenTime||i<ob.lastVisibleTime)return;for(t>kC("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}})),nu(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(WC.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Eg())),Ng()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),nA.on(ly.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),nA.on(ly.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch((t=>{e&&PA(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(WC.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):WC.warning("[".concat(this.trackId,"] play warning: "),t)}));const i=pg();if(("Safari"===i.name&&15===Number(i.version)||wg())&&t&&t.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};t.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return WC.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const n=i.getContext("2d");return n?(n.drawImage(this.videoElement,0,0,i.width,i.height),new tg(((n,r)=>{i.toBlob((async e=>{if(i.remove(),e){const t=await sb(e);n({buffer:t,width:i.width,height:i.height})}else r(new Vg(xg.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await rb(e)}destroy(){nA.off(ly.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),nA.off(ly.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[]}initVideoElement(){if(this.videoElementStatus=zy.INIT,!this.videoElementCheckInterval&&(lb.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{(function(e){return e!==document.body&&document.body.contains(e)})(this.videoElement)||(this.videoElementStatus=zy.DESTROYED)}),1e3),kC("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i;const n=(e,t)=>{if(this.videoElementStatus===zy.PLAYING){if(i){const e=t.presentationTime-i.presentationTime;e>kC("VIDEO_FREEZE_DURATION")&&ob.lastVisibleTime>=ob.lastHiddenTime&&i.timestamp>ob.lastVisibleTime&&i.timestamp>ob.lastHiddenTime&&(this.renderFreezeAccTime+=e)}i=cb(cb({},t),{},{timestamp:e})}var r,s;kC("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(r=(s=this.videoElement).requestVideoFrameCallback)||void 0===r||r.call(s,n))};null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e||e.call(t,n)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),Mg()&&(this.videoElement.poster="noposter");const i=pg();"Safari"===i.name&&15===Number(i.version)||wg()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream?this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Rg()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Rg()&&this.videoElement.load());const n=this.videoElement.play();void 0!==n&&n.catch((e=>{WC.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){lb.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=zy.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{WC.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{WC.error(e)})),this.autoplayFailed=!1,Ug()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};Ug()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),OA()}}const lb=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class hb extends db{constructor(e){super(e),nu(this,"container",void 0),nu(this,"slot",void 0),this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await rb(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",kC("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}function ub(e){return new tg(((t,i)=>{let n=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const s=Cg()?"canplay":"playing";r.addEventListener(s,(()=>{const e=r.videoWidth,i=r.videoHeight;!e&&Rg()||(n=!0,r.srcObject=null,r.remove(),t([e,i]))})),r.srcObject=new MediaStream([e]),r.play().catch(FS),setTimeout((()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}const pb=async(e,t,i)=>{const n=function(e){const t=[];for(let i=0;i<e.length;i+=2)t.push(parseInt(e.slice(i,i+2),16));return Uint8Array.from(t)}(function(e){const t="0123456789abcdef";function i(e){let i,n="";for(i=0;i<=3;i++)n+=t.charAt(e>>8*i+4&15)+t.charAt(e>>8*i&15);return n}function n(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function r(e,t,i,r,s,o){return n(function(e,t){return e<<t|e>>>32-t}(n(n(t,e),n(r,o)),s),i)}function s(e,t,i,n,s,o,a){return r(t&i|~t&n,e,t,s,o,a)}function o(e,t,i,n,s,o,a){return r(t&n|i&~n,e,t,s,o,a)}function a(e,t,i,n,s,o,a){return r(t^i^n,e,t,s,o,a)}function c(e,t,i,n,s,o,a){return r(i^(t|~n),e,t,s,o,a)}const d=function(e){let t;const i=1+(e.length+8>>6),n=new Array(16*i);for(t=0;t<16*i;t++)n[t]=0;for(t=0;t<e.length;t++)n[t>>2]|=e.charCodeAt(t)<<t%4*8;return n[t>>2]|=128<<t%4*8,n[16*i-2]=8*e.length,n}(e);let l,h,u,p,_,E=1732584193,m=-271733879,f=-1732584194,g=271733878;for(l=0;l<d.length;l+=16)h=E,u=m,p=f,_=g,E=s(E,m,f,g,d[l+0],7,-680876936),g=s(g,E,m,f,d[l+1],12,-389564586),f=s(f,g,E,m,d[l+2],17,606105819),m=s(m,f,g,E,d[l+3],22,-1044525330),E=s(E,m,f,g,d[l+4],7,-176418897),g=s(g,E,m,f,d[l+5],12,1200080426),f=s(f,g,E,m,d[l+6],17,-1473231341),m=s(m,f,g,E,d[l+7],22,-45705983),E=s(E,m,f,g,d[l+8],7,1770035416),g=s(g,E,m,f,d[l+9],12,-1958414417),f=s(f,g,E,m,d[l+10],17,-42063),m=s(m,f,g,E,d[l+11],22,-1990404162),E=s(E,m,f,g,d[l+12],7,1804603682),g=s(g,E,m,f,d[l+13],12,-40341101),f=s(f,g,E,m,d[l+14],17,-1502002290),m=s(m,f,g,E,d[l+15],22,1236535329),E=o(E,m,f,g,d[l+1],5,-165796510),g=o(g,E,m,f,d[l+6],9,-1069501632),f=o(f,g,E,m,d[l+11],14,643717713),m=o(m,f,g,E,d[l+0],20,-373897302),E=o(E,m,f,g,d[l+5],5,-701558691),g=o(g,E,m,f,d[l+10],9,38016083),f=o(f,g,E,m,d[l+15],14,-660478335),m=o(m,f,g,E,d[l+4],20,-405537848),E=o(E,m,f,g,d[l+9],5,568446438),g=o(g,E,m,f,d[l+14],9,-1019803690),f=o(f,g,E,m,d[l+3],14,-187363961),m=o(m,f,g,E,d[l+8],20,1163531501),E=o(E,m,f,g,d[l+13],5,-1444681467),g=o(g,E,m,f,d[l+2],9,-51403784),f=o(f,g,E,m,d[l+7],14,1735328473),m=o(m,f,g,E,d[l+12],20,-1926607734),E=a(E,m,f,g,d[l+5],4,-378558),g=a(g,E,m,f,d[l+8],11,-2022574463),f=a(f,g,E,m,d[l+11],16,1839030562),m=a(m,f,g,E,d[l+14],23,-35309556),E=a(E,m,f,g,d[l+1],4,-1530992060),g=a(g,E,m,f,d[l+4],11,1272893353),f=a(f,g,E,m,d[l+7],16,-155497632),m=a(m,f,g,E,d[l+10],23,-1094730640),E=a(E,m,f,g,d[l+13],4,681279174),g=a(g,E,m,f,d[l+0],11,-358537222),f=a(f,g,E,m,d[l+3],16,-722521979),m=a(m,f,g,E,d[l+6],23,76029189),E=a(E,m,f,g,d[l+9],4,-640364487),g=a(g,E,m,f,d[l+12],11,-421815835),f=a(f,g,E,m,d[l+15],16,530742520),m=a(m,f,g,E,d[l+2],23,-995338651),E=c(E,m,f,g,d[l+0],6,-198630844),g=c(g,E,m,f,d[l+7],10,1126891415),f=c(f,g,E,m,d[l+14],15,-1416354905),m=c(m,f,g,E,d[l+5],21,-57434055),E=c(E,m,f,g,d[l+12],6,1700485571),g=c(g,E,m,f,d[l+3],10,-1894986606),f=c(f,g,E,m,d[l+10],15,-1051523),m=c(m,f,g,E,d[l+1],21,-2054922799),E=c(E,m,f,g,d[l+8],6,1873313359),g=c(g,E,m,f,d[l+15],10,-30611744),f=c(f,g,E,m,d[l+6],15,-1560198380),m=c(m,f,g,E,d[l+13],21,1309151649),E=c(E,m,f,g,d[l+4],6,-145523070),g=c(g,E,m,f,d[l+11],10,-1120210379),f=c(f,g,E,m,d[l+2],15,718787259),m=c(m,f,g,E,d[l+9],21,-343485551),E=n(E,h),m=n(m,u),f=n(f,p),g=n(g,_);return i(E)+i(m)+i(f)+i(g)}(""+t+i)).slice(0,16),r=n.slice(0,12),s=await window.crypto.subtle.importKey("raw",n,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},s,e))},_b=async(e,t,i)=>await pb(e.buffer,t,i);function Eb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function mb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Eb(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Eb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class fb extends $y{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==zy.PLAYING)}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,t,i,n,r,s){if(super(e,r),nu(this,"trackMediaType","video"),nu(this,"_player",void 0),nu(this,"_videoVisibleTimer",null),nu(this,"_previousVideoVisibleStatus",void 0),nu(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),nu(this,"_encoderConfig",void 0),nu(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),nu(this,"_optimizationMode",void 0),nu(this,"_videoHeight",void 0),nu(this,"_videoWidth",void 0),nu(this,"_forceBitrateLimit",void 0),nu(this,"_enabled",!0),nu(this,"processorDestination",void 0),nu(this,"_processorContext",void 0),Tg()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=t,this._scalabilityMode=i,this._optimizationMode=n,this._hints=s||[],-1===this._hints.indexOf(Dy.SCREEN_TRACK))this.updateBitrateFromProfile();else if(function(e,t,i){const n=pg();return!(n.name!==e||!n.osVersion)&&(i?Number(n.version)>=t&&Number(n.version)<=i:Number(n.version)===t)}(cg.CHROME,115)&&-1!==_g().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&hA().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),n=new MediaStreamTrackGenerator({kind:"video"});let r,s,o=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),r&&(r.close(),r=void 0),e.stop(),s=void 0,n.removeEventListener("ended",a)};let c=window.setInterval((()=>{if(s&&r&&Date.now()-o>(null!=t?t:1e3))try{"live"===n.readyState?s.enqueue(r.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===n.readyState?(s=t,o=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close()}});return n.addEventListener("ended",a),i.readable.pipeThrough(d).pipeTo(n.writable),n}}(e);t&&(WC.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(Dy.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this.processorContext=new FA(this.getTrackId(),"local"),this.processorDestination=new VA(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(WC.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}WC.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=mb(mb(mb({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new db(i):this._player=new hb(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Uy.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),kC("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,WC.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(WC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await gS(this,Ny.NEED_DISABLE_TRACK,this)}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void WC.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await gS(this,Ny.NEED_ENABLE_TRACK,this)}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,WC.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await gS(this,Ny.NEED_MUTE_TRACK,this):await gS(this,Ny.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Vg(xg.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=vy(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=$A({encoderConfig:e});(Tg()||Cg()||Dg())&&(t.deviceId=void 0),WC.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new Vg(xg.UNEXPECTED_ERROR,e.toString());throw WC.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(Dy.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await gS(this,Ny.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(WC)}}getStats(){return NS((()=>{WC.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning"),SS(this,Ny.GET_STATS)||mb({},jy)}async setBeautyEffect(e){WC.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await rb(e)}async setBitrateLimit(e){if(WC.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e){this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<e.max_bitrate?this._encoderConfig.bitrateMax:e.max_bitrate:this._encoderConfig.bitrateMax=e.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=e.min_bitrate);try{await gS(this,Ny.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(WC)}}}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void WC.error(xg.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await gS(this,Ny.SET_OPTIMIZATION_MODE,this)}catch(e){throw this._optimizationMode=t,WC.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return WC.error(xg.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,WC.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){ub(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(FS)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const[n,r]=function(e,t,i,n){let r;const s=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75),o=s;if("STANDARD_BITRATE"===n)r=4*s;else{if("COMPATIABLE_BITRATE"!==n)return;r=2*s}return[Math.floor(r),Math.floor(o)]}(e,t,i,kC("BITRATE_ADAPTER_TYPE"))||[void 0,void 0];this._encoderConfig.bitrateMin||this._encoderConfig.bitrateMax||(this._encoderConfig.bitrateMin=r,this._encoderConfig.bitrateMax=n,WC.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(n,", brMin: ").concat(r,"]")))}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:s}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=Qg.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new Vg(xg.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new Vg(xg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=mb(mb({},i),vy(e))),i=wS(i);const n=xS(8,"track-video-cloned-"),r=new fb(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,i,wS(this._scalabilityMode),this._optimizationMode,n,wS(this._hints));return e&&i&&r.setEncoderConfiguration(i),WC.debug("clone video track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(t)),r}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new Vg(xg.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new Vg(xg.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}bindProcessorDestinationEvents(){this.processorDestination.on(Ky.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await gS(this,Ny.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gS(this,Ny.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Ky.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(Yy.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(Yy.REQUEST_CONSTRAINTS)}}Lv([tv({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Object,Object]),kv("design:returntype",void 0)],fb.prototype,"play",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],fb.prototype,"stop",null),Lv([qS("LocalVideoTrack","_enabledMutex"),tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Boolean]),kv("design:returntype",tg)],fb.prototype,"setEnabled",null),Lv([qS("LocalVideoTrack","_enabledMutex"),tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean]),kv("design:returntype",tg)],fb.prototype,"setMuted",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Object,Boolean]),kv("design:returntype",tg)],fb.prototype,"setEncoderConfiguration",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",Object)],fb.prototype,"getStats",null),Lv([tv({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Object]),kv("design:returntype",tg)],fb.prototype,"setBeautyEffect",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",ImageData)],fb.prototype,"getCurrentFrameData",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[String,Number]),kv("design:returntype",tg)],fb.prototype,"getCurrentFrameImage",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],fb.prototype,"setBitrateLimit",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],fb.prototype,"setOptimizationMode",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",void 0)],fb.prototype,"setScalabiltyMode",null),Lv([MA(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],fb.prototype,"updateMediaStreamTrackResolution",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t.name]}),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",Object)],fb.prototype,"pipe",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],fb.prototype,"unpipe",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],fb.prototype,"close",null),Lv([tv({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),kv("design:type",Function),kv("design:paramtypes",[MediaStreamTrack,Boolean]),kv("design:returntype",tg)],fb.prototype,"replaceTrack",null);class gb extends fb{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,n,r,s){super(e,vy(t.encoderConfig),n,r,s),nu(this,"_config",void 0),nu(this,"_originalConstraints",void 0),nu(this,"_constraints",void 0),nu(this,"_enabled",!0),nu(this,"_deviceName","default"),nu(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(wg()||Og())&&!function(){const e=pg();if(e.os!==ag.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}()&&Pg()&&this._enabled&&!this._isClosed&&(WC.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=vy(this._config.encoderConfig),nA.on(ly.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),nA.on(ly.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(e){return"string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0}async _setDeviceById(e){if(WC.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await AA.getDeviceById(e),i={};i.video=mb({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await CA(i,this.getTrackId())}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await CA({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await AA.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){WC.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:mb(mb({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await CA(t,this.getTrackId())}catch(t){throw WC.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await CA({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=mb({},t.video),WC.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(WC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await CA({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await gS(this,Ny.NEED_ENABLE_TRACK,this)}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),WC.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await gS(this,Ny.NEED_DISABLE_TRACK,this)}catch(e){throw WC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}WC.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Vg(xg.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=vy(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin);const i=bS(this._config);i.encoderConfig=e;const n=$A(i);(Tg()||Cg()||Dg())&&(n.deviceId=void 0),WC.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(n));try{await this._originMediaStreamTrack.applyConstraints(n),this.updateMediaStreamTrackResolution()}catch(e){const t=new Vg(xg.UNEXPECTED_ERROR,e.toString());throw WC.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=i,this._constraints=n,this._originalConstraints=n,this._encoderConfig=e,-1===this._hints.indexOf(Dy.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await gS(this,Ny.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(WC)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((Cg()||Dg())&&this._enabled&&!this._isClosed&&nA.duringInterruption){const e=async()=>{nA.off(ly.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(WC.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};nA.on(ly.IOS_INTERRUPTION_END,e)}else WC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Uy.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=AA.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await CA({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),nA.off(ly.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),nA.off(ly.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=mb(mb({},i),vy(e))),i=wS(i);const n=xS(8,"track-cam-cloned-"),r=new gb(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,wS(mb(mb({},this._config),{},{encoderConfig:i})),wS(this._constraints),wS(this._scalabilityMode),this._optimizationMode,n);return e&&i&&r.setEncoderConfiguration(i),WC.debug("clone track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(t)),r}bindProcessorContextEvents(){this.processorContext.on(Yy.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})),this.processorContext.on(Yy.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}}function Sb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Tb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Sb(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Sb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Rb(e,t,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=Tb(Tb({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?WC.debug("[".concat(e,"] set content hint to"),i.optimizationMode):WC.debug("[".concat(e,"] set content hint failed")))):WC.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}function Cb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function vb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Cb(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Cb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],gb.prototype,"setDevice",null),Lv([qS("CameraVideoTrack","_enabledMutex"),tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Boolean]),kv("design:returntype",tg)],gb.prototype,"setEnabled",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),MA(),kv("design:type",Function),kv("design:paramtypes",[Object,Boolean]),kv("design:returntype",tg)],gb.prototype,"setEncoderConfiguration",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],gb.prototype,"close",null);class Ib extends Zy{getUserId(){return this._userId}constructor(e,t,i,n){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(n.clientId,"_").concat(xS(5,""))),nu(this,"_userId",void 0),nu(this,"_uintId",void 0),nu(this,"_isDestroyed",!1),nu(this,"store",void 0),nu(this,"processor",void 0),this._userId=t,this._uintId=i,this.store=n}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,WC.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}class yb extends Ib{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==zy.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,n){super(e,t,i,n),nu(this,"_videoVisibleTimer",null),nu(this,"_previousVideoVisibleStatus",void 0),nu(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),nu(this,"trackMediaType","video"),nu(this,"_videoWidth",void 0),nu(this,"_videoHeight",void 0),nu(this,"_player",void 0),nu(this,"processorDestination",void 0),nu(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new FA(this.getTrackId(),"remote"),this.processorDestination=new VA(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return NS((()=>{WC.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning"),SS(this,Ny.GET_STATS)||vb({},Hy)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(WC.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}WC.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=vb(vb({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new db(i):this._player=new hb(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(xy.FIRST_FRAME_DECODED)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(xy.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),kC("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,WC.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){ub(this._originMediaStreamTrack).then((e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t})).catch(FS)}_updatePlayerSource(){WC.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:s}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=Qg.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new Vg(xg.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new Vg(xg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Ky.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Ky.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}}Lv([tv({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),kv("design:type",Function),kv("design:paramtypes",[Object,Object]),kv("design:returntype",void 0)],yb.prototype,"play",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],yb.prototype,"stop",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t.name]}),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",Object)],yb.prototype,"pipe",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],yb.prototype,"unpipe",null);class Ab extends Ib{get isPlaying(){return this._useAudioElement?kA.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,n){super(e,t,i,n),nu(this,"trackMediaType","audio"),nu(this,"_source",void 0),nu(this,"_useAudioElement",!0),nu(this,"_volume",100),nu(this,"processorContext",void 0),nu(this,"processorDestination",void 0),nu(this,"_played",!1),nu(this,"_bypassWebAudio",!1),kC("DISABLE_WEBAUDIO")?(this._source=new GA,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new _A(e,!0),kC("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(Vy.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(xy.FIRST_FRAME_DECODED)})),this.processorContext=new jA(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new BA(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Vy.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Vy.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Vy.ON_AUDIO_BUFFER),this._source.on(Vy.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?kA.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement)throw new Vg(xg.NOT_SUPPORTED,"your browser does not support setting the audio output device");await kA.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){return NS((()=>{WC.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning"),SS(this,Ny.GET_STATS)||vb({},Gy)}play(){WC.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(WC.debug("[".concat(this.getTrackId(),"] use audio element to play")),kA.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){WC.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?kA.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];WC.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&kA.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new Vg(xg.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new Vg(xg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new Vg(xg.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Ky.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(Ky.ON_NODE,(e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Ky.ON_TRACK),this.processorDestination.removeAllListeners(Ky.ON_NODE)}}function bb(e){let t=e.length;for(;--t>=0;)e[t]=0}Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",void 0)],Ab.prototype,"setVolume",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t]}),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],Ab.prototype,"setPlaybackDevice",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],Ab.prototype,"play",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],Ab.prototype,"stop",null),Lv([tv({argsMap:(e,t)=>[e.getTrackId(),t.name]}),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",Object)],Ab.prototype,"pipe",null),Lv([tv({argsMap:e=>[e.getTrackId()]}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],Ab.prototype,"unpipe",null);const wb=256,Ob=286,Nb=30,Db=15,Pb=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Lb=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),kb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Mb=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ub=new Array(576);bb(Ub);const xb=new Array(60);bb(xb);const Vb=new Array(512);bb(Vb);const Fb=new Array(256);bb(Fb);const Bb=new Array(29);bb(Bb);const jb=new Array(Nb);function Gb(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}let Wb,Hb,Kb;function Yb(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}bb(jb);const qb=e=>e<256?Vb[e]:Vb[256+(e>>>7)],Jb=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},zb=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,Jb(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)},Xb=(e,t,i)=>{zb(e,i[2*t],i[2*t+1])},Qb=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},Zb=(e,t,i)=>{const n=new Array(16);let r,s,o=0;for(r=1;r<=Db;r++)o=o+i[r-1]<<1,n[r]=o;for(s=0;s<=t;s++){let t=e[2*s+1];0!==t&&(e[2*s]=Qb(n[t]++,t))}},$b=e=>{let t;for(t=0;t<Ob;t++)e.dyn_ltree[2*t]=0;for(t=0;t<Nb;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},ew=e=>{e.bi_valid>8?Jb(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},tw=(e,t,i,n)=>{const r=2*t,s=2*i;return e[r]<e[s]||e[r]===e[s]&&n[t]<=n[i]},iw=(e,t,i)=>{const n=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r<e.heap_len&&tw(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!tw(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n},nw=(e,t,i)=>{let n,r,s,o,a=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+a++],n+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],0===n?Xb(e,r,t):(s=Fb[r],Xb(e,s+wb+1,t),o=Pb[s],0!==o&&(r-=Bb[s],zb(e,r,o)),n--,s=qb(n),Xb(e,s,i),o=Lb[s],0!==o&&(n-=jb[s],zb(e,n,o)))}while(a<e.sym_next);Xb(e,256,t)},rw=(e,t)=>{const i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,s=t.stat_desc.elems;let o,a,c,d=-1;for(e.heap_len=0,e.heap_max=573,o=0;o<s;o++)0!==i[2*o]?(e.heap[++e.heap_len]=d=o,e.depth[o]=0):i[2*o+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=d<2?++d:0,i[2*c]=1,e.depth[c]=0,e.opt_len--,r&&(e.static_len-=n[2*c+1]);for(t.max_code=d,o=e.heap_len>>1;o>=1;o--)iw(e,i,o);c=s;do{o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],iw(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=a,i[2*c]=i[2*o]+i[2*a],e.depth[c]=(e.depth[o]>=e.depth[a]?e.depth[o]:e.depth[a])+1,i[2*o+1]=i[2*a+1]=c,e.heap[1]=c++,iw(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,s=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,l,h,u,p,_,E=0;for(u=0;u<=Db;u++)e.bl_count[u]=0;for(i[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)l=e.heap[d],u=i[2*i[2*l+1]+1]+1,u>c&&(u=c,E++),i[2*l+1]=u,l>n||(e.bl_count[u]++,p=0,l>=a&&(p=o[l-a]),_=i[2*l],e.opt_len+=_*(u+p),s&&(e.static_len+=_*(r[2*l+1]+p)));if(0!==E){do{for(u=c-1;0===e.bl_count[u];)u--;e.bl_count[u]--,e.bl_count[u+1]+=2,e.bl_count[c]--,E-=2}while(E>0);for(u=c;0!==u;u--)for(l=e.bl_count[u];0!==l;)h=e.heap[--d],h>n||(i[2*h+1]!==u&&(e.opt_len+=(u-i[2*h+1])*i[2*h],i[2*h+1]=u),l--)}})(e,t),Zb(i,d,e.bl_count)},sw=(e,t,i)=>{let n,r,s=-1,o=t[1],a=0,c=7,d=4;for(0===o&&(c=138,d=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=o,o=t[2*(n+1)+1],++a<c&&r===o||(a<d?e.bl_tree[2*r]+=a:0!==r?(r!==s&&e.bl_tree[2*r]++,e.bl_tree[32]++):a<=10?e.bl_tree[34]++:e.bl_tree[36]++,a=0,s=r,0===o?(c=138,d=3):r===o?(c=6,d=3):(c=7,d=4))},ow=(e,t,i)=>{let n,r,s=-1,o=t[1],a=0,c=7,d=4;for(0===o&&(c=138,d=3),n=0;n<=i;n++)if(r=o,o=t[2*(n+1)+1],!(++a<c&&r===o)){if(a<d)do{Xb(e,r,e.bl_tree)}while(0!=--a);else 0!==r?(r!==s&&(Xb(e,r,e.bl_tree),a--),Xb(e,16,e.bl_tree),zb(e,a-3,2)):a<=10?(Xb(e,17,e.bl_tree),zb(e,a-3,3)):(Xb(e,18,e.bl_tree),zb(e,a-11,7));a=0,s=r,0===o?(c=138,d=3):r===o?(c=6,d=3):(c=7,d=4)}};let aw=!1;const cw=(e,t,i,n)=>{zb(e,0+(n?1:0),3),ew(e),Jb(e,i),Jb(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var dw=e=>{aw||((()=>{let e,t,i,n,r;const s=new Array(16);for(i=0,n=0;n<28;n++)for(Bb[n]=i,e=0;e<1<<Pb[n];e++)Fb[i++]=n;for(Fb[i-1]=n,r=0,n=0;n<16;n++)for(jb[n]=r,e=0;e<1<<Lb[n];e++)Vb[r++]=n;for(r>>=7;n<Nb;n++)for(jb[n]=r<<7,e=0;e<1<<Lb[n]-7;e++)Vb[256+r++]=n;for(t=0;t<=Db;t++)s[t]=0;for(e=0;e<=143;)Ub[2*e+1]=8,e++,s[8]++;for(;e<=255;)Ub[2*e+1]=9,e++,s[9]++;for(;e<=279;)Ub[2*e+1]=7,e++,s[7]++;for(;e<=287;)Ub[2*e+1]=8,e++,s[8]++;for(Zb(Ub,287,s),e=0;e<Nb;e++)xb[2*e+1]=5,xb[2*e]=Qb(e,5);Wb=new Gb(Ub,Pb,257,Ob,Db),Hb=new Gb(xb,Lb,0,Nb,Db),Kb=new Gb(new Array(0),kb,0,19,7)})(),aw=!0),e.l_desc=new Yb(e.dyn_ltree,Wb),e.d_desc=new Yb(e.dyn_dtree,Hb),e.bl_desc=new Yb(e.bl_tree,Kb),e.bi_buf=0,e.bi_valid=0,$b(e)},lw=(e,t,i,n)=>{let r,s,o=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<wb;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),rw(e,e.l_desc),rw(e,e.d_desc),o=(e=>{let t;for(sw(e,e.dyn_ltree,e.l_desc.max_code),sw(e,e.dyn_dtree,e.d_desc.max_code),rw(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*Mb[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=r&&(r=s)):r=s=i+5,i+4<=r&&-1!==t?cw(e,t,i,n):4===e.strategy||s===r?(zb(e,2+(n?1:0),3),nw(e,Ub,xb)):(zb(e,4+(n?1:0),3),((e,t,i,n)=>{let r;for(zb(e,t-257,5),zb(e,i-1,5),zb(e,n-4,4),r=0;r<n;r++)zb(e,e.bl_tree[2*Mb[r]+1],3);ow(e,e.dyn_ltree,t-1),ow(e,e.dyn_dtree,i-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,o+1),nw(e,e.dyn_ltree,e.dyn_dtree)),$b(e),n&&ew(e)},hw=(e,t,i)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(Fb[i]+wb+1)]++,e.dyn_dtree[2*qb(t)]++),e.sym_next===e.sym_end),uw={_tr_init:dw,_tr_stored_block:cw,_tr_flush_block:lw,_tr_tally:hw,_tr_align:e=>{zb(e,2,3),Xb(e,256,Ub),(e=>{16===e.bi_valid?(Jb(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)}},pw=(e,t,i,n)=>{let r=65535&e|0,s=e>>>16&65535|0,o=0;for(;0!==i;){o=i>2e3?2e3:i,i-=o;do{r=r+t[n++]|0,s=s+r|0}while(--o);r%=65521,s%=65521}return r|s<<16|0};const _w=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var Ew=(e,t,i,n)=>{const r=_w,s=n+i;e^=-1;for(let i=n;i<s;i++)e=e>>>8^r[255&(e^t[i])];return-1^e},mw={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},fw={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:gw,_tr_stored_block:Sw,_tr_flush_block:Tw,_tr_tally:Rw,_tr_align:Cw}=uw,{Z_NO_FLUSH:vw,Z_PARTIAL_FLUSH:Iw,Z_FULL_FLUSH:yw,Z_FINISH:Aw,Z_BLOCK:bw,Z_OK:ww,Z_STREAM_END:Ow,Z_STREAM_ERROR:Nw,Z_DATA_ERROR:Dw,Z_BUF_ERROR:Pw,Z_DEFAULT_COMPRESSION:Lw,Z_FILTERED:kw,Z_HUFFMAN_ONLY:Mw,Z_RLE:Uw,Z_FIXED:xw,Z_DEFAULT_STRATEGY:Vw,Z_UNKNOWN:Fw,Z_DEFLATED:Bw}=fw,jw=286,Gw=30,Ww=19,Hw=2*jw+1,Kw=15,Yw=258,qw=262,Jw=42,zw=113,Xw=666,Qw=(e,t)=>(e.msg=mw[t],t),Zw=e=>2*e-(e>4?9:0),$w=e=>{let t=e.length;for(;--t>=0;)e[t]=0},eO=e=>{let t,i,n,r=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=r?i-r:0}while(--t);t=r,n=t;do{i=e.prev[--n],e.prev[n]=i>=r?i-r:0}while(--t)};let tO=(e,t,i)=>(t<<e.hash_shift^i)&e.hash_mask;const iO=e=>{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},nO=(e,t)=>{Tw(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,iO(e.strm)},rO=(e,t)=>{e.pending_buf[e.pending++]=t},sO=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},oO=(e,t,i,n)=>{let r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=pw(e.adler,t,r,i):2===e.state.wrap&&(e.adler=Ew(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},aO=(e,t)=>{let i,n,r=e.max_chain_length,s=e.strstart,o=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-qw?e.strstart-(e.w_size-qw):0,d=e.window,l=e.w_mask,h=e.prev,u=e.strstart+Yw;let p=d[s+o-1],_=d[s+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,d[i+o]===_&&d[i+o-1]===p&&d[i]===d[s]&&d[++i]===d[s+1]){s+=2,i++;do{}while(d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&s<u);if(n=Yw-(u-s),s=u-Yw,n>o){if(e.match_start=t,o=n,n>=a)break;p=d[s+o-1],_=d[s+o]}}}while((t=h[t&l])>c&&0!=--r);return o<=e.lookahead?o:e.lookahead},cO=e=>{const t=e.w_size;let i,n,r;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-qw)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),eO(e),n+=t),0===e.strm.avail_in)break;if(i=oO(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=tO(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=tO(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<qw&&0!==e.strm.avail_in)},dO=(e,t)=>{let i,n,r,s=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,o=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_out<r)break;if(r=e.strm.avail_out-r,n=e.strstart-e.block_start,i>n+e.strm.avail_in&&(i=n+e.strm.avail_in),i>r&&(i=r),i<s&&(0===i&&t!==Aw||t===vw||i!==n+e.strm.avail_in))break;o=t===Aw&&i===n+e.strm.avail_in?1:0,Sw(e,0,0,o),e.pending_buf[e.pending-4]=i,e.pending_buf[e.pending-3]=i>>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,iO(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(oO(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===o);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),o?4:t!==vw&&t!==Aw&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(r=e.window_size-e.strstart,e.strm.avail_in>r&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(oO(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water<e.strstart&&(e.high_water=e.strstart),r=e.bi_valid+42>>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,s=r>e.w_size?e.w_size:r,n=e.strstart-e.block_start,(n>=s||(n||t===Aw)&&t!==vw&&0===e.strm.avail_in&&n<=r)&&(i=n>r?r:n,o=t===Aw&&0===e.strm.avail_in&&i===n?1:0,Sw(e,e.block_start,i,o),e.block_start+=i,iO(e.strm)),o?3:1)},lO=(e,t)=>{let i,n;for(;;){if(e.lookahead<qw){if(cO(e),e.lookahead<qw&&t===vw)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=tO(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-qw&&(e.match_length=aO(e,i)),e.match_length>=3)if(n=Rw(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=tO(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=tO(e,e.ins_h,e.window[e.strstart+1]);else n=Rw(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(nO(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===Aw?(nO(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nO(e,!1),0===e.strm.avail_out)?1:2},hO=(e,t)=>{let i,n,r;for(;;){if(e.lookahead<qw){if(cO(e),e.lookahead<qw&&t===vw)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=tO(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-qw&&(e.match_length=aO(e,i),e.match_length<=5&&(e.strategy===kw||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=Rw(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=tO(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(nO(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=Rw(e,0,e.window[e.strstart-1]),n&&nO(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=Rw(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===Aw?(nO(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nO(e,!1),0===e.strm.avail_out)?1:2};function uO(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}const pO=[new uO(0,0,0,0,dO),new uO(4,4,8,4,lO),new uO(4,5,16,8,lO),new uO(4,6,32,32,lO),new uO(4,4,16,16,hO),new uO(8,16,32,32,hO),new uO(8,16,128,128,hO),new uO(8,32,128,256,hO),new uO(32,128,258,1024,hO),new uO(32,258,258,4096,hO)];function _O(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Bw,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*Hw),this.dyn_dtree=new Uint16Array(2*(2*Gw+1)),this.bl_tree=new Uint16Array(2*(2*Ww+1)),$w(this.dyn_ltree),$w(this.dyn_dtree),$w(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(Kw+1),this.heap=new Uint16Array(2*jw+1),$w(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*jw+1),$w(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const EO=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==Jw&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==zw&&t.status!==Xw?1:0},mO=e=>{if(EO(e))return Qw(e,Nw);e.total_in=e.total_out=0,e.data_type=Fw;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?Jw:zw,e.adler=2===t.wrap?0:1,t.last_flush=-2,gw(t),ww},fO=e=>{const t=mO(e);var i;return t===ww&&((i=e.state).window_size=2*i.w_size,$w(i.head),i.max_lazy_match=pO[i.level].max_lazy,i.good_match=pO[i.level].good_length,i.nice_match=pO[i.level].nice_length,i.max_chain_length=pO[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t},gO=(e,t,i,n,r,s)=>{if(!e)return Nw;let o=1;if(t===Lw&&(t=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),r<1||r>9||i!==Bw||n<8||n>15||t<0||t>9||s<0||s>xw||8===n&&1!==o)return Qw(e,Nw);8===n&&(n=9);const a=new _O;return e.state=a,a.strm=e,a.status=Jw,a.wrap=o,a.gzhead=null,a.w_bits=n,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=r+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+3-1)/3),a.window=new Uint8Array(2*a.w_size),a.head=new Uint16Array(a.hash_size),a.prev=new Uint16Array(a.w_size),a.lit_bufsize=1<<r+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new Uint8Array(a.pending_buf_size),a.sym_buf=a.lit_bufsize,a.sym_end=3*(a.lit_bufsize-1),a.level=t,a.strategy=s,a.method=i,fO(e)};var SO=(e,t)=>{if(EO(e)||t>bw||t<0)return e?Qw(e,Nw):Nw;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===Xw&&t!==Aw)return Qw(e,0===e.avail_out?Pw:Nw);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(iO(e),0===e.avail_out)return i.last_flush=-1,ww}else if(0===e.avail_in&&Zw(t)<=Zw(n)&&t!==Aw)return Qw(e,Pw);if(i.status===Xw&&0!==e.avail_in)return Qw(e,Pw);if(i.status===Jw&&0===i.wrap&&(i.status=zw),i.status===Jw){let t=Bw+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=Mw||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,sO(i,t),0!==i.strstart&&(sO(i,e.adler>>>16),sO(i,65535&e.adler)),e.adler=1,i.status=zw,iO(e),0!==i.pending)return i.last_flush=-1,ww}if(57===i.status)if(e.adler=0,rO(i,31),rO(i,139),rO(i,8),i.gzhead)rO(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),rO(i,255&i.gzhead.time),rO(i,i.gzhead.time>>8&255),rO(i,i.gzhead.time>>16&255),rO(i,i.gzhead.time>>24&255),rO(i,9===i.level?2:i.strategy>=Mw||i.level<2?4:0),rO(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(rO(i,255&i.gzhead.extra.length),rO(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=Ew(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(rO(i,0),rO(i,0),rO(i,0),rO(i,0),rO(i,0),rO(i,9===i.level?2:i.strategy>=Mw||i.level<2?4:0),rO(i,3),i.status=zw,iO(e),0!==i.pending)return i.last_flush=-1,ww;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,iO(e),0!==i.pending)return i.last_flush=-1,ww;t=0,n-=r}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-n,n)),iO(e),0!==i.pending)return i.last_flush=-1,ww;n=0}t=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,rO(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-n,n)),iO(e),0!==i.pending)return i.last_flush=-1,ww;n=0}t=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,rO(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Ew(e.adler,i.pending_buf,i.pending-n,n))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(iO(e),0!==i.pending))return i.last_flush=-1,ww;rO(i,255&e.adler),rO(i,e.adler>>8&255),e.adler=0}if(i.status=zw,iO(e),0!==i.pending)return i.last_flush=-1,ww}if(0!==e.avail_in||0!==i.lookahead||t!==vw&&i.status!==Xw){let n=0===i.level?dO(i,t):i.strategy===Mw?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(cO(e),0===e.lookahead)){if(t===vw)return 1;break}if(e.match_length=0,i=Rw(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(nO(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===Aw?(nO(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nO(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===Uw?((e,t)=>{let i,n,r,s;const o=e.window;for(;;){if(e.lookahead<=Yw){if(cO(e),e.lookahead<=Yw&&t===vw)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,n=o[r],n===o[++r]&&n===o[++r]&&n===o[++r])){s=e.strstart+Yw;do{}while(n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&r<s);e.match_length=Yw-(s-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=Rw(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=Rw(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(nO(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===Aw?(nO(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nO(e,!1),0===e.strm.avail_out)?1:2})(i,t):pO[i.level].func(i,t);if(3!==n&&4!==n||(i.status=Xw),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),ww;if(2===n&&(t===Iw?Cw(i):t!==bw&&(Sw(i,0,0,!1),t===yw&&($w(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),iO(e),0===e.avail_out))return i.last_flush=-1,ww}return t!==Aw?ww:i.wrap<=0?Ow:(2===i.wrap?(rO(i,255&e.adler),rO(i,e.adler>>8&255),rO(i,e.adler>>16&255),rO(i,e.adler>>24&255),rO(i,255&e.total_in),rO(i,e.total_in>>8&255),rO(i,e.total_in>>16&255),rO(i,e.total_in>>24&255)):(sO(i,e.adler>>>16),sO(i,65535&e.adler)),iO(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?ww:Ow)},TO=(e,t)=>{let i=t.length;if(EO(e))return Nw;const n=e.state,r=n.wrap;if(2===r||1===r&&n.status!==Jw||n.lookahead)return Nw;if(1===r&&(e.adler=pw(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===r&&($w(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size}const s=e.avail_in,o=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,cO(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=tO(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++}while(--t);n.strstart=e,n.lookahead=2,cO(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=o,e.input=a,e.avail_in=s,n.wrap=r,ww},RO={deflateInit:(e,t)=>gO(e,t,Bw,15,8,Vw),deflateInit2:gO,deflateReset:fO,deflateResetKeep:mO,deflateSetHeader:(e,t)=>EO(e)||2!==e.state.wrap?Nw:(e.state.gzhead=t,ww),deflate:SO,deflateEnd:e=>{if(EO(e))return Nw;const t=e.state.status;return e.state=null,t===zw?Qw(e,Dw):ww},deflateSetDictionary:TO,deflateInfo:"pako deflate (from Nodeca project)"};const CO=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var vO={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)CO(i,t)&&(e[t]=i[t])}}return e},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i<n;i++)t+=e[i].length;const i=new Uint8Array(t);for(let t=0,n=0,r=e.length;t<r;t++){let r=e[t];i.set(r,n),n+=r.length}return i}};let IO=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){IO=!1}const yO=new Uint8Array(256);for(let e=0;e<256;e++)yO[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;yO[254]=yO[254]=1;var AO={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,r,s,o=e.length,a=0;for(r=0;r<o;r++)i=e.charCodeAt(r),55296==(64512&i)&&r+1<o&&(n=e.charCodeAt(r+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),a+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Uint8Array(a),s=0,r=0;s<a;r++)i=e.charCodeAt(r),55296==(64512&i)&&r+1<o&&(n=e.charCodeAt(r+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[s++]=i:i<2048?(t[s++]=192|i>>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t},buf2string:(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let n,r;const s=new Array(2*i);for(r=0,n=0;n<i;){let t=e[n++];if(t<128){s[r++]=t;continue}let o=yO[t];if(o>4)s[r++]=65533,n+=o-1;else{for(t&=2===o?31:3===o?15:7;o>1&&n<i;)t=t<<6|63&e[n++],o--;o>1?s[r++]=65533:t<65536?s[r++]=t:(t-=65536,s[r++]=55296|t>>10&1023,s[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&IO)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let n=0;n<t;n++)i+=String.fromCharCode(e[n]);return i})(s,r)},utf8border:(e,t)=>{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+yO[e[i]]>t?i:t}},bO=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const wO=Object.prototype.toString,{Z_NO_FLUSH:OO,Z_SYNC_FLUSH:NO,Z_FULL_FLUSH:DO,Z_FINISH:PO,Z_OK:LO,Z_STREAM_END:kO,Z_DEFAULT_COMPRESSION:MO,Z_DEFAULT_STRATEGY:UO,Z_DEFLATED:xO}=fw;function VO(e){this.options=vO.assign({level:MO,method:xO,chunkSize:16384,windowBits:15,memLevel:8,strategy:UO},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new bO,this.strm.avail_out=0;let i=RO.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==LO)throw new Error(mw[i]);if(t.header&&RO.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?AO.string2buf(t.dictionary):"[object ArrayBuffer]"===wO.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=RO.deflateSetDictionary(this.strm,e),i!==LO)throw new Error(mw[i]);this._dict_set=!0}}function FO(e,t){const i=new VO(t);if(i.push(e,!0),i.err)throw i.msg||mw[i.err];return i.result}VO.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let r,s;if(this.ended)return!1;for(s=t===~~t?t:!0===t?PO:OO,"string"==typeof e?i.input=AO.string2buf(e):"[object ArrayBuffer]"===wO.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(s===NO||s===DO)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=RO.deflate(i,s),r===kO)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=RO.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===LO;if(0!==i.avail_out){if(s>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},VO.prototype.onData=function(e){this.chunks.push(e)},VO.prototype.onEnd=function(e){e===LO&&(this.result=vO.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var BO={Deflate:VO,deflate:FO,deflateRaw:function(e,t){return(t=t||{}).raw=!0,FO(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,FO(e,t)},constants:fw};const jO=16209;var GO=function(e,t){let i,n,r,s,o,a,c,d,l,h,u,p,_,E,m,f,g,S,T,R,C,v,I,y;const A=e.state;i=e.next_in,I=e.input,n=i+(e.avail_in-5),r=e.next_out,y=e.output,s=r-(t-e.avail_out),o=r+(e.avail_out-257),a=A.dmax,c=A.wsize,d=A.whave,l=A.wnext,h=A.window,u=A.hold,p=A.bits,_=A.lencode,E=A.distcode,m=(1<<A.lenbits)-1,f=(1<<A.distbits)-1;e:do{p<15&&(u+=I[i++]<<p,p+=8,u+=I[i++]<<p,p+=8),g=_[u&m];t:for(;;){if(S=g>>>24,u>>>=S,p-=S,S=g>>>16&255,0===S)y[r++]=65535&g;else{if(!(16&S)){if(0==(64&S)){g=_[(65535&g)+(u&(1<<S)-1)];continue t}if(32&S){A.mode=16191;break e}e.msg="invalid literal/length code",A.mode=jO;break e}T=65535&g,S&=15,S&&(p<S&&(u+=I[i++]<<p,p+=8),T+=u&(1<<S)-1,u>>>=S,p-=S),p<15&&(u+=I[i++]<<p,p+=8,u+=I[i++]<<p,p+=8),g=E[u&f];i:for(;;){if(S=g>>>24,u>>>=S,p-=S,S=g>>>16&255,!(16&S)){if(0==(64&S)){g=E[(65535&g)+(u&(1<<S)-1)];continue i}e.msg="invalid distance code",A.mode=jO;break e}if(R=65535&g,S&=15,p<S&&(u+=I[i++]<<p,p+=8,p<S&&(u+=I[i++]<<p,p+=8)),R+=u&(1<<S)-1,R>a){e.msg="invalid distance too far back",A.mode=jO;break e}if(u>>>=S,p-=S,S=r-s,R>S){if(S=R-S,S>d&&A.sane){e.msg="invalid distance too far back",A.mode=jO;break e}if(C=0,v=h,0===l){if(C+=c-S,S<T){T-=S;do{y[r++]=h[C++]}while(--S);C=r-R,v=y}}else if(l<S){if(C+=c+l-S,S-=l,S<T){T-=S;do{y[r++]=h[C++]}while(--S);if(C=0,l<T){S=l,T-=S;do{y[r++]=h[C++]}while(--S);C=r-R,v=y}}}else if(C+=l-S,S<T){T-=S;do{y[r++]=h[C++]}while(--S);C=r-R,v=y}for(;T>2;)y[r++]=v[C++],y[r++]=v[C++],y[r++]=v[C++],T-=3;T&&(y[r++]=v[C++],T>1&&(y[r++]=v[C++]))}else{C=r-R;do{y[r++]=y[C++],y[r++]=y[C++],y[r++]=y[C++],T-=3}while(T>2);T&&(y[r++]=y[C++],T>1&&(y[r++]=y[C++]))}break}}break}}while(i<n&&r<o);T=p>>3,i-=T,p-=T<<3,u&=(1<<p)-1,e.next_in=i,e.next_out=r,e.avail_in=i<n?n-i+5:5-(i-n),e.avail_out=r<o?o-r+257:257-(r-o),A.hold=u,A.bits=p};const WO=15,HO=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),KO=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),YO=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),qO=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var JO=(e,t,i,n,r,s,o,a)=>{const c=a.bits;let d,l,h,u,p,_,E=0,m=0,f=0,g=0,S=0,T=0,R=0,C=0,v=0,I=0,y=null;const A=new Uint16Array(16),b=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=WO;E++)A[E]=0;for(m=0;m<n;m++)A[t[i+m]]++;for(S=c,g=WO;g>=1&&0===A[g];g--);if(S>g&&(S=g),0===g)return r[s++]=20971520,r[s++]=20971520,a.bits=1,0;for(f=1;f<g&&0===A[f];f++);for(S<f&&(S=f),C=1,E=1;E<=WO;E++)if(C<<=1,C-=A[E],C<0)return-1;if(C>0&&(0===e||1!==g))return-1;for(b[1]=0,E=1;E<WO;E++)b[E+1]=b[E]+A[E];for(m=0;m<n;m++)0!==t[i+m]&&(o[b[t[i+m]]++]=m);if(0===e?(y=D=o,_=20):1===e?(y=HO,D=KO,_=257):(y=YO,D=qO,_=0),I=0,m=0,E=f,p=s,T=S,R=0,h=-1,v=1<<S,u=v-1,1===e&&v>852||2===e&&v>592)return 1;for(;;){w=E-R,o[m]+1<_?(O=0,N=o[m]):o[m]>=_?(O=D[o[m]-_],N=y[o[m]-_]):(O=96,N=0),d=1<<E-R,l=1<<T,f=l;do{l-=d,r[p+(I>>R)+l]=w<<24|O<<16|N|0}while(0!==l);for(d=1<<E-1;I&d;)d>>=1;if(0!==d?(I&=d-1,I+=d):I=0,m++,0==--A[E]){if(E===g)break;E=t[i+o[m]]}if(E>S&&(I&u)!==h){for(0===R&&(R=S),p+=f,T=E-R,C=1<<T;T+R<g&&(C-=A[T+R],!(C<=0));)T++,C<<=1;if(v+=1<<T,1===e&&v>852||2===e&&v>592)return 1;h=I&u,r[h]=S<<24|T<<16|p-s|0}}return 0!==I&&(r[p+I]=E-R<<24|64<<16|0),a.bits=S,0};const{Z_FINISH:zO,Z_BLOCK:XO,Z_TREES:QO,Z_OK:ZO,Z_STREAM_END:$O,Z_NEED_DICT:eN,Z_STREAM_ERROR:tN,Z_DATA_ERROR:iN,Z_MEM_ERROR:nN,Z_BUF_ERROR:rN,Z_DEFLATED:sN}=fw,oN=16180,aN=16190,cN=16191,dN=16192,lN=16194,hN=16199,uN=16200,pN=16206,_N=16209,EN=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function mN(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const fN=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<oN||t.mode>16211?1:0},gN=e=>{if(fN(e))return tN;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=oN,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,ZO},SN=e=>{if(fN(e))return tN;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,gN(e)},TN=(e,t)=>{let i;if(fN(e))return tN;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?tN:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,SN(e))},RN=(e,t)=>{if(!e)return tN;const i=new mN;e.state=i,i.strm=e,i.window=null,i.mode=oN;const n=TN(e,t);return n!==ZO&&(e.state=null),n};let CN,vN,IN=!0;const yN=e=>{if(IN){CN=new Int32Array(512),vN=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(JO(1,e.lens,0,288,CN,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;JO(2,e.lens,0,32,vN,0,e.work,{bits:5}),IN=!1}e.lencode=CN,e.lenbits=9,e.distcode=vN,e.distbits=5},AN=(e,t,i,n)=>{let r;const s=e.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),n>=s.wsize?(s.window.set(t.subarray(i-s.wsize,i),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>n&&(r=n),s.window.set(t.subarray(i-n,i-n+r),s.wnext),(n-=r)?(s.window.set(t.subarray(i-n,i),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=r))),0};var bN=(e,t)=>{let i,n,r,s,o,a,c,d,l,h,u,p,_,E,m,f,g,S,T,R,C,v,I=0;const y=new Uint8Array(4);let A,b;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(fN(e)||!e.output||!e.input&&0!==e.avail_in)return tN;i=e.state,i.mode===cN&&(i.mode=dN),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,h=a,u=c,v=ZO;e:for(;;)switch(i.mode){case oN:if(0===i.wrap){i.mode=dN;break}for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(2&i.wrap&&35615===d){0===i.wbits&&(i.wbits=15),i.check=0,y[0]=255&d,y[1]=d>>>8&255,i.check=Ew(i.check,y,2,0),d=0,l=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg="incorrect header check",i.mode=_N;break}if((15&d)!==sN){e.msg="unknown compression method",i.mode=_N;break}if(d>>>=4,l-=4,C=8+(15&d),0===i.wbits&&(i.wbits=C),C>15||C>i.wbits){e.msg="invalid window size",i.mode=_N;break}i.dmax=1<<i.wbits,i.flags=0,e.adler=i.check=1,i.mode=512&d?16189:cN,d=0,l=0;break;case 16181:for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(i.flags=d,(255&i.flags)!==sN){e.msg="unknown compression method",i.mode=_N;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=_N;break}i.head&&(i.head.text=d>>8&1),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=Ew(i.check,y,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.head&&(i.head.time=d),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,y[2]=d>>>16&255,y[3]=d>>>24&255,i.check=Ew(i.check,y,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.head&&(i.head.xflags=255&d,i.head.os=d>>8),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=Ew(i.check,y,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&i.flags){for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.length=d,i.head&&(i.head.extra_len=d),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=Ew(i.check,y,2,0)),d=0,l=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(p=i.length,p>a&&(p=a),p&&(i.head&&(C=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(s,s+p),C)),512&i.flags&&4&i.wrap&&(i.check=Ew(i.check,n,p,s)),a-=p,s+=p,i.length-=p),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;p=0;do{C=n[s+p++],i.head&&C&&i.length<65536&&(i.head.name+=String.fromCharCode(C))}while(C&&p<a);if(512&i.flags&&4&i.wrap&&(i.check=Ew(i.check,n,p,s)),a-=p,s+=p,C)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=16187;case 16187:if(4096&i.flags){if(0===a)break e;p=0;do{C=n[s+p++],i.head&&C&&i.length<65536&&(i.head.comment+=String.fromCharCode(C))}while(C&&p<a);if(512&i.flags&&4&i.wrap&&(i.check=Ew(i.check,n,p,s)),a-=p,s+=p,C)break e}else i.head&&(i.head.comment=null);i.mode=16188;case 16188:if(512&i.flags){for(;l<16;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(4&i.wrap&&d!==(65535&i.check)){e.msg="header crc mismatch",i.mode=_N;break}d=0,l=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=cN;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}e.adler=i.check=EN(d),d=0,l=0,i.mode=aN;case aN:if(0===i.havedict)return e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,eN;e.adler=i.check=1,i.mode=cN;case cN:if(t===XO||t===QO)break e;case dN:if(i.last){d>>>=7&l,l-=7&l,i.mode=pN;break}for(;l<3;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}switch(i.last=1&d,d>>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(yN(i),i.mode=hN,t===QO){d>>>=2,l-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=_N}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if((65535&d)!=(d>>>16^65535)){e.msg="invalid stored block lengths",i.mode=_N;break}if(i.length=65535&d,d=0,l=0,i.mode=lN,t===QO)break e;case lN:i.mode=16195;case 16195:if(p=i.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(n.subarray(s,s+p),o),a-=p,s+=p,c-=p,o+=p,i.length-=p;break}i.mode=cN;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(i.nlen=257+(31&d),d>>>=5,l-=5,i.ndist=1+(31&d),d>>>=5,l-=5,i.ncode=4+(15&d),d>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=_N;break}i.have=0,i.mode=16197;case 16197:for(;i.have<i.ncode;){for(;l<3;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.lens[w[i.have++]]=7&d,d>>>=3,l-=3}for(;i.have<19;)i.lens[w[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,A={bits:i.lenbits},v=JO(0,i.lens,0,19,i.lencode,0,i.work,A),i.lenbits=A.bits,v){e.msg="invalid code lengths set",i.mode=_N;break}i.have=0,i.mode=16198;case 16198:for(;i.have<i.nlen+i.ndist;){for(;I=i.lencode[d&(1<<i.lenbits)-1],m=I>>>24,f=I>>>16&255,g=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(g<16)d>>>=m,l-=m,i.lens[i.have++]=g;else{if(16===g){for(b=m+2;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(d>>>=m,l-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=_N;break}C=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2}else if(17===g){for(b=m+3;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}d>>>=m,l-=m,C=0,p=3+(7&d),d>>>=3,l-=3}else{for(b=m+7;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}d>>>=m,l-=m,C=0,p=11+(127&d),d>>>=7,l-=7}if(i.have+p>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=_N;break}for(;p--;)i.lens[i.have++]=C}}if(i.mode===_N)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=_N;break}if(i.lenbits=9,A={bits:i.lenbits},v=JO(1,i.lens,0,i.nlen,i.lencode,0,i.work,A),i.lenbits=A.bits,v){e.msg="invalid literal/lengths set",i.mode=_N;break}if(i.distbits=6,i.distcode=i.distdyn,A={bits:i.distbits},v=JO(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,A),i.distbits=A.bits,v){e.msg="invalid distances set",i.mode=_N;break}if(i.mode=hN,t===QO)break e;case hN:i.mode=uN;case uN:if(a>=6&&c>=258){e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,GO(e,u),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,i.mode===cN&&(i.back=-1);break}for(i.back=0;I=i.lencode[d&(1<<i.lenbits)-1],m=I>>>24,f=I>>>16&255,g=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(f&&0==(240&f)){for(S=m,T=f,R=g;I=i.lencode[R+((d&(1<<S+T)-1)>>S)],m=I>>>24,f=I>>>16&255,g=65535&I,!(S+m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}d>>>=S,l-=S,i.back+=S}if(d>>>=m,l-=m,i.back+=m,i.length=g,0===f){i.mode=16205;break}if(32&f){i.back=-1,i.mode=cN;break}if(64&f){e.msg="invalid literal/length code",i.mode=_N;break}i.extra=15&f,i.mode=16201;case 16201:if(i.extra){for(b=i.extra;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.length+=d&(1<<i.extra)-1,d>>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;I=i.distcode[d&(1<<i.distbits)-1],m=I>>>24,f=I>>>16&255,g=65535&I,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(0==(240&f)){for(S=m,T=f,R=g;I=i.distcode[R+((d&(1<<S+T)-1)>>S)],m=I>>>24,f=I>>>16&255,g=65535&I,!(S+m<=l);){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}d>>>=S,l-=S,i.back+=S}if(d>>>=m,l-=m,i.back+=m,64&f){e.msg="invalid distance code",i.mode=_N;break}i.offset=g,i.extra=15&f,i.mode=16203;case 16203:if(i.extra){for(b=i.extra;l<b;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}i.offset+=d&(1<<i.extra)-1,d>>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=_N;break}i.mode=16204;case 16204:if(0===c)break e;if(p=u-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=_N;break}p>i.wnext?(p-=i.wnext,_=i.wsize-p):_=i.wnext-p,p>i.length&&(p=i.length),E=i.window}else E=r,_=o-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do{r[o++]=E[_++]}while(--p);0===i.length&&(i.mode=uN);break;case 16205:if(0===c)break e;r[o++]=i.length,c--,i.mode=uN;break;case pN:if(i.wrap){for(;l<32;){if(0===a)break e;a--,d|=n[s++]<<l,l+=8}if(u-=c,e.total_out+=u,i.total+=u,4&i.wrap&&u&&(e.adler=i.check=i.flags?Ew(i.check,r,u,o-u):pw(i.check,r,u,o-u)),u=c,4&i.wrap&&(i.flags?d:EN(d))!==i.check){e.msg="incorrect data check",i.mode=_N;break}d=0,l=0}i.mode=16207;case 16207:if(i.wrap&&i.flags){for(;l<32;){if(0===a)break e;a--,d+=n[s++]<<l,l+=8}if(4&i.wrap&&d!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=_N;break}d=0,l=0}i.mode=16208;case 16208:v=$O;break e;case _N:v=iN;break e;case 16210:return nN;default:return tN}return e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,(i.wsize||u!==e.avail_out&&i.mode<_N&&(i.mode<pN||t!==zO))&&AN(e,e.output,e.next_out,u-e.avail_out),h-=e.avail_in,u-=e.avail_out,e.total_in+=h,e.total_out+=u,i.total+=u,4&i.wrap&&u&&(e.adler=i.check=i.flags?Ew(i.check,r,u,e.next_out-u):pw(i.check,r,u,e.next_out-u)),e.data_type=i.bits+(i.last?64:0)+(i.mode===cN?128:0)+(i.mode===hN||i.mode===lN?256:0),(0===h&&0===u||t===zO)&&v===ZO&&(v=rN),v},wN={inflateReset:SN,inflateReset2:TN,inflateResetKeep:gN,inflateInit:e=>RN(e,15),inflateInit2:RN,inflate:bN,inflateEnd:e=>{if(fN(e))return tN;let t=e.state;return t.window&&(t.window=null),e.state=null,ZO},inflateGetHeader:(e,t)=>{if(fN(e))return tN;const i=e.state;return 0==(2&i.wrap)?tN:(i.head=t,t.done=!1,ZO)},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,s;return fN(e)?tN:(n=e.state,0!==n.wrap&&n.mode!==aN?tN:n.mode===aN&&(r=1,r=pw(r,t,i,0),r!==n.check)?iN:(s=AN(e,t,i,i),s?(n.mode=16210,nN):(n.havedict=1,ZO)))},inflateInfo:"pako inflate (from Nodeca project)"},ON=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const NN=Object.prototype.toString,{Z_NO_FLUSH:DN,Z_FINISH:PN,Z_OK:LN,Z_STREAM_END:kN,Z_NEED_DICT:MN,Z_STREAM_ERROR:UN,Z_DATA_ERROR:xN,Z_MEM_ERROR:VN}=fw;function FN(e){this.options=vO.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new bO,this.strm.avail_out=0;let i=wN.inflateInit2(this.strm,t.windowBits);if(i!==LN)throw new Error(mw[i]);if(this.header=new ON,wN.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=AO.string2buf(t.dictionary):"[object ArrayBuffer]"===NN.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=wN.inflateSetDictionary(this.strm,t.dictionary),i!==LN)))throw new Error(mw[i])}function BN(e,t){const i=new FN(t);if(i.push(e),i.err)throw i.msg||mw[i.err];return i.result}FN.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let s,o,a;if(this.ended)return!1;for(o=t===~~t?t:!0===t?PN:DN,"[object ArrayBuffer]"===NN.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),s=wN.inflate(i,o),s===MN&&r&&(s=wN.inflateSetDictionary(i,r),s===LN?s=wN.inflate(i,o):s===xN&&(s=MN));i.avail_in>0&&s===kN&&i.state.wrap>0&&0!==e[i.next_in];)wN.inflateReset(i),s=wN.inflate(i,o);switch(s){case UN:case xN:case MN:case VN:return this.onEnd(s),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||s===kN))if("string"===this.options.to){let e=AO.utf8border(i.output,i.next_out),t=i.next_out-e,r=AO.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(s!==LN||0!==a){if(s===kN)return s=wN.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},FN.prototype.onData=function(e){this.chunks.push(e)},FN.prototype.onEnd=function(e){e===LN&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=vO.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var jN={Inflate:FN,inflate:BN,inflateRaw:function(e,t){return(t=t||{}).raw=!0,BN(e,t)},ungzip:BN,constants:fw};const{Deflate:GN,deflate:WN,deflateRaw:HN,gzip:KN}=BO,{Inflate:YN,inflate:qN,inflateRaw:JN,ungzip:zN}=jN;var XN,QN=WN,ZN=qN;!function(e){e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE"}(XN||(XN={}));class $N{constructor(){nu(this,"_sequence",0),nu(this,"_startTime",Date.now()),nu(this,"isUseOneByte",!0)}get startTime(){const e=Date.now()-this._startTime;return e<Math.pow(2,16)?e:(this._startTime+=Math.pow(2,16),this.startTime)}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence)}serialize(e){const t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){const i=new Uint8Array(4);i.set([1,0,0,0]);const n={id:0,length:4,data:i.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[n]};t.commonPacketHeader.extension=1,t.extension=r,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;const i=new ArrayBuffer(t.commonPacketHeader.length),n=new Uint8Array(i),r=new DataView(i);let s=0;if(r.setUint16(s,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),s+=2,r.setUint32(s,t.commonPacketHeader.sequence,!0),s+=4,r.setUint16(s,t.commonStreamHeader,!0),s+=2,t.extension){const e=this.serializeExtension(t.extension);n.set(new Uint8Array(e),s),s+=e.byteLength}if(n.set(new Uint8Array(t.payload),s),s+=t.payload.byteLength,s!==t.commonPacketHeader.length)throw Error("serialize error!");return i}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let i=0;const n=t.getUint16(i,!0);i+=2;const r=(32768&n)>>15;let s,o;if(t.getUint16(i+2,!0),t.getUint16(i,!0),i+=4,t.getUint16(i,!0),i+=2,r){o=this.deserializeExtension(e.slice(i)),i+=2+o.length,s=e.slice(i);let t=!1;if(o.datas.length>0){const e=o.datas.find((e=>0===e.id));e&&(t=1==(1&new DataView(e.data).getUint32(0,!0)))}s=t?this.decompress(s):s}else s=e.slice(8);return s}serializeExtension(e){const{profile:t,length:i,datas:n}=e,r=new ArrayBuffer(i+2),s=new Uint8Array(r),o=new DataView(r);let a=0;if(o.setUint8(a++,t),o.setUint8(a++,i),n.forEach((e=>{t?(o.setUint8(a++,e.id),o.setUint8(a++,e.length),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(o.setUint8(a++,e.id|e.length<<4),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength)})),a!==i+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(i+2));return r}deserializeExtension(e){const t=new DataView(e);let i=0;const n=t.getUint8(i);i++;const r=t.getUint8(i);i++;const s=n===XN.TWO_BYTE,o=[],a=new DataView(e,2);let c=0;for(;c<r;){let e=0,t=0,i=new ArrayBuffer(0);s?(e=a.getUint8(c),c++,t=a.getUint8(c),c++):(e=15&a.getUint8(c),t=a.getUint8(c)>>4,c++),t>0&&(i=a.buffer.slice(c+2,c+2+t),c+=i.byteLength),o.push({id:e,length:t,data:i})}if(c!==r)throw Error("parse error");return{profile:n,length:r,datas:o}}decompress(e){return ZN(new Uint8Array(e))}compress(e){return QN(new Uint8Array(e))}}class eD extends iS{constructor(e,t){super(),nu(this,"_version",1),nu(this,"_type",3),nu(this,"_config",void 0),nu(this,"_originDataChannel",void 0),nu(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),nu(this,"_dataStreamPacketHandler",void 0),nu(this,"_datachannelEventMap",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader(),this._dataStreamPacketHandler=new $N}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return kC("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting"}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new tg(((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout((()=>{var e;t(new Vg(xg.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new Vg(xg.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new Vg(xg.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[Qy.OPEN,Qy.CLOSE,Qy.ERROR].forEach((t=>{const i=()=>{this.emit(t)};this._datachannelEventMap.set(t,i),e.addEventListener(t,i)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let[i,n]=t;e.removeEventListener(i,n)})),this._datachannelEventMap.clear()}}class tD extends eD{constructor(e){super(e),nu(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const t=e.data.slice(0,this._dataStreamPacketHeader.byteLength);if(new DataView(t).getUint8(3)!==this.id)return;let i=e.data.slice(this._dataStreamPacketHeader.byteLength);i=this._dataStreamPacketHandler.deserialize(i),this.emit(Qy.MESSAGE,i)}}_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents()}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close())}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener)}}class iD extends eD{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const i=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);i.set(new Uint8Array(this._dataStreamPacketHeader),0),i.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(i.buffer)}}}class nD extends iS{constructor(){super(...arguments),nu(this,"resultStorage",new Map)}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i))}setRemoteAudioStats(e,t){const i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const i=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",i,this.checkVideoDecode(t))}record(e,t,i){if(kC("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(n&&(n.result.push(i),n.result.length>=5)){var r;const i=Lr(r=n.result).call(r,!0);n.isPrevNormal&&!i&&this.emit("exception",rD[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",rD[e]+2e3,e+"_RECOVER",t),n.isPrevNormal=i,n.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof ZA&&!t.isActive||!!t.muted||0!==e.sendVolumeLevel}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=pD(t._encoderConfig.frameRate));const n=e.captureFrameRate;return!i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof ZA&&!t.isActive||!!t.muted||0!==e.sendBitrate}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const rD={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003},sD=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t))}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t))}measureFromSubscribeStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function oD(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function aD(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?oD(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):oD(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class cD{constructor(e){nu(this,"store",void 0),nu(this,"onStatsException",void 0),nu(this,"onUploadPublishDuration",void 0),nu(this,"onStatsChanged",void 0),nu(this,"localStats",new Map),nu(this,"remoteStats",new Map),nu(this,"updateStatsInterval",void 0),nu(this,"trafficStats",void 0),nu(this,"trafficStatsPeerList",[]),nu(this,"uplinkStats",void 0),nu(this,"exceptionMonitor",void 0),nu(this,"p2pChannel",void 0),nu(this,"scalabilityMode",cv.L1T1),nu(this,"updateStats",(()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.updateStatsInterval=window.setInterval(this.updateStats,1e3),this.exceptionMonitor=new nD,this.exceptionMonitor.on("exception",((e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i)}))}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(uI.LocalAudioTrack)||aD({},By)}getLocalVideoTrackStats(){return this.localStats.get(uI.LocalVideoTrack)||aD({},jy)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{audioStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n)}else Array.from(this.remoteStats.entries()).forEach((e=>{let[i,{networkStats:n}]=e;n&&(t[i]=n)}));return t}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let[n,{videoStats:r}]=e;r&&(i[n]=t(n,r))}));return i}getRTCStats(){let e=0,t=0,i=0,n=0;const r=this.localStats.get(uI.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const s=this.localStats.get(uI.LocalVideoTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate);const o=this.localStats.get(uI.LocalVideoLowTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate),this.remoteStats.forEach((e=>{let{audioStats:t,videoStats:r}=e;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),r&&(i+=r.receiveBytes,n+=r.receiveBitrate)}));let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd)),e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?sD.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?sD.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,n>r?n:r),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&WC.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,i){if(!e)return!1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,r=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!r}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let[i,n]=t;switch(i){case uI.LocalVideoTrack:case uI.LocalVideoLowTrack:{const t=n,s=aD({},jy),o=e.getStats(),a=e.getLocalMedia(i);if(o){const i=o.videoSend.find((e=>e.ssrc===(null==a?void 0:a.ssrcs[0].ssrcId)));if(i){const n=e.getLocalVideoSize(),r=e.getEncoderConfig(uI.LocalVideoTrack);"H264"!==i.codec&&"H265"!==i.codec&&"VP8"!==i.codec&&"VP9"!==i.codec&&"AV1X"!==i.codec&&"AV1"!==i.codec||(s.codecType=i.codec),s.sendBytes=i.bytes,s.sendBitrate=t?8*Math.max(0,s.sendBytes-t.sendBytes):0,i.inputFrame?(s.captureFrameRate=i.inputFrame.frameRate,s.captureResolutionHeight=i.inputFrame.height,s.captureResolutionWidth=i.inputFrame.width):n&&(s.captureResolutionWidth=n.width,s.captureResolutionHeight=n.height),i.sentFrame?(s.sendFrameRate=i.sentFrame.frameRate,s.sendResolutionHeight=i.sentFrame.height,s.sendResolutionWidth=i.sentFrame.width):n&&(s.sendResolutionWidth=n.width,s.sendResolutionHeight=n.height),i.avgEncodeMs&&(s.encodeDelay=i.avgEncodeMs),r&&r.bitrateMax&&(s.targetSendBitrate=1e3*r.bitrateMax),s.sendPackets=i.packets,s.sendPacketsLost=i.packetsLost,s.sendJitterMs=i.jitterMs,s.sendRttMs=i.rttMs,s.totalDuration=t?t.totalDuration+1:1,s.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(s.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(WC.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(s.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var r;this.localStats.set(i,s),((null==t?void 0:t.sendResolutionWidth)!==s.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==s.sendResolutionHeight)&&(null===(r=this.onStatsChanged)||void 0===r||r.call(this,"resolution",{width:s.sendResolutionWidth,height:s.sendResolutionHeight})),s&&a&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,a.track,s);break}case uI.LocalAudioTrack:{const t=n,r=aD({},By),s=e.getStats(),o=e.getLocalMedia(i);if(s){const i=s.audioSend.find((e=>e.ssrc===(null==o?void 0:o.ssrcs[0].ssrcId)));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(r.codecType=i.codec),i.inputLevel)r.sendVolumeLevel=Math.round(32767*i.inputLevel);else{const t=e.getLocalAudioVolume();t&&(r.sendVolumeLevel=Math.round(32767*t))}r.sendBytes=i.bytes,r.sendPackets=i.packets,r.sendPacketsLost=i.packetsLost,r.sendJitterMs=i.jitterMs,r.sendRttMs=i.rttMs,r.sendBitrate=t?8*Math.max(0,r.sendBytes-t.sendBytes):0}}this.trafficStats&&(r.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(uI.LocalAudioTrack,r),r&&o&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,o.track,r);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{let[i,{videoStats:n,audioStats:r,videoPcStats:s}]=t;const o=r,a=n,c=s,d=aD({},Gy),l=aD({},Hy),h=aD({},Wy),{audioTrack:u,videoTrack:p,audioSSRC:_,videoSSRC:E}=e.getRemoteMedia(i),m=e.getStats(),f=null==m?void 0:m.audioRecv.find((e=>e.ssrc===_)),g=null==m?void 0:m.videoRecv.find((e=>e.ssrc===E)),S=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===i));if(f&&("opus"!==f.codec&&"aac"!==f.codec&&"PCMU"!==f.codec&&"PCMA"!==f.codec&&"G722"!==f.codec||(d.codecType=f.codec),f.outputLevel?d.receiveLevel=Math.round(32767*f.outputLevel):u&&(d.receiveLevel=Math.round(32767*u.getVolumeLevel())),d.receiveBytes=f.bytes,d.receivePackets=f.packets,d.receivePacketsLost=f.packetsLost,d.packetLossRate=d.receivePacketsLost/(d.receivePackets+d.receivePacketsLost),d.receiveBitrate=o?8*Math.max(0,d.receiveBytes-o.receiveBytes):0,d.totalDuration=o?o.totalDuration+1:1,d.totalFreezeTime=o?o.totalFreezeTime:0,d.freezeRate=d.totalFreezeTime/d.totalDuration,d.receiveDelay=f.jitterBufferMs,d.totalDuration>10&&cD.isRemoteAudioFreeze(u)&&(d.totalFreezeTime+=1)),g){"H264"!==g.codec&&"H265"!==g.codec&&"VP8"!==g.codec&&"VP9"!==g.codec&&"AV1X"!==g.codec&&"AV1"!==g.codec||(l.codecType=g.codec),l.receiveBytes=g.bytes,l.receiveBitrate=a?8*Math.max(0,l.receiveBytes-a.receiveBytes):0,l.decodeFrameRate=g.decodeFrameRate<0?0:g.decodeFrameRate,l.renderFrameRate=g.decodeFrameRate<0?0:g.decodeFrameRate,g.outputFrame&&(l.renderFrameRate=g.outputFrame.frameRate),g.receivedFrame?(l.receiveFrameRate=g.receivedFrame.frameRate,l.receiveResolutionHeight=g.receivedFrame.height,l.receiveResolutionWidth=g.receivedFrame.width):p&&(l.receiveResolutionHeight=p._videoHeight||0,l.receiveResolutionWidth=p._videoWidth||0),void 0!==g.framesRateFirefox&&(l.receiveFrameRate=Math.round(g.framesRateFirefox)),l.receivePackets=g.packets,l.receivePacketsLost=g.packetsLost,l.packetLossRate=l.receivePacketsLost/(l.receivePackets+l.receivePacketsLost),l.totalDuration=a?a.totalDuration+1:1,l.totalFreezeTime=a?a.totalFreezeTime:0,l.receiveDelay=g.jitterBufferMs||0;const t=!!E&&e.getRemoteVideoIsReady(E);p&&t&&cD.isRemoteVideoFreeze(p,g,c)&&(l.totalFreezeTime+=1),l.freezeRate=l.totalFreezeTime/l.totalDuration}S&&(d.end2EndDelay=S.B_ad,l.end2EndDelay=S.B_vd,d.transportDelay=S.B_ed,l.transportDelay=S.B_ed,d.currentPacketLossRate=S.B_ealr4/100,l.currentPacketLossRate=S.B_evlr4/100,h.uplinkNetworkQuality=S.B_punq?S.B_punq:0,h.downlinkNetworkQuality=S.B_pdnq?S.B_pdnq:0),this.remoteStats.set(i,{audioStats:d,videoStats:l,videoPcStats:g,networkStats:h}),u&&this.exceptionMonitor.setRemoteAudioStats(u,d),p&&this.exceptionMonitor.setRemoteVideoStats(p,l)}))}}function dD(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function lD(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?dD(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):dD(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function hD(e){return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(kC("TURN_DOMAIN")):(WC.info("Cannot recognized as IP address ".concat(e,". Used As Host instead")),e)}function uD(e,t){var i,n;const r=kC("GATEWAY_DOMAINS");let s=r[1]&&-1!==t.indexOf(r[1])?1:0;e.addresses=e.addresses||[];const o=e.addresses.map((e=>e.domain_prefix?{address:"".concat(e.domain_prefix,".").concat(r[s++%r.length],":").concat(e.port)}:e.ip.match(/^[\.\:\d]+$/)?{ip:e.ip,port:e.port,address:"".concat(e.ip.replace(/[^\d]/g,"-"),".").concat(r[s++%r.length],":").concat(e.port)}:(WC.info("Cannot recognized as IP address ".concat(e.ip,". Used As Host instead")),{ip:e.ip,port:e.port,address:"".concat(e.ip,":").concat(e.port)})));if(null!==(i=e.detail)&&void 0!==i&&i[18]&&"string"==typeof(null===(n=e.detail)||void 0===n?void 0:n[18])){const t=e.detail[18],i=null==t?void 0:t.split(";");for(let e=0;e<i.length;e++){var a;const t=Ey(a=i[e]).call(a);o[e]&&t&&(o[e].ip6=t)}}return{gatewayAddrs:o,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]}}function pD(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function _D(e){const t=e._encoderConfig;if(!t)return{};const i={resolution:t.width&&t.height?"".concat(pD(t.width),"x").concat(pD(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return"number"==typeof t.frameRate?(i.maxFrameRate=t.frameRate,i.minFrameRate=t.frameRate):t.frameRate&&(i.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,i.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),i}function ED(e){const t={connectionType:0,googRtt:e.rtt};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t.connectionType=1),"tcp"===i&&(t.connectionType=3),"tls"===i&&(t.connectionType=4);break}case"srflx":t.connectionType=2}return t}function mD(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function fD(e,t){let i,n,r;switch(t){case dy.CHOOSE_SERVER:n=4096,r="choose server";break;case dy.CLOUD_PROXY:n=1048576,r="proxy";break;case dy.CLOUD_PROXY_5:n=4194304,r="proxy5";break;case dy.CLOUD_PROXY_FALLBACK:n=4194310,r="proxy fallback";break;default:throw new Mv(xg.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach((t=>{t.buffer&&t.buffer.flag===n&&(i={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map((e=>lD(lD({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:lD(lD({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})})),!i)throw new Mv(xg.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i}async function gD(e,t){return await tg.all(e.addresses.map((async e=>({address:hD(e.ip),tcpport:e.port,udpport:e.port,username:t&&kC("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():rv.username,password:t&&kC("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await tS(t.toString()):rv.password}))))}function SD(e,t){const i=t._videoHeight||t.getMediaStreamTrack(!0).getSettings().height;return i?Math.max(i/pD(e.height),1):(WC.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function TD(e){let{candidateType:t,relayProtocol:i,type:n,address:r,port:s,protocol:o}=e;return"local-candidate"===n?{candidateType:t,relayProtocol:i,protocol:o}:{candidateType:t,relayProtocol:i,address:r,port:s,protocol:o}}function RD(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class CD extends iS{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Lr(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(TI.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(TI.CONNECTED):"closed"===this._state?this.emit(TI.CLOSED):"failed"===this._state&&this.emit(TI.FAILED))}constructor(e,t,i,n){super(),nu(this,"connectionID",0),nu(this,"currentURLIndex",0),nu(this,"reconnectReason",void 0),nu(this,"_reconnectMode","tryNext"),nu(this,"_name",void 0),nu(this,"_state","closed"),nu(this,"_retryConfig",void 0),nu(this,"_reconnectCount",0),nu(this,"_forceCloseTimeout",5e3),nu(this,"_onlineReconnectListener",void 0),nu(this,"_closeEstablishingTransmitter",(()=>{})),nu(this,"_store",void 0),nu(this,"_joinChannelServiceRecordIndex",void 0),nu(this,"_useCompress",void 0),nu(this,"_inflateLength",0),nu(this,"_deflateLength",0),this._store=n,this._name=e,this._retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?RD(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):RD(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t),this._useCompress=i}resetReconnectCount(e){WC.debug("".concat(this._name," reset reconnect count, reason: ").concat(e)),this._reconnectCount=0}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const e=this._transmitter;t?setTimeout((()=>e.close()),500):e.close(),this._transmitter=void 0}this.state=e?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(e,t){if(!this._transmitter)return void WC.warning("[".concat(this._name,"] can not reconnect, no websocket"));var i;void 0!==e&&(this.reconnectMode=e),WC.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex&&(null===(i=this._store)||void 0===i||i.recordJoinChannelService({status:"error",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const n=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),n&&n.bind(this._transmitter)({code:9999,reason:t})}getInflateData(){const e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t}}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}var vD;!function(e){e[e.Default=0]="Default",e[e.Ack=1]="Ack"}(vD||(vD={}));class ID{constructor(e,t,i){nu(this,"version",1),nu(this,"initialRTO",void 0),nu(this,"maxBatchAckCount",void 0),nu(this,"maxRTO",void 0),nu(this,"initialRTT",void 0),nu(this,"ID",void 0),nu(this,"rtt",void 0),nu(this,"packetNumber",1),nu(this,"rtoRatioMap",new Map),nu(this,"timeoutMap",new Map),nu(this,"unorderedPacketQueue",[]),nu(this,"batchAckPacketQueue",[]),nu(this,"lastOrderedPacketNumber",0),nu(this,"batchAckTimer",void 0),nu(this,"sendImpl",void 0),nu(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=xS(7,"transmitter-"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:kC("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:kC("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:kC("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:kC("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:kC("TRANSMITTER_MAX_RTO")}packetize(e,t){return{type:vD.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case vD.Default:{let t;t="string"==typeof e.payload?(new TextEncoder).encode(e.payload):e.payload;const i=new ArrayBuffer(t.length+15),n=new DataView(i);return n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.packetNumber),Jg(n,7,BigInt(e.sendTs)),new Uint8Array(n.buffer).set(t,15),i}case vD.Ack:{const t=new ArrayBuffer(16),i=new DataView(t);return i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.maxAckPacketNumber),i.setUint8(7,e.shift),Jg(i,8,BigInt(e.ackSendTs)),t}}}deserialize(e){const t=new DataView(e),i=t.getUint16(0),n=t.getUint8(2);switch(n){case vD.Default:{const r=t.getUint32(3),s=qg(t,7),o=e.slice(15),a=(new TextDecoder).decode(o);return{version:i,type:n,packetNumber:r,sendTs:Number(s),payload:a}}case vD.Ack:{const e=t.getUint32(3),r=t.getUint8(7),s=qg(t,8);return{version:i,type:n,maxAckPacketNumber:e,shift:r,ackSendTs:Number(s)}}default:throw WC.error("[".concat(this.ID,"] Unrecognized packet type ").concat(n)),new Error("Unrecognized packet type ".concat(n))}}sendMessage(e){const t=this.packetize(e,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const i=this.calculateRTO(t),n=window.setTimeout((()=>{this.resendMessage(t)}),i);this.timeoutMap.set(t.packetNumber,n),this.sendPacket(t)}onData(e){const t=this.deserialize(e);t.type===vD.Default?this.ack(t):t.type===vD.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach((e=>{let[t,i]=e;window.clearTimeout(i)})),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer)}resendMessage(e){const t=this.calculateRTO(e),i=window.setTimeout((()=>{this.resendMessage(e)}),t);this.timeoutMap.set(e.packetNumber,i),this.sendPacket(e)}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const i=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),i>this.maxRTO?this.maxRTO:i}}updateRTT(e,t){const i=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-i-this.rtt)/8}ack(e){if(e.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(e):(this.batchAckPacketQueue.push(e),this.batchAckTimer=window.setTimeout((()=>{this.batchAck()}),this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(e.payload);;){const e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(e.packetNumber<=this.lastOrderedPacketNumber){const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:vD.Ack,version:this.version};this.sendPacket(t)}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:vD.Ack,version:this.version};this.sendPacket(t)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:vD.Ack,version:this.version};this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===vD.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t)}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t)}}}class yD extends CD{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),nu(this,"_initMutex",void 0),nu(this,"_reconnectInterrupter",void 0),nu(this,"_url",void 0),nu(this,"_transmitter",void 0),nu(this,"_addresses",void 0),nu(this,"_reliableTransmission",void 0),this._initMutex=new YS("datachannel");const{timeout:i,timeoutFactor:n}=t,r=Math.max(300,Math.floor(3*i/5)),s=Math.max(1.2,Math.floor(8*n)/10);hS.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=s),RS.on(uS.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===hS.ONLINE?(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=s):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=n))}))}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;const i=(t,i)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex((e=>e.fingerprint||kC("FINGERPRINT")));const n=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(n).then(t).catch(i),this.once(TI.CLOSED,(()=>i(new Mv(xg.WS_DISCONNECT)))),this.once(TI.CONNECTED,(()=>t()))};return this._initMutex.lock().then((e=>new tg(((e,t)=>{i(e,t)})).then((()=>{e()})).catch((()=>{e()}))))}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new Mv(xg.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e)),this._reliableTransmission.sendMessage(e)}catch(e){throw new Mv(xg.WS_ERR,"send datachannel signal message error"+e.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(e){const t=JSON.stringify(e);return{compressed:t,compressedLength:t.length,origin:e}}sendMessageWithUint8Array(e){return{compressed:e,compressedLength:e.byteLength,origin:e}}createTransmitterConnection(e){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(e.ip,":").concat(e.port),new tg(((t,i)=>{var n;const r=()=>{WC.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),t()},s=async e=>{var n;if(null===(n=this._closeEstablishingTransmitter)||void 0===n||n.call(this),WC.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const n=SS(this,TI.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(n);if("closed"===this.state)return void WC.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!r)return i(new Mv(xg.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else i(new Mv(xg.WS_DISCONNECT,"datachannel close: ".concat(e.code))),this.close()},o=e=>{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data)};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),WC.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));const a=null===(n=this._store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();fS(this,TI.TO_CONNECT_DATACHANNEL,e).then((e=>{var t,i;if(!e)throw new Error("transmissonInfo not exist yet");const{transmitter:n,close:d}=e;this._transmitter=n,null===(t=this._store)||void 0===t||t.signalChannelOpen();const l=Date.now()-c;WC.debug("[choose dc] dc open cost ".concat(l,"ms")),this._reliableTransmission=new ID((e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e))}),(e=>{"string"==typeof e&&this.emit(TI.ON_MESSAGE,e)})),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d()},r&&r(),n.onclose=s,n.onmessage=o,null===(i=this._store)||void 0===i||i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this._joinChannelServiceRecordIndex=a})).catch((e=>{var t;if(null===(t=this._store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof Mv&&e.code===xg.WS_ABORT?"aborted":"error",errors:[e]},a),"closed"!==this.state){if(e instanceof Mv&&e.code===xg.WS_ERR){const t=new Mv(xg.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return WC.error("[".concat(this._name,"]").concat(t)),void i(t)}s&&s(e)}else i(new Mv(xg.WS_DISCONNECT,"datachannel is closed: ".concat(e.toString())))}))}))}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount)return!1;if(!this._addresses)return!1;if("closed"===this.state)return!1;this._onlineReconnectListener||RS.networkState!==hS.OFFLINE||(this._onlineReconnectListener=RS.onlineWaiter&&RS.onlineWaiter.then((()=>{this._onlineReconnectListener=void 0})));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},t){const t=zS(this._reconnectCount,this._retryConfig);WC.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await tg.race([US(t),this._onlineReconnectListener||new tg((()=>{}))])}if("closed"===this.state||!i)return!1;this._reconnectCount+=1;const n=async(e,t)=>{this.emit(TI.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];this.emit(TI.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||kC("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return WC.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);WC.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];this.emit(TI.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else"recover"===e&&(WC.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(TI.RECONNECT_WAITTING_FINISH,e),this.emit(TI.FAILBACK));return!0}catch(i){var r,s;return WC.error("[".concat(this._name,"] reconnect failed"),i.toString()),null!=i&&null!==(r=i.data)&&void 0!==r&&r.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&Lr(s=i.data.desc).call(s,"dynamic key expired")?(this.emit(TI.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class AD extends iS{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Ev.CONNECTED?this.emit(mv.WS_CONNECTED):e===Ev.RECONNECTING?this.emit(mv.WS_RECONNECTING,this._websocketReconnectReason):e===Ev.CLOSED&&this.emit(mv.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),nu(this,"_disconnectedReason",void 0),nu(this,"_websocketReconnectReason",void 0),nu(this,"_connectionState",Ev.CLOSED),nu(this,"reconnectToken",void 0),nu(this,"websocket",void 0),nu(this,"openConnectionTime",void 0),nu(this,"clientId",void 0),nu(this,"lastMsgTime",Date.now()),nu(this,"uploadCache",[]),nu(this,"uploadCacheInterval",void 0),nu(this,"rttRolling",new dT(5)),nu(this,"pingpongTimer",void 0),nu(this,"inflateDataTimer",void 0),nu(this,"pingpongTimeoutCount",0),nu(this,"joinResponse",void 0),nu(this,"multiIpOption",void 0),nu(this,"initError",void 0),nu(this,"spec",void 0),nu(this,"store",void 0),nu(this,"onWebsocketMessage",(e=>{if(e instanceof ArrayBuffer)return void this.emit(mv.ON_BINARY_DATA,e);const t=JSON.parse(e);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")&&(this.emit(t._type,t._message),t._type===Sv.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Sv.ON_USER_BANNED))switch(t._message.error_code){case 14:this.close(cS.UID_BANNED);break;case 15:this.close(cS.IP_BANNED);break;case 16:this.close(cS.CHANNEL_BANNED)}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new yD("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===Ev.CONNECTED&&this.reconnect("retry",SI.OFFLINE)}))}async request(e,t,i,n){const r=xS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new tg(((t,i)=>{if(this.connectionState===Ev.CONNECTED)return t();const n=()=>{this.off(mv.WS_CLOSED,r),t()},r=()=>{this.off(mv.WS_CONNECTED,n),i(new Mv(xg.WS_ABORT))};this.once(mv.WS_CONNECTED,n),this.once(mv.WS_CLOSED,r),e!==fv.PUBLISH&&e!==fv.SUBSCRIBE&&e!==fv.UNSUBSCRIBE&&e!==fv.UNPUBLISH&&e!==fv.CONTROL&&e!==fv.RESTART_ICE||this.once(mv.DISCONNECT_P2P,(()=>{i(new Mv(xg.DISCONNECT_P2P))})),e!==fv.PUBLISH&&e!==fv.RESTART_ICE||this.once(mv.ABORT_P2P_EXECUTION,(()=>{i(new Mv(xg.DISCONNECT_P2P))}))}));if(this.connectionState!==Ev.CONNECTING&&this.connectionState!==Ev.RECONNECTING||e===fv.JOIN||e===fv.REJOIN||await a(),e===fv.LEAVE&&(this.websocket.unbindDcCloseEventListener(),n=!0),this.websocket.sendMessage(s,!0,!1),n)return;const c=new tg(((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.emit(mv.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new Mv(xg.WS_ABORT,"type: ".concat(e))),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(mv.WS_CLOSED,c),this.once(mv.WS_RECONNECTING,c),US(kC("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==o||s||(WC.warning("dc request timeout, type: ".concat(e)),this.emit(mv.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===Ev.CLOSED||e===fv.LEAVE)throw new Mv(xg.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===fv.JOIN||e===fv.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),h=kI(l),u=new Mv(xg.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===h.action?d.message:(WC.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(h.desc,", action: ").concat(h.action)),l===_v.ERR_TOO_MANY_BROADCASTERS?e===fv.JOIN||e===fv.REJOIN?(this.initError=u,this.close(),u.throw()):u.throw():"failed"===h.action?u.throw():"quit"===h.action?(this.initError=u,this.close(),u.throw()):(l===_v.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,WC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",SI.MULTI_IP)):this.reconnect(h.action,SI.SERVER_ERROR),e===fv.JOIN||e===fv.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new tg((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=kC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==Ev.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),kC("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new tg(((i,n)=>{this.once(mv.WS_CONNECTED,(()=>i(this.joinResponse))),this.once(mv.WS_CLOSED,(()=>n(this.initError||new Mv(xg.WS_ABORT)))),this.connectionState=Ev.CONNECTING,this.websocket.init(e).catch(n),this.websocket.once(TI.FAILBACK,(()=>{void 0===this.openConnectionTime&&n(new Mv(xg.INIT_DATACHANNEL_TIMEOUT))})),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval((()=>{this.handleInflateData()}),2e4),setTimeout((()=>{t&&void 0===this.openConnectionTime&&(WC.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),n(new Mv(xg.INIT_DATACHANNEL_TIMEOUT)))}),kC("DC_JOIN_WITH_FAILBACK"))}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||cS.LEAVE,this.connectionState=Ev.CLOSED,WC.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===cS.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new yD("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(mv.ABORT_P2P_EXECUTION);const e=await fS(this,mv.DATACHANNEL_CONNECTING),t=await this.request(fv.JOIN,e);if(!t)return this.emit(mv.REPORT_JOIN_GATEWAY,xg.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(mv.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new Mv(xg.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=TS(this,mv.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(fv.REJOIN,e);return!!t&&(this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(Sv.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(Sv.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(Sv.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(Sv.MUTE_AUDIO,{uid:e.uid}):this.emit(Sv.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(Sv.MUTE_VIDEO,{uid:e.uid}):this.emit(Sv.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(Sv.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(Sv.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(Sv.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(Sv.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(Sv.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleNotification(e){WC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kI(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(cS.UID_BANNED),void this.close()):void this.reconnect(t.action,SI.SERVER_ERROR);WC.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=kC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(WC.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>kC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",SI.TIMEOUT):this.request(fv.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),kC("REPORT_STATS")&&this.send(fv.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleInflateData(){const{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(gv.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(TI.RECONNECT_WAITTING_FINISH,(e=>{this.emit(mv.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(TI.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(mv.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(TI.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(TI.CLOSED,(()=>{this.connectionState=Ev.CLOSED})),this.websocket.on(TI.FAILED,(()=>{this._disconnectedReason=cS.NETWORK_ERROR,this.connectionState=Ev.CLOSED})),this.websocket.on(TI.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Ev.CONNECTED?this.connectionState=Ev.RECONNECTING:this.connectionState=Ev.CONNECTING})),this.websocket.on(TI.WILL_RECONNECT,((e,t)=>{if(TS(this,mv.IS_P2P_DISCONNECTED)&&"retry"===e)return WC.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(mv.NEED_RENEW_SESSION),this.emit(mv.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(WC.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(mv.NEED_RENEW_SESSION),this.emit(mv.DISCONNECT_P2P)),t(e)})),this.websocket.on(TI.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{WC.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",SI.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(mv.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof Mv&&e.code===xg.UNEXPECTED_RESPONSE&&e.data.code===_v.ERR_NO_AUTHORIZED)return WC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",SI.SERVER_ERROR);WC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",SI.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(TI.REQUEST_NEW_URLS,((e,t)=>{fS(this,mv.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(TI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(Sv.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(TI.TO_CONNECT_DATACHANNEL,(async(e,t,i)=>fS(this,mv.DATACHANNEL_PRECONNECT,e).then(t).catch(i))),this.websocket.on(TI.FAILBACK,(()=>{void 0!==this.openConnectionTime&&this.emit(mv.DATACHANNEL_FAILBACK)}))}}class bD extends iS{constructor(e){super(),nu(this,"_signal",void 0),nu(this,"_sequence",0),nu(this,"_userMap",new Map),nu(this,"_encoder",new TextEncoder),this._signal=e}async send(e,t,i,n,r){var s,o,a;"string"!=typeof t&&(t=JSON.stringify(t)),n=null!==(s=n)&&void 0!==s?s:xS(6,""),r=null!==(o=r)&&void 0!==o?o:this._sequence++;const c={_id:n,_type:e,_seq:null!==(a=r)&&void 0!==a?a:this._sequence++,_message:t};if(kC("SHOW_P2P_LOG")&&WC.debug("send message",c),this.sendStreamMessage(JSON.stringify(c)),i)return;const d=new tg(((t,i)=>{const r=window.setTimeout((()=>{this.off("res-@".concat(n),s),WC.warning("[external-signal] request timeout, type: ".concat(e)),0===this._userMap.size?i(new Vg(xg.INVALID_REMOTE_USER)):i(new Vg(xg.TIMEOUT))}),kC("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),s=(e,n)=>{r&&window.clearTimeout(r),"success"===e?t({isSuccess:!0,message:n}):i(new Vg(xg.UNEXPECTED_ERROR,n))};this.once("res-@".concat(n),s)}));let l;try{l=await d}catch(i){if(i.code===xg.TIMEOUT)return await this.send(e,t,!1,n,r);throw i}return l.isSuccess?l.message:void 0}sendStreamMessage(e){this._splitMessage(e).forEach((e=>{this._signal.request(fv.DATA_STREAM,{payload:PS(this._encoder.encode(e))})}))}onMessage(e){const{_uid:t}=e;let i;const n=this._userMap.get(t);if(n?i=n.splitMessageMap:(i=new Map,this._userMap.set(t,{isStart:!1,splitMessageMap:i,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map})),"id"in e&&"total"in e){var r;const{id:n,total:s}=e,o=null!==(r=i.get(n))&&void 0!==r?r:[];if(o.push(e),i.has(n)||i.set(n,o),o.length!==s)return;{const r=Zu(o).call(o,((e,t)=>e.index-t.index)).map((e=>e.payload)).join("");i.delete(n),(e=JSON.parse(r))._uid=t}}this.handleReceivedMessage(e)}setStart(e){this._userMap.has(e)?this._userMap.get(e).isStart=!0:this._userMap.set(e,{isStart:!0,splitMessageMap:new Map,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map}),this.handleReceivedMessage()}setEnd(e){return this._userMap.delete(e),0===this._userMap.size}ack(e,t,i){this.send(AI.ACK,JSON.stringify({success:!i,message:t}),!0,e)}handleReceivedMessage(e){const t=()=>{this._userMap.forEach((e=>{const{receivedMessagesMap:t,nextExpectedSequenceNumber:i}=e;for(;t.has(i);){const n=t.get(i);t.delete(i),this.receiveMessage(n),e.nextExpectedSequenceNumber++}}))};if(!e)return void t();const{_uid:i,_seq:n}=e,r=this._userMap.get(i),{receivedMessagesMap:s,isStart:o,nextExpectedSequenceNumber:a}=r;n<a?WC.debug("[external-signal] receive old message, seq: ".concat(n)):(s.set(n,e),o&&n===a&&(this.receiveMessage(e),s.delete(a),r.nextExpectedSequenceNumber++,t()))}receiveMessage(e){const{_id:t,_type:i,_message:n,_uid:r}=e;if(kC("SHOW_P2P_LOG")&&WC.debug("收到消息",e),t)switch(e._type){case AI.PUBLISH:const s=JSON.parse(n);this._signal.emit(i,s,r),this.ack(e._id);break;case AI.CONTROL:case AI.UNPUBLISH:case AI.DO_SUBSCRIBE:case AI.DO_UNSUBSCRIBE:{const t=JSON.parse(n);t.uid=r,fS(this._signal,i,t).then((t=>{this.ack(e._id,t)})).catch((t=>{this.ack(e._id,void 0,!0)}));break}case AI.ACK:{const{success:e,message:i}=JSON.parse(n);this.emit("res-@".concat(t),e?"success":"failed",i);break}case AI.CALL:fS(this,i,n).then((e=>{this.ack(t,e)}));break;case AI.RESTART_ICE:case AI.EXCHANGE_SDP:case AI.SUBSCRIBE:case AI.UNSUBSCRIBE:fS(this._signal,i,n).then((e=>{this.ack(t,e)})).catch((t=>{this.ack(e._id,void 0,!0)}));break;case AI.CANDIDATE:this._signal.emit(i,n),this.ack(t);break;case AI.JOIN:this.emit(i,JSON.parse(n));break;default:this.emit(i,n),this.ack(t)}}_splitMessage(e){if(e.length<bD.MAX_MESSAGE_SIZE)return[e];const t=[],i=xS(6,"");let n=0;const r=Math.ceil(e.length/800);for(;e.length>0;){n++;const s=e.slice(0,800);t.push({id:i,index:n,total:r,payload:s}),e=e.slice(800)}return t.map((e=>JSON.stringify(e)))}clear(){this._sequence=0,this._userMap.clear()}}nu(bD,"MAX_MESSAGE_SIZE",1024);class wD extends iS{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Ev.CONNECTED?this.emit(mv.WS_CONNECTED):e===Ev.RECONNECTING?this.emit(mv.WS_RECONNECTING,this._websocketReconnectReason):e===Ev.CLOSED&&this.emit(mv.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),nu(this,"_disconnectedReason",void 0),nu(this,"_websocketReconnectReason",void 0),nu(this,"_connectionState",Ev.CLOSED),nu(this,"reconnectToken",void 0),nu(this,"_userInRoom",!1),nu(this,"_userOnlineTime",void 0),nu(this,"websocket",void 0),nu(this,"openConnectionTime",void 0),nu(this,"clientId",void 0),nu(this,"lastMsgTime",Date.now()),nu(this,"uploadCache",[]),nu(this,"uploadCacheInterval",void 0),nu(this,"rttRolling",new dT(5)),nu(this,"pingpongTimer",void 0),nu(this,"wsInflateDataTimer",void 0),nu(this,"pingpongTimeoutCount",0),nu(this,"joinResponse",void 0),nu(this,"multiIpOption",void 0),nu(this,"initError",void 0),nu(this,"spec",void 0),nu(this,"store",void 0),nu(this,"_external_signal",void 0),nu(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(mv.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){switch(t._type){case Sv.ON_DATA_STREAM:return void this.handleDataStream(t._message);case Sv.MUTE_AUDIO:case Sv.MUTE_VIDEO:case Sv.ON_P2P_LOST:return;case Sv.ON_USER_ONLINE:this.emit(t._type,t._message);const{uid:e}=t._message;return this._external_signal.setStart(e),void this._external_signal.send(AI.JOIN,{onlineTime:this._userOnlineTime},!0)}if(this.emit(t._type,t._message),t._type===Sv.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Sv.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(cS.UID_BANNED);break;case 15:this.close(cS.IP_BANNED);break;case 16:this.close(cS.CHANNEL_BANNED)}if(t._type===Sv.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case _v.ERR_LICENSE_MISSING:this.close(cS.LICENSE_MISSING);break;case _v.ERR_LICENSE_EXPIRED:this.close(cS.LICENSE_EXPIRED);break;case _v.ERR_LICENSE_MINUTES_EXCEEDED:this.close(cS.LICENSE_MINUTES_EXCEEDED);break;case _v.ERR_LICENSE_PERIOD_INVALID:this.close(cS.LICENSE_PERIOD_INVALID);break;case _v.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(cS.LICENSE_MULTIPLE_SDK_SERVICE);break;case _v.ERR_LICENSE_ILLEGAL:this.close(cS.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new qI("gateway-".concat(this.clientId),this.spec.retryConfig,!0,kC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),kC("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===Ev.CONNECTED&&this.reconnect("retry",lS.OFFLINE)})),this._external_signal=new bD(this),this._handleSignalP2PEvents()}async request(e,t,i,n){const r=xS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new tg(((t,i)=>{if(this.connectionState===Ev.CONNECTED)return t();const n=()=>{this.off(mv.WS_CLOSED,r),t()},r=()=>{this.off(mv.WS_CONNECTED,n),i(new Vg(xg.WS_ABORT))};this.once(mv.WS_CONNECTED,n),this.once(mv.WS_CLOSED,r),e!==fv.PUBLISH&&e!==fv.SUBSCRIBE&&e!==fv.UNSUBSCRIBE&&e!==fv.UNPUBLISH&&e!==fv.CONTROL&&e!==fv.RESTART_ICE||this.once(mv.DISCONNECT_P2P,(()=>{i(new Vg(xg.DISCONNECT_P2P))})),e!==fv.PUBLISH&&e!==fv.RESTART_ICE||this.once(mv.ABORT_P2P_EXECUTION,(()=>{i(new Vg(xg.DISCONNECT_P2P))}))}));if(this.connectionState!==Ev.CONNECTING&&this.connectionState!==Ev.RECONNECTING||e===fv.JOIN||e===fv.REJOIN||await a(),this.websocket.sendMessage(s,!0),n)return;const c=new tg(((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.emit(mv.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new Vg(xg.WS_ABORT,"type: ".concat(e))),this.off(mv.WS_CLOSED,c),this.off(mv.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(mv.WS_CLOSED,c),this.once(mv.WS_RECONNECTING,c),US(kC("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==o||s||(WC.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(mv.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(n){if(this.connectionState===Ev.CLOSED||e===fv.LEAVE)throw new Vg(xg.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===fv.JOIN||e===fv.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),h=kI(l),u=new Vg(xg.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===h.action?d.message:(WC.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(h.desc,", action: ").concat(h.action)),l===_v.ERR_TOO_MANY_BROADCASTERS?e===fv.JOIN||e===fv.REJOIN?(this.initError=u,this.close(),u.throw()):u.throw():"failed"===h.action?u.throw():"quit"===h.action?(this.initError=u,this.close(),u.throw()):(l===_v.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,WC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",lS.MULTI_IP)):this.reconnect(h.action,lS.SERVER_ERROR),e===fv.JOIN||e===fv.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new tg((i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)}))}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=kC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==Ev.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),kC("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}async sendExtensionMessage(e,t,i){return await this.waitTillUserOnline(),await this._external_signal.send(e,t,i)}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new tg(((t,i)=>{this.once(mv.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(mv.WS_CLOSED,(()=>i(this.initError||new Vg(xg.WS_ABORT)))),this.connectionState=Ev.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||cS.LEAVE,this.connectionState=Ev.CLOSED,WC.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===cS.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new qI("gateway-".concat(this.clientId),this.spec.retryConfig,!0,kC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),kC("JOIN_GATEWAY_USE_443PORT_ONLY"),this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(mv.ABORT_P2P_EXECUTION);const e=await fS(this,mv.REQUEST_JOIN_INFO),t=await this.request(fv.JOIN,e);if(!t)return this.emit(mv.REPORT_JOIN_GATEWAY,xg.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(mv.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),this._userOnlineTime=(new Date).getTime(),this._external_signal.clear(),!0}async rejoin(){if(!this.reconnectToken)throw new Vg(xg.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=TS(this,mv.REQUEST_REJOIN_INFO);return e.token=this.reconnectToken,!!await this.request(fv.REJOIN,e)&&(this.connectionState=Ev.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}handleDataStream(e){try{var t;const i=DS(e.payload),n=(new TextDecoder).decode(i),r=JSON.parse(n);"total"in r&&"id"in r||Lr(t=Object.values(AI)).call(t,r._type)?(e.seq&&delete e.seq,r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(Sv.ON_DATA_STREAM,e)}catch(e){}}handleNotification(e){WC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kI(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(cS.UID_BANNED),void this.close()):void this.reconnect(t.action,lS.SERVER_ERROR);WC.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=kC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(WC.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>kC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",lS.TIMEOUT):this.request(fv.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),kC("REPORT_STATS")&&this.send(fv.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(gv.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(Cv.RECONNECT_WAITTING_FINISH,(e=>{this.emit(mv.WS_RECONNECT_WAITTING_FINISH,e)})),this.websocket.on(Cv.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(mv.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(Cv.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Cv.CLOSED,(()=>{this.connectionState=Ev.CLOSED})),this.websocket.on(Cv.FAILED,(()=>{this._disconnectedReason=cS.NETWORK_ERROR,this.connectionState=Ev.CLOSED})),this.websocket.on(Cv.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Ev.CONNECTED?this.connectionState=Ev.RECONNECTING:this.connectionState=Ev.CONNECTING})),this.websocket.on(Cv.WILL_RECONNECT,((e,t,i)=>{if(TS(this,mv.IS_P2P_DISCONNECTED)&&"retry"===e)return WC.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(mv.NEED_RENEW_SESSION),this.emit(mv.DISCONNECT_P2P),i("tryNext");"retry"!==e&&(WC.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(mv.NEED_RENEW_SESSION),this.emit(mv.DISCONNECT_P2P)),i(e)})),this.websocket.on(Cv.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{WC.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",lS.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(mv.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof Vg&&e.code===xg.UNEXPECTED_RESPONSE&&e.data.code===_v.ERR_NO_AUTHORIZED)return WC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",lS.SERVER_ERROR);WC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",lS.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(Cv.REQUEST_NEW_URLS,((e,t)=>{fS(this,mv.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(Cv.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(Sv.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}_handleSignalP2PEvents(){this._external_signal.on(AI.JOIN,(async e=>{if(this._userOnlineTime&&this._userOnlineTime<e.onlineTime){const e=await fS(this,mv.P2P_START,void 0),t=await this._external_signal.send(AI.CALL,e);this.emit(mv.P2P_CONNECTION,t,!0)}this._userInRoom=!0,this.emit("user-online")})),this.on(Sv.ON_USER_OFFLINE,(async e=>{this._external_signal.clear(),this._userInRoom=!1})),this._external_signal.on(AI.CALL,(async(e,t,i)=>{this._userInRoom=!0,this.emit("user-online");try{t(await fS(this,mv.P2P_START,e))}catch(e){i(e)}}))}async waitTillUserOnline(){return new tg((e=>{if(this._userInRoom)e();else{const t=()=>{this.off("user-online",t),e()};this.on("user-online",t)}}))}}function OD(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function ND(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?OD(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):OD(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const DD=new Map;class PD extends iS{get state(){return this._state}set state(e){if(e===this._state)return;const t=this._state;this._state=e,"DISCONNECTED"===e&&this._disconnectedReason?this.emit(Zv.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(Zv.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){WC.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){super(),nu(this,"store",void 0),nu(this,"joinInfo",void 0),nu(this,"key",void 0),nu(this,"ntpOffset",0),nu(this,"signal",void 0),nu(this,"role",void 0),nu(this,"inChannelInfo",{joinAt:null,duration:0}),nu(this,"spec",void 0),nu(this,"_state","DISCONNECTED"),nu(this,"_statsCollector",void 0),nu(this,"_disconnectedReason",void 0),nu(this,"isSignalRecover",!1),nu(this,"hasChangeBGPAddress",!1),nu(this,"trafficStatsInterval",void 0),nu(this,"networkQualityInterval",void 0),nu(this,"_joinGatewayStartTime",0),nu(this,"_signalTimeout",!1),nu(this,"_clientRoleOptions",void 0),nu(this,"_isProactiveJoin",!1),this.store=e,this.spec=t,this.signal=this.store.useP2P?new wD(ND(ND({},t),{},{retryConfig:t.websocketRetryConfig}),e):this.store.useDataChannel?new AD(ND(ND({},t),{},{retryConfig:t.websocketRetryConfig}),e):new zI(ND(ND({},t),{},{retryConfig:t.websocketRetryConfig}),e),this._statsCollector=t.statsCollector,this.role=t.role||"audience",this._clientRoleOptions=t.clientRoleOptions,this.handleSignalEvents()}async join(e,t,i){if(this.signal instanceof AD){let t=!1;"disabled"!==e.cloudProxyServer?(WC.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(e.cloudProxyServer,")")),t=!0):"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length>255||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length<22?(WC.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),t=!0):e.apResponse.addresses.some((e=>e.fingerprint))||kC("FINGERPRINT")||(WC.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0),t&&this.resetSignal()}this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const n=Date.now();let r=DD.get(e.cname);if(r||(r=new Map,DD.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new Mv(xg.UID_CONFLICT);throw iv.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!e.proxyServer,signalChannel:this.signal instanceof AD?"1":"0"}),this._isProactiveJoin=!1,t}r.set(e.uid,!0),this.joinInfo=e,this.key=t;let s=0;this.joinGatewayStartTime=n;const o=e.proxyServer;try{let t;if(WC.debug("[".concat(this.store.clientId,"] use ").concat(this.signal instanceof AD?"datachannel":"websocket"," join uid ").concat(s)),this.signal instanceof AD)t=await this.signal.init(e.apResponse.addresses,i);else{const n=e.gatewayAddrs.map((t=>{let{address:i}=t;const[n,r]=i.split(":"),s={host:n,port:r};return e.proxyServer&&(s.proxy=e.proxyServer),s}));t=await this.signal.init(n,i)}s=t.uid,WC.debug("[".concat(this.store.clientId,"] ").concat(this.signal instanceof AD?"datachannel":"websocket"," join uid ").concat(s," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){if(t&&t.code===xg.INIT_WEBSOCKET_TIMEOUT)throw WC.warning("[".concat(this.store.clientId,"] User join failed"),t.toString()),t;if(t&&t.code===xg.INIT_DATACHANNEL_TIMEOUT)throw WC.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw WC.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),iv.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!o,signalChannel:this.signal instanceof AD?"1":"0"}),this._isProactiveJoin=!1,r.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),WC.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{WC.warning("[".concat(this.store.clientId,"] get traffic stats error"),e.toString())}))}),3e3),this.networkQualityInterval=window.setInterval((()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(Zv.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(Zv.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(Zv.NETWORK_QUALITY,{uplinkNetworkQuality:mD(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:mD(this._statsCollector.trafficStats.B_dnq)}):this.emit(Zv.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})}),2e3),this.store.joinGatewayEnd(),s}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==cS.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==Ev.CONNECTED||await function(e,t){return t===1/0?e:tg.race([e,MS(t)])}(this.signal.request(fv.LEAVE,void 0,!0),3e3)}catch(e){WC.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==cS.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const n={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:kC("PUB_EXTEND"),twcc:!!kC("PUBLISH_TWCC"),rtx:!!kC("USE_PUB_RTX")};try{return(await this.signal.request(fv.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===_v.ERR_PUBLISH_REQUEST_INVALID)return WC.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),n.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw n}}async publishDataChannel(e,t,i){var n;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const r={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(n=t.maxRetransmits)&&void 0!==n?n:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(fv.PUBLISH_DATASTREAM,r,!0)}catch(n){if(i&&n.data&&n.data.code===_v.ERR_PUBLISH_REQUEST_INVALID)return WC.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),n.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw n}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(fv.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){WC.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await tg.all(e.map((e=>this.signal.request(fv.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){WC.warning("unpublish datachannels warning: ",e)}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!kC("SUBSCRIBE_TWCC"),rtx:!!kC("USE_SUB_RTX"),extend:kC("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(kC("SVC"))&&0!==kC("SVC").length?kC("SVC"):void 0};try{return(await this.signal.request(fv.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===_v.ERR_SUBSCRIBE_REQUEST_INVALID)return WC.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),n.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw n}}async subscribeDataChannel(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const n={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(fv.SUBSCRIBE_DATASTREAM,n,!0)}catch(n){if(i&&n.data&&n.data.code===_v.ERR_SUBSCRIBE_REQUEST_INVALID)return WC.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),n.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw n}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!kC("USE_SUB_RTX")};try{return await this.signal.request(fv.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===_v.ERR_SUBSCRIBE_REQUEST_INVALID)return WC.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,n=e.height,r=!0;return"number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(r=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,t||(r=!1)),r?{stream_type:0,width:i,height:n,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0}(e);if(t)return this.signal.request(fv.SET_VIDEO_PROFILE,t);WC.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(fv.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){WC.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new Mv(xg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await tg.all(e.map((e=>this.signal.request(fv.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){WC.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(fv.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){WC.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=e;return{gatewayEstablishParams:await this.signal.request(fv.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(fv.GATEWAY_INFO)}async renewToken(e){await this.signal.request(fv.RENEW_TOKEN,e),this.key=e.token}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),"CONNECTED"!==this.state)return void(this.role=e);let i,n=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,n=1):n=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:n=0,await this.signal.request(fv.SET_CLIENT_ROLE,{role:e,level:n,delay:i,client_ts:Date.now()}),this.role=e}async setRemoteVideoStreamType(e,t){await this.signal.request(fv.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(fv.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(fv.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(fv.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(fv.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,i){if(this.signal instanceof wD)return this.signal.sendExtensionMessage(e,t,i)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),ND({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(fv.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=DD.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0)}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:rv.username,password:rv.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null}(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(ND(ND({},rv),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if("CONNECTED"!==this.state)return;const e=await this.signal.request(fv.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach((e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find((t=>t.peer_uid===e.peer_uid));t&&t.B_st!==e.B_st&&AS((()=>{this.emit(Zv.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){if(!this.joinInfo||!this.key)throw new Mv(xg.UNEXPECTED_ERROR,"can not generate join message, no join info");const t=Object.assign({},this.joinInfo.apResponse);let i=kC("REPORT_APP_SCENARIO");if("string"!=typeof i)try{i=JSON.stringify(i)}catch(e){i=void 0}i&&i.length>128&&(i=void 0);const n=ND({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:OC,browser:navigator.userAgent,process_id:kC("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:t,extend:kC("JOIN_EXTEND"),details:{6:this.joinInfo.stringUid,cservice_map:"proxy3"===this.joinInfo.cloudProxyServer?"1":"proxy5"===this.joinInfo.cloudProxyServer?"2":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:i,attributes:{userAttributes:{enablePublishedUserList:kC("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:kC("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:"number"==typeof kC("SUBSCRIBE_AUDIO_FILTER_TOPN")?kC("SUBSCRIBE_AUDIO_FILTER_TOPN"):void 0,enablePublishAudioFilter:"boolean"==typeof kC("ENABLE_PUBLISH_AUDIO_FILTER")?kC("ENABLE_PUBLISH_AUDIO_FILTER"):void 0,enableUserLicenseCheck:"boolean"==typeof kC("ENABLE_USER_LICENSE_CHECK")?kC("ENABLE_USER_LICENSE_CHECK"):void 0,enableRTX:!0===kC("USE_PUB_RTX")||!0===kC("USE_SUB_RTX")||void 0,disableFEC:kC("DISABLE_FEC"),enableNTPReport:!!kC("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:!!kC("ENABLE_INSTANT_VIDEO")||void 0,enableDataStream2:"boolean"==typeof kC("ENABLE_DATASTREAM_2")?kC("ENABLE_DATASTREAM_2"):void 0,rtm2Flag:"number"==typeof kC("RTM2_FLAG")?kC("RTM2_FLAG"):void 0,enableUserAutoRebalanceCheck:!!kC("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:"boolean"==typeof kC("USE_XR")?kC("USE_XR"):void 0}},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(n.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(n.aes_mode=this.joinInfo.aesmode,kC("ENCRYPT_AES")?(n.aes_secret=this.joinInfo.aespassword,n.aes_encrypt=!0):n.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(n.aes_salt=this.joinInfo.aessalt)),t.addresses[this.signal.websocket.currentURLIndex]&&(n.ap_response.ticket=t.addresses[this.signal.websocket.currentURLIndex].ticket,delete t.addresses),void 0!==this.joinInfo.defaultVideoStream&&(n.default_video_stream=this.joinInfo.defaultVideoStream),n}getRejoinMessage(){if(!this.joinInfo)throw new Mv(xg.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(mv.WS_RECONNECT_WAITTING_FINISH,(e=>{var t;Lr(t=["tryNext","recover"]).call(t,e)&&this.joinInfo&&iv.adjustSessionStartTime(this.joinInfo.sid)})),this.signal.on(mv.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(mv.WS_RECONNECTING,(e=>{this.joinInfo&&iv.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||lS.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",iv.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(mv.WS_CLOSED,(e=>{let t;switch(e){case cS.LEAVE:t=lS.LEAVE;break;case cS.UID_BANNED:case cS.IP_BANNED:case cS.CHANNEL_BANNED:case cS.SERVER_ERROR:t=lS.SERVER_ERROR;break;case cS.FALLBACK:t=lS.FALLBACK;break;case cS.LICENSE_MISSING:case cS.LICENSE_EXPIRED:case cS.LICENSE_MINUTES_EXCEEDED:case cS.LICENSE_PERIOD_INVALID:case cS.LICENSE_MULTIPLE_SDK_SERVICE:case cS.LICENSE_ILLEGAL:case cS.TOKEN_EXPIRE:t=e;break;default:t=lS.NETWORK_ERROR}WC.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+lS.NETWORK_ERROR)),this.joinInfo&&iv.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===cS.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==cS.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(mv.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo&&("audience"===this.role&&this._clientRoleOptions&&(this._clientRoleOptions.level||this._clientRoleOptions.delay)&&(WC.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(this._clientRoleOptions.level,", delay: ").concat(this._clientRoleOptions.delay)),this.setClientRole(this.role,this._clientRoleOptions)),iv.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof AD?"1":"0"}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion)){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void WC.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));LC("EVENT_REPORT_DOMAIN",e[1]),LC("EVENT_REPORT_BACKUP_DOMAIN",e[1]),LC("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}})),this.signal.on(Sv.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(mv.REQUEST_RECOVER,((e,t,i)=>{if(!this.joinInfo)return i(new Mv(xg.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,fS(this,Zv.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)})),this.signal.on(mv.REQUEST_JOIN_INFO,(async e=>{var t;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const{iceParameters:i,dtlsParameters:n,rtpCapabilities:r}=await fS(this,Zv.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:null===(t=this.joinInfo)||void 0===t?void 0:t.turnServer});e(this.getJoinMessage({ortc:{iceParameters:i,dtlsParameters:n,rtpCapabilities:r,version:"2"}}))})),this.signal.on(mv.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(mv.REPORT_JOIN_GATEWAY,((e,t)=>{this.joinInfo&&(iv.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:e,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof AD?"1":"0"}),this._isProactiveJoin=!1)})),this.signal.on(mv.IS_P2P_DISCONNECTED,(e=>{e(TS(this,Zv.IS_P2P_DISCONNECTED))})),this.signal.on(mv.DISCONNECT_P2P,(()=>{this.emit(Zv.DISCONNECT_P2P)})),this.signal.on(mv.NEED_RENEW_SESSION,(()=>{this.emit(Zv.NEED_RENEW_SESSION)})),this.signal.on(mv.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(mv.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(mv.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(Zv.JOIN_RESPONSE,e,t)})),this.signal.on(mv.DATACHANNEL_PRECONNECT,(async(e,t,i)=>{this.updateTurnConfigFromSignal();const n=this.getCurrentGatewayAddress();return fS(this,Zv.DATACHANNEL_PRECONNECT,e,n).then(t).catch(i)})),this.signal.on(mv.DATACHANNEL_CONNECTING,(async e=>{const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await fS(this,Zv.REQUEST_DC_CONNECTION_PARAMS);e(this.getJoinMessage({ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n,version:"2"}}))})),this.signal.on(mv.DATACHANNEL_FAILBACK,(()=>{WC.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(Zv.DATACHANNEL_FAILBACK)}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(fv.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(fv.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw WC.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(fv.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(fv.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw WC.warning("unpublish datastream warning: ",e),e}}async tryMassUnsubBeforeResub(e){const t={users:e.map((e=>({stream_id:e.stream_id,stream_type:e.stream_type})))};try{await this.signal.request(fv.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const i={action:e.find((e=>e.stream_type===Qv.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(fv.CONTROL,i,!0,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const i={action:e.find((e=>e.stream_type===Qv.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(fv.CONTROL,i,!0,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const i={action:e===dI.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(fv.CONTROL,i,!0,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const i={action:e===dI.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(fv.CONTROL,i,!0,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),e),e}}uploadStats(e,t){this.signal.upload(e,t)}getSignalRTT(){return this.signal.rtt}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(fv.RESTART_ICE,t,!0)}catch(e){throw WC.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(){"CONNECTED"===this.state&&this.signal.reconnect(void 0,lS.P2P_FAILED)}getCurrentGatewayAddress(){var e;if(!kC("GATEWAY_WSS_ADDRESS"))return null!==(e=this.joinInfo)&&void 0!==e&&e.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(fv.SET_PARAMETER,{enablePublishAudioFilter:e})}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(cS.FALLBACK)),this.store.useDataChannel=!1,this.signal=new zI(ND(ND({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(Zv.RESET_SIGNAL,tI.websocket)}}let LD=0,kD=0;function MD(e,t,i,n){return new tg(((r,s)=>{t.timeout=t.timeout||kC("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),LD+=LS(t.data)):i&&(t.data.size?LD+=t.data.size:t.data instanceof FormData?LD+=kS(t.data):LD+=LS(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,EC.request(t).then((e=>{"string"==typeof e.data?kD+=LS(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?kD+=e.data.byteLength:kD+=LS(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{EC.isCancel(e)?s(new Mv(xg.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new Mv(xg.NETWORK_TIMEOUT,e.message)):e.response?s(new Mv(xg.NETWORK_RESPONSE_ERROR,e.response.status)):s(new Mv(xg.NETWORK_ERROR,e.message))}))}))}
2
2
  /*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */!function(){var e;function t(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var i,n="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,i){return e==Array.prototype||e==Object.prototype||(e[t]=i.value),e},r=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof J&&J];for(var t=0;t<e.length;++t){var i=e[t];if(i&&i.Math==Math)return i}throw Error("Cannot find global object")}(this);function s(e,t){if(t)e:{var i=r;e=e.split(".");for(var s=0;s<e.length-1;s++){var o=e[s];if(!(o in i))break e;i=i[o]}(t=t(s=i[e=e[e.length-1]]))!=s&&null!=t&&n(i,e,{configurable:!0,writable:!0,value:t})}}function o(e){return(e={next:e})[Symbol.iterator]=function(){return this},e}function a(e){var i="undefined"!=typeof Symbol&&Symbol.iterator&&e[Symbol.iterator];return i?i.call(e):{next:t(e)}}if(s("Symbol",(function(e){function t(e,t){this.A=e,n(this,"description",{configurable:!0,writable:!0,value:t})}if(e)return e;t.prototype.toString=function(){return this.A};var i="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",r=0;return function e(n){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(i+(n||"")+"_"+r++,n)}})),s("Symbol.iterator",(function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var i="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),s=0;s<i.length;s++){var a=r[i[s]];"function"==typeof a&&"function"!=typeof a.prototype[e]&&n(a.prototype,e,{configurable:!0,writable:!0,value:function(){return o(t(this))}})}return e})),"function"==typeof Object.setPrototypeOf)i=Object.setPrototypeOf;else{var c;e:{var d={};try{d.__proto__={a:!0},c=d.a;break e}catch(e){}c=!1}i=c?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null}var l=i;function h(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function u(e){if(e.m)throw new TypeError("Generator is already running");e.m=!0}function p(e,t){return e.h=3,{value:t}}function _(e){this.g=new h,this.G=e}function E(e,t,i,n){try{var r=t.call(e.g.j,i);if(!(r instanceof Object))throw new TypeError("Iterator result "+r+" is not an object");if(!r.done)return e.g.m=!1,r;var s=r.value}catch(t){return e.g.j=null,e.g.s(t),m(e)}return e.g.j=null,n.call(e.g,s),m(e)}function m(e){for(;e.g.h;)try{var t=e.G(e.g);if(t)return e.g.m=!1,{value:t.value,done:!1}}catch(t){e.g.v=void 0,e.g.s(t)}if(e.g.m=!1,e.g.l){if(t=e.g.l,e.g.l=null,t.F)throw t.D;return{value:t.return,done:!0}}return{value:void 0,done:!0}}function f(e){this.next=function(t){return e.o(t)},this.throw=function(t){return e.s(t)},this.return=function(t){return function(e,t){u(e.g);var i=e.g.j;return i?E(e,"return"in i?i.return:function(e){return{value:e,done:!0}},t,e.g.return):(e.g.return(t),m(e))}(e,t)},this[Symbol.iterator]=function(){return this}}function g(e,t){return t=new f(new _(t)),l&&e.prototype&&l(t,e.prototype),t}if(h.prototype.o=function(e){this.v=e},h.prototype.s=function(e){this.l={D:e,F:!0},this.h=this.C||this.u},h.prototype.return=function(e){this.l={return:e},this.h=this.u},_.prototype.o=function(e){return u(this.g),this.g.j?E(this,this.g.j.next,e,this.g.o):(this.g.o(e),m(this))},_.prototype.s=function(e){return u(this.g),this.g.j?E(this,this.g.j.throw,e,this.g.o):(this.g.s(e),m(this))},s("Array.prototype.entries",(function(e){return e||function(){return function(e,t){e instanceof String&&(e+="");var i=0,n=!1,r={next:function(){if(!n&&i<e.length){var r=i++;return{value:t(r,e[r]),done:!1}}return n=!0,{done:!0,value:void 0}}};return r[Symbol.iterator]=function(){return r},r}(this,(function(e,t){return[e,t]}))}})),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var S=function(e,t){for(var i=0;i<e.length;i++)t(e[i])},T=function(e){return e.replace(/\r?\n|\r/g,"\r\n")},R=function(e,t,i){return t instanceof Blob?(i=void 0!==i?String(i+""):"string"==typeof t.name?t.name:"blob",t.name===i&&"[object Blob]"!==Object.prototype.toString.call(t)||(t=new File([t],i)),[String(e),t]):[String(e),String(t)]},C=function(e,t){if(e.length<t)throw new TypeError(t+" argument required, but only "+e.length+" present.")},v="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,I=v.FormData,y=v.XMLHttpRequest&&v.XMLHttpRequest.prototype.send,A=v.Request&&v.fetch,b=v.navigator&&v.navigator.sendBeacon,w=v.Element&&v.Element.prototype,O=v.Symbol&&Symbol.toStringTag;O&&(Blob.prototype[O]||(Blob.prototype[O]="Blob"),"File"in v&&!File.prototype[O]&&(File.prototype[O]="File"));try{new File([],"")}catch(e){v.File=function(e,t,i){return e=new Blob(e,i||{}),Object.defineProperties(e,{name:{value:t},lastModified:{value:+(i&&void 0!==i.lastModified?new Date(i.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),O&&Object.defineProperty(e,O,{value:"File"}),e}}var N=function(e){return e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},D=function(e){this.i=[];var t=this;e&&S(e.elements,(function(e){if(e.name&&!e.disabled&&"submit"!==e.type&&"button"!==e.type&&!e.matches("form fieldset[disabled] *"))if("file"===e.type){var i=e.files&&e.files.length?e.files:[new File([],"",{type:"application/octet-stream"})];S(i,(function(i){t.append(e.name,i)}))}else"select-multiple"===e.type||"select-one"===e.type?S(e.options,(function(i){!i.disabled&&i.selected&&t.append(e.name,i.value)})):"checkbox"===e.type||"radio"===e.type?e.checked&&t.append(e.name,e.value):(i="textarea"===e.type?T(e.value):e.value,t.append(e.name,i))}))};if((e=D.prototype).append=function(e,t,i){C(arguments,2),this.i.push(R(e,t,i))},e.delete=function(e){C(arguments,1);var t=[];e=String(e),S(this.i,(function(i){i[0]!==e&&t.push(i)})),this.i=t},e.entries=function e(){var t,i=this;return g(e,(function(e){if(1==e.h&&(t=0),3!=e.h)return t<i.i.length?e=p(e,i.i[t]):(e.h=0,e=void 0),e;t++,e.h=2}))},e.forEach=function(e,t){C(arguments,1);for(var i=a(this),n=i.next();!n.done;n=i.next()){var r=a(n.value);n=r.next().value,r=r.next().value,e.call(t,r,n,this)}},e.get=function(e){C(arguments,1);var t=this.i;e=String(e);for(var i=0;i<t.length;i++)if(t[i][0]===e)return t[i][1];return null},e.getAll=function(e){C(arguments,1);var t=[];return e=String(e),S(this.i,(function(i){i[0]===e&&t.push(i[1])})),t},e.has=function(e){C(arguments,1),e=String(e);for(var t=0;t<this.i.length;t++)if(this.i[t][0]===e)return!0;return!1},e.keys=function e(){var t,i,n,r=this;return g(e,(function(e){if(1==e.h&&(t=a(r),i=t.next()),3!=e.h)return i.done?void(e.h=0):(n=i.value,p(e,a(n).next().value));i=t.next(),e.h=2}))},e.set=function(e,t,i){C(arguments,2),e=String(e);var n=[],r=R(e,t,i),s=!0;S(this.i,(function(t){t[0]===e?s&&(s=!n.push(r)):n.push(t)})),s&&n.push(r),this.i=n},e.values=function e(){var t,i,n,r,s=this;return g(e,(function(e){if(1==e.h&&(t=a(s),i=t.next()),3!=e.h)return i.done?void(e.h=0):(n=i.value,(r=a(n)).next(),p(e,r.next().value));i=t.next(),e.h=2}))},D.prototype._asNative=function(){for(var e=new I,t=a(this),i=t.next();!i.done;i=t.next()){var n=a(i.value);i=n.next().value,n=n.next().value,e.append(i,n)}return e},D.prototype._blob=function(){var e="----formdata-polyfill-"+Math.random(),t=[],i="--"+e+'\r\nContent-Disposition: form-data; name="';return this.forEach((function(e,n){return"string"==typeof e?t.push(i+N(T(n))+'"\r\n\r\n'+T(e)+"\r\n"):t.push(i+N(T(n))+'"; filename="'+N(e.name)+'"\r\nContent-Type: '+(e.type||"application/octet-stream")+"\r\n\r\n",e,"\r\n")})),t.push("--"+e+"--"),new Blob(t,{type:"multipart/form-data; boundary="+e})},D.prototype[Symbol.iterator]=function(){return this.entries()},D.prototype.toString=function(){return"[object FormData]"},w&&!w.matches&&(w.matches=w.matchesSelector||w.mozMatchesSelector||w.msMatchesSelector||w.oMatchesSelector||w.webkitMatchesSelector||function(e){for(var t=(e=(this.document||this.ownerDocument).querySelectorAll(e)).length;0<=--t&&e.item(t)!==this;);return-1<t}),O&&(D.prototype[O]="FormData"),y){var P=v.XMLHttpRequest.prototype.setRequestHeader;v.XMLHttpRequest.prototype.setRequestHeader=function(e,t){P.call(this,e,t),"content-type"===e.toLowerCase()&&(this.B=!0)},v.XMLHttpRequest.prototype.send=function(e){e instanceof D?(e=e._blob(),this.B||this.setRequestHeader("Content-Type",e.type),y.call(this,e)):y.call(this,e)}}A&&(v.fetch=function(e,t){return t&&t.body&&t.body instanceof D&&(t.body=t.body._blob()),A.call(this,e,t)}),b&&(v.navigator.sendBeacon=function(e,t){return t instanceof D&&(t=t._asNative()),b.call(this,e,t)}),v.FormData=D}}();const UD=()=>{const e=kC("AREAS");return 0===e.length&&e.push(iI.GLOBAL),cT(e).call(e,((e,t,i)=>{const n=xD(t);return n?0===i?n:"".concat(e,",").concat(n):e}),"")},xD=e=>e===iI.OVERSEA?"".concat(sI.ASIA,",").concat(sI.EUROPE,",").concat(sI.AFRICA,",").concat(sI.NORTH_AMERICA,",").concat(sI.SOUTH_AMERICA,",").concat(sI.OCEANIA):sI[e],VD=e=>{const t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map((e=>{const i=oI[e],n=Object.keys(i);n&&n.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))}))})),t},FD={GLOBAL:{ASIA:[iI.CHINA,iI.JAPAN,iI.INDIA,iI.KOREA,iI.HKMC],EUROPE:[],NORTH_AMERICA:[iI.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},BD=Object.keys(FD[iI.GLOBAL]),jD=[iI.CHINA,iI.NORTH_AMERICA,iI.EUROPE,iI.ASIA,iI.JAPAN,iI.INDIA,iI.OCEANIA,iI.SOUTH_AMERICA,iI.AFRICA,iI.KOREA,iI.HKMC,iI.US],GD=function(e,t){let i=[];if(Lr(e).call(e,iI.GLOBAL)){const s=[iI.GLOBAL,iI.OVERSEA],o=Object.keys(oI);if(t===iI.GLOBAL)throw new Mv(xg.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===iI.CHINA)i=[iI.OVERSEA];else if(r=t,Lr(BD).call(BD,r)){const e=(n=t,FD[iI.GLOBAL][n]||[]),r=[...s,t,...e];i=o.filter((e=>!Lr(r).call(r,e)))}else if(function(e){let t=!1;return BD.forEach((i=>{var n;Lr(n=FD[iI.GLOBAL][i]).call(n,e)&&(t=!0)})),t}(t)){const e=function(e){let t;return BD.forEach((i=>{var n;Lr(n=FD[iI.GLOBAL][i]).call(n,e)&&(t=i)})),t}(t),n=[...s,e,t];i=o.filter((e=>!Lr(n).call(n,e)))}else i=e;i=function(e){const t=[];return jD.forEach((i=>{Lr(e).call(e,i)&&t.push(i)})),t.concat(e.filter((e=>!Lr(jD).call(jD,e))))}(i)}else i=e;var n,r;return i};function WD(e){var t,i;if(!e&&Lr(t=kC("AREAS")).call(t,iI.EXTENSIONS))return WC.debug("update area from ap : reset"),void HD(nv,!0);if(!Lr(i=kC("AREAS")).call(i,iI.GLOBAL)||!e)return;let n=oI.EXTENSIONS;n&&(n={CODE:xD(iI.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(e,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(e,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(e,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(e,".agora.io"),"cds-ap-web-2-".concat(e,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(e,".agora.io"),"sua-ap-web-2-".concat(e,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(e,".agora.io"),"uap-ap-web-2-".concat(e,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(e,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(e,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(e,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(e,".agora.io")]},WC.debug("update area from ap success: ".concat(e,",config is "),n),LC("AREAS",[iI.EXTENSIONS],!0),Object.keys(n).map((e=>{LC(e,"LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e?n[e][0]:n[e])})))}function HD(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=iv.reportApiInvoke(null,{name:sS.SET_AREA,options:e,tag:oS.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!Lr(rI).call(rI,e))throw new Mv(xg.INVALID_PARAMS,"invalid area code")})),n=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new Mv(xg.INVALID_PARAMS,"area code is needed");let r=t;"string"==typeof t&&(r=[t]),n=i?GD(r,i):r}if(!t){if(MC.AREAS){const e=new Mv(xg.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void WC.warning("setArea is prohibited because of config-distribute")}if(Lr(n).call(n,iI.GLOBAL)&&kC("AREAS")===iI.EXTENSIONS){const e=new Mv(xg.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void WC.warning("setArea is prohibited because of ap extensions")}}LC("AREAS",n,t);const r=VD(n);Object.keys(r).map((e=>{LC(e,"LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e?r[e][0]:r[e])})),WC.debug("set area success:",n.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}function KD(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function YD(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?KD(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):KD(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let qD=1;function JD(e,t,i,n,r){qD+=1;const s={sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:qD,requestId:qD,version:OC,cname:i.cname},o={service_name:t,json_body:JSON.stringify(s)};let a,c,d=e[0];return XS((async()=>{a=Date.now();const e=await MD(d,{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,0!==e.code){const t=new Mv(xg.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw WC.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new Mv(xg.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw WC.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new Mv(xg.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw WC.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(kC("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(i,t);return kC("LIVE_STREAMING_ADDRESS")&&(r.addressList=kC("LIVE_STREAMING_ADDRESS")instanceof Array?kC("LIVE_STREAMING_ADDRESS"):[kC("LIVE_STREAMING_ADDRESS")]),YD(YD({},r),{},{responseTime:c})}),((n,r)=>(iv.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(n.addressList),firstSuccess:0===r,responseTime:c,serverIp:e[r%e.length]}),!1)),((n,r)=>(iv.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(n.code!==xg.OPERATION_ABORTED&&n.code!==xg.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(r+1)%e.length],!0))),r)}let zD=1;function XD(e,t,i,n){let{url:r,areaCode:s}=e;const o=Date.now();let a;const[c,d]=tP(t,s,[dy.CHOOSE_SERVER]);let l=RS.networkState;return XS((async()=>{l&&RS.networkState===hS.OFFLINE&&RS.onlineWaiter&&await tg.race([RS.onlineWaiter,US(n&&n.maxRetryTimeout||JS.maxRetryTimeout)]),l=RS.networkState;const{data:e,headers:s}=await MD(r,{data:c,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);a="1"===s.http3?1:-1,iv.reportResourceTiming(r,t.sid),ZD(e,r,t,o,[dy.CHOOSE_SERVER],a);const d=fD(e,dy.CHOOSE_SERVER);return $D(d),uD(d,r)}),(e=>(e&&iv.joinChooseServer(t.sid,{lts:o,succ:!0,csAddr:r,opid:d,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[dy.CHOOSE_SERVER].toString(),isHttp3:a}),!1)),(e=>e.code!==xg.OPERATION_ABORTED&&(e.code===xg.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(iv.joinChooseServer(t.sid,{lts:o,succ:!1,csAddr:r,serverList:null,opid:d,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[dy.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:l}),isHttp3:a}),WC.warning("[".concat(t.clientId,"] Choose server network error, retry"),e),!0))),n)}function QD(e,t,i,n){let r,{url:s,areaCode:o,serviceIds:a}=e;const c=Date.now(),[d,l]=tP(t,o,a);let h;return XS((async()=>{h&&RS.networkState===hS.OFFLINE&&RS.onlineWaiter&&await tg.race([RS.onlineWaiter,US(n&&n.maxRetryTimeout||JS.maxRetryTimeout)]),h=RS.networkState;const{data:e,headers:o}=await MD(s,{data:d,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r="1"===o.http3?1:-1,iv.reportResourceTiming(s,t.sid),ZD(e,s,t,c,a,r);const l=fD(e,dy.CHOOSE_SERVER),u=fD(e,"proxy5"===t.cloudProxyServer?dy.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK);return $D(l),{gatewayInfo:uD(l,s),proxyInfo:u,url:s}}),(e=>(e.gatewayInfo&&iv.joinChooseServer(t.sid,{lts:c,succ:!0,csAddr:s,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:l,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r}),e.proxyInfo&&iv.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:s,turnServerAddrList:e.proxyInfo.addresses.map((e=>e.ip)).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:a.toString()}),!1)),(e=>e.code!==xg.OPERATION_ABORTED&&(e.code===xg.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(iv.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:s,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:h})}),WC.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),n)}const ZD=(e,t,i,n,r,s)=>{const o=[],a=o=>{4096===o.flag?iv.joinChooseServer(i.sid,{lts:n,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:o.error.message,csIp:o.error.data&&o.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:s}):1048576!==o.flag&&4194304!==o.flag&&4194310!==o.flag||iv.joinWebProxyAP(i.sid,{lts:n,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:o.error.code,eventType:i.cloudProxyServer,unilbsServerIds:r.toString()})};if(e.response_body.forEach((t=>{const i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)WC.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else{const i={error:new Mv(xg.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:t.buffer.flag};o.push(i),a(i)}if(0!==i){const n=PI(i),r={error:new Mv(xg.CAN_NOT_GET_GATEWAY_SERVER,n.desc,{desc:n.desc,retry:n.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?WC.warning(r.error.toString()):o.push(r),a(r)}})),o.length)throw WC.warning("[".concat(i.clientId,"] multi unilbs ").concat(t," failed, ").concat(o.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry))).join(" | "))),new Mv(xg.CAN_NOT_GET_GATEWAY_SERVER,o.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!o.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(o.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})},$D=e=>{var t,i,n,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new Mv(xg.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});if(kC("AP_AREA")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?WD(e.detail[23].toLowerCase()):WD()),null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(i=e.detail)||void 0===i?void 0:i[19])){const t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t<i.length;t++){var s;const n=Ey(s=i[t]).call(s);e.addresses[t]&&i&&(e.addresses[t].fingerprint=n)}}if(kC("GATEWAY_ADDRESS")&&kC("GATEWAY_ADDRESS").length>0){WC.debug("assign gateway address to",kC("GATEWAY_ADDRESS"));const t=kC("GATEWAY_ADDRESS").map((t=>{var i,n;const r=null!==(i=null===(n=e.addresses.find((e=>e.ip===t.ip&&e.port===t.port)))||void 0===n?void 0:n.fingerprint)&&void 0!==i?i:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:r}}));e.addresses=t}},eP=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=PI(t.buffer.code);throw new Mv(xg.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw WC.debug("update ticket request received ap response without response body:",t),new Mv(xg.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},tP=(e,t,i)=>{const n=Math.floor(Math.random()*10**12),r={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:YD({6:e.stringUid,11:t,12:kC("USE_NEW_TOKEN")?"1":void 0,22:t},kC("AP_RTM")?{26:"RTM2"}:{}),key:e.token,service_ids:i,uid:e.uid||0}}]};r.request_bodies.forEach((t=>{e.multiIP&&e.multiIP.gateway_ip&&(t.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}))}));const s=new FormData;return s.append("request",JSON.stringify(r)),[s,n]},iP=(e,t)=>{const i=Math.floor(Math.random()*10**12),n={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map((e=>({ip:e.ip,port:e.port})))}}]},r=new FormData;return r.append("request",JSON.stringify(n)),[r,i]};let nP=0;function rP(e){return tg.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const sP=async e=>{let{fragementLength:t,referenceList:i,asyncMapHandler:n,allFailedhandler:r,promisesCollector:s}=e,o=0;const a=t;let c,d=0;const l=async()=>{const e=(()=>{const e=o*a,t=e+a;return i.slice(e,t).map(n)})();s&&s.push(...e);try{c=await rP(e)}catch(e){if(d+=a,o++,!(d>=i.length))return void await l();r(e)}e.forEach((e=>e.cancel()))};return await l(),c};async function oP(e,t,i,n){const r=async function(e,t,i,n){let r=null;const s=[],o=async()=>{const r=kC("WEBCS_DOMAIN").slice(0,kC("AJAX_REQUEST_CONCURRENT")).map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:UD()}))),o=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),a=await sP({fragementLength:kC("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(WC.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),XD(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0]},promisesCollector:s});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},o),a},a=async()=>{if(await US(1e3),null!==r)return r;const o=kC("WEBCS_DOMAIN_BACKUP_LIST").map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:UD()}))),a=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),c=await sP({fragementLength:kC("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(WC.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),XD(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:s});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c};try{return r=await rP([o(),a()]),s.length&&s.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),r}catch(e){throw e[0]}}(e,t,i,n);return{gatewayInfo:await r}}async function aP(e,t,i,n,r){const s=e.cloudProxyServer;if("disabled"===s){if(!n)return;if(e.useLocalAccessPoint)return await oP(e,t,i,r);if(kC("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:n,proxyInfo:s}=await lP(e,t,i,r);return e.turnServer&&"auto"!==e.turnServer.mode||(e.turnServer={mode:"manual",servers:s.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||rv.tcpport,udpport:e.udpport||rv.udpport,username:e.username||rv.username,password:e.password||rv.password,forceturn:!1,security:!0})))}),{gatewayInfo:n}}return await oP(e,t,i,r)}const{proxyInfo:o,gatewayInfo:a}=await lP(e,t,i,r),c={gatewayInfo:a};return e.turnServer={mode:"manual",servers:o.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===s?void 0:e.tcpport?e.tcpport:rv.tcpport,udpport:"proxy4"===s?void 0:e.udpport?e.udpport:rv.udpport,username:e.username||rv.username,password:e.password||rv.password,forceturn:"proxy4"!==s,security:"proxy5"===s})))},WC.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(s)),c}async function cP(e,t,i,n,r){const s=kC("ACCOUNT_REGISTER").slice(0,kC("AJAX_REQUEST_CONCURRENT"));let o=[];o=t.proxyServer?s.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):s.map((e=>"https://".concat(e,"/api/v1")));const a=null==r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:o});try{const s=await async function(e,t,i,n,r){const s=Date.now(),o={sid:i.sid,opid:10,appid:i.appId,string_uid:t};let a=e[0];const c=await XS((()=>MD(a+"".concat(-1===a.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((i,n)=>{if(0===i.code){if(i.uid<=0||i.uid>=Math.pow(2,32))throw WC.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),iv.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:xg.INVALID_UINT_UID_FROM_STRING_UID,extend:o}),new Mv(xg.INVALID_UINT_UID_FROM_STRING_UID);return iv.reqUserAccount(o.sid,{lts:s,success:!0,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:null,extend:o}),!1}const r=PI(i.code);return r.retry&&(a=e[(n+1)%e.length]),iv.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:r.desc,extend:o}),r.retry}),((t,i)=>t.code!==xg.OPERATION_ABORTED&&(iv.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:null,errorCode:t.code,extend:o}),a=e[(i+1)%e.length],!0)),r);if(0!==c.code){const e=PI(c.code);throw new Mv(xg.UNEXPECTED_RESPONSE,e.desc)}return c}(o,e,t,i,n);return null==r||r.recordJoinChannelService({status:"success",endTs:Date.now()},a),s.uid}catch(e){throw null==r||r.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},a),e}}async function dP(e,t,i){const n=kC("CDS_AP").slice(0,kC("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1"):"https://".concat(t,"/api/v1?action=config"))).map((n=>function(e,t,i,n){const r=pg(),s={flag:64,cipher_method:0,features:{device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:OC,cname:t.cname,sid:t.sid,session_id:t.sid,detail:"",proxyServer:t.proxyServer}};return XS((()=>MD(e,{data:s,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==xg.OPERATION_ABORTED),n)}(n,e,t,i)));let r=null,s=null,o={};try{r=await rP(n)}catch(e){if(e.code===xg.OPERATION_ABORTED)throw e;s=e}if(n.forEach((e=>e.cancel())),iv.reportApiInvoke(e.sid,{name:sS.REQUEST_CONFIG_DISTRIBUTE,options:{error:s,res:r}}).onSuccess(),r&&r.test_tags)try{o=function(e){if(!e.test_tags)return{};const t=e.test_tags,i=Object.keys(t),n={};return i.forEach((e=>{var i;const r=Ey(i=e.slice(4)).call(i),s=JSON.parse(t[e])[1];n[r]=s})),n}(r)}catch(e){}return o}async function lP(e,t,i,n){const r=kC("PROXY_SERVER_TYPE3"),s=(e,t,i)=>{let n=i||r;return Array.isArray(n)&&(n=t%2==0?r[1]:r[0]),"https://".concat(n,"/ap/?url=").concat(e)};let o=null;const a=[],c=async()=>{const r=kC("WEBCS_DOMAIN").slice(0,kC("AJAX_REQUEST_CONCURRENT")).map(((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:UD(),serviceIds:[dy.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?dy.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK]}})),o=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),c=await sP({fragementLength:kC("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(WC.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),QD(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},o),c},d=async()=>{if(await US(1e3),null!==o)return o;const r=kC("WEBCS_DOMAIN_BACKUP_LIST").map(((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:UD(),serviceIds:[dy.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?dy.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK]}})),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),d=await sP({fragementLength:kC("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(WC.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),QD(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d};let l,h,u;try{({gatewayInfo:l,proxyInfo:h,url:u}=await rP([c(),d()]))}catch(e){throw e[0]}if(a.length&&a.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),!l||!h)throw new Mv(xg.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=u,"disabled"!==e.cloudProxyServer&&Array.isArray(r)&&u){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(u)[1];Lr(r).call(r,t)&&(e.proxyServer=t,WC.setProxyServer(t),iv.setProxyServer(t))}return o={gatewayInfo:l,proxyInfo:await gD(h,l.uid)},o}async function hP(e,t,i,n){const r=kC("UAP_AP").slice(0,kC("AJAX_REQUEST_CONCURRENT")).map((e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap")));return await JD(r,e,t,i,n)}async function uP(e,t,i){const n=kC("UAP_AP").slice(0,kC("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1?action=uap"):"https://".concat(t,"/api/v1?action=uap"))).map((n=>function(e,t,i,n){const r={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:OC,cname:t.cname,uid:t.uid.toString(),requestId:zD,seq:zD};zD+=1;const s={service_name:"tele_channel",json_body:JSON.stringify(r)};return XS((async()=>{const t=await MD(e,{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new Mv(xg.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw WC.error(e.toString()),e}const n=JSON.parse(t.json_body);if(200!==n.code){const e=new Mv(xg.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(n.code,", reason: ").concat(n.reason));throw WC.error(e.toString()),e}if(!n.servers||0===n.servers.length){const e=new Mv(xg.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw WC.error(e.toString()),e}return{vid:n.vid,workerToken:n.workerToken,addressList:(kC("CHANNEL_MEDIA_RELAY_SERVERS")||n.servers).map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(kC("WORKER_DOMAIN"),":").concat(e.wss)))}}),void 0,(e=>!!(e.code!==xg.OPERATION_ABORTED&&e.code!==xg.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),n)}(n,e,t,i)));try{const e=await rP(n);return n.forEach((e=>e.cancel())),e}catch(e){throw e[0]}}async function pP(e,t,i){let n=null;const r=[],s=async s=>{const o=kC(s?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2")));return s&&(await US(1e3),null!==n)?n:await sP({fragementLength:kC("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(WC.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(s?"backup":""," choose_server:"),n),function(e,t,i,n){const[r]=iP(t,[dy.CHOOSE_SERVER]);let s=RS.networkState;return XS((async()=>{s&&RS.networkState===hS.OFFLINE&&RS.onlineWaiter&&await tg.race([RS.onlineWaiter,US(n&&n.maxRetryTimeout||JS.maxRetryTimeout)]),s=RS.networkState;const t=await MD(e,{data:r,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return eP(t,e)}),(()=>!1),(e=>e.code!==xg.OPERATION_ABORTED&&(e.code===xg.UPDATE_TICKET_FAILED?e.data.retry:(WC.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0))),n)}(n,e,t,i)),allFailedhandler:e=>{throw e[0]},promisesCollector:r})};try{return n=await rP([s(!1),s(!0)]),r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),n}catch(e){throw e[0]}}function _P(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function EP(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?_P(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):_P(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class mP extends iS{constructor(){super(),nu(this,"configs",void 0),nu(this,"joinInfo",void 0),nu(this,"cancelToken",void 0),nu(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),nu(this,"interval",void 0),nu(this,"mutex",new YS("config-distribute")),nu(this,"mutableParamsRead",!1)}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),kC("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval((()=>{this.updateConfigDistribute()}),kC("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0}async awaitConfigDistributeComplete(){this.mutex.isLocked&&(await this.mutex.lock())()}async updateConfigDistribute(){if(this.mutableParamsRead||(this.mutableParamsRead=!0,iv.reportApiInvoke(null,{options:void 0,name:sS.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:oS.TRACER}).onSuccess(JSON.stringify(MC))),!this.joinInfo||!this.cancelToken||!this.retryConfig)return void WC.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await dP(this.joinInfo,this.cancelToken,this.retryConfig),WC.debug("[config-distribute] get config distribute",JSON.stringify(e)),e.limit_bitrate&&this.handleBitrateLimit(e.limit_bitrate),this.cacheGlobalParameterConfig(e),this.configs=e}catch(e){const t=new Mv(xg.NETWORK_RESPONSE_ERROR,e);WC.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.configs?this.configs.limit_bitrate:void 0}handleBitrateLimit(e){var t;(t=e)&&t.uplink&&t.id&&void 0!==t.uplink.max_bitrate&&void 0!==t.uplink.min_bitrate&&(this.configs&&this.configs.limit_bitrate?this.configs&&this.configs.limit_bitrate&&this.configs.limit_bitrate.id!==e.id&&this.emit(aI.UPDATE_BITRATE_LIMIT,e):this.emit(aI.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.configs&&this.configs.limit_bitrate&&EP({},this.configs.limit_bitrate.low_stream_uplink)}cacheGlobalParameterConfig(e){var t;const i=Zu(t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e)))).call(t);for(let t=0;t<i.length;t++)for(let n=i.length-1;n>t;n--){const t=i[n];if("number"==typeof e[t].__priority){const r=e[t].__priority,s=i[n-1];if("number"==typeof e[s].__priority){if(!(r>e[s].__priority))continue;{const e=t;i[n]=i[n-1],i[n-1]=e}}else{const e=t;i[n]=i[n-1],i[n-1]=e}}}const n={};i.forEach((t=>{const i=e[t],r=i.__expires;Object.keys(i).forEach((e=>{"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(n,e)||(n[e]=EP({value:i[e]},r&&{expires:r}))}))}));try{!function(e){try{const t=Date.now();Object.keys(e).forEach((i=>{switch(i){case"ENABLE_EVENT_REPORT":case"UPLOAD_LOG":if(Object.prototype.hasOwnProperty.call(PC,i)){const{value:n,expires:r}=e[i];if(r&&r<=t)return;MC[i]=n,PC[i]=n,WC.debug("Update global parameters from config distribute",i,n)}}}))}catch(t){WC.error("Error update config immediately: ".concat(e),t.message)}}(n);const e=JSON.stringify(n),t=window.btoa(e);window.localStorage.setItem("websdk_ng_global_parameter",t),WC.debug("Caching global parameters ".concat(e))}catch(e){WC.error("Error caching global parameters:",e.message)}}}function fP(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function gP(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?fP(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fP(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class SP extends iS{constructor(e,t,i,n){super(),nu(this,"spec",void 0),nu(this,"token",void 0),nu(this,"websocket",void 0),nu(this,"pingpongTimer",void 0),nu(this,"reconnectMode","retry"),nu(this,"serviceMode",void 0),nu(this,"reqId",0),nu(this,"commandReqId",0),nu(this,"handleWebSocketOpen",(()=>{this.reconnectMode="retry",this.startPingPong()})),nu(this,"handleWebSocketMessage",(e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):this.serviceMode===vv.INJECT?this.emit(Wv.INJECT_STREAM_STATUS,t):(iv.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===vv.TRANSCODE?1:2}),this.emit(Wv.PUBLISH_STREAM_STATUS,t))})),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new JI("live-streaming",i),this.websocket.on(Cv.CONNECTED,this.handleWebSocketOpen),this.websocket.on(Cv.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(Cv.REQUEST_NEW_URLS,((e,t)=>{fS(this,Wv.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(Cv.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,i,n){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const r=this.commandReqId,s=this.reqId;if(!s||!this.websocket)throw new Mv(xg.UNEXPECTED_ERROR);const o=gP({command:e,sdkVersion:"4.19.1"===OC?"0.0.1":OC,seq:s,requestId:s,allocate:i,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new Mv(xg.WS_DISCONNECT);const a=()=>new tg(((e,t)=>{this.websocket.once(Cv.CLOSED,(()=>t(new Mv(xg.WS_ABORT)))),this.websocket.once(Cv.CONNECTED,e)}));"connected"!==this.websocket.state&&await a(),o.clientRequest&&(o.clientRequest.workerToken=this.token);const c=new tg(((e,t)=>{const i=()=>{t(new Mv(xg.WS_ABORT))};this.websocket.once(Cv.RECONNECTING,i),this.websocket.once(Cv.CLOSED,i),this.once("@".concat(s,"-").concat(this.spec.sid),(t=>{e(t)}))}));n&&iv.workerEvent(this.spec.sid,gP(gP({},n),{},{requestId:r,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(o);let l=null;try{l=await c}catch(n){if("closed"===this.websocket.state)throw n;return await a(),await this.request(e,t,i)}return n&&iv.workerEvent(this.spec.sid,gP(gP({},n),{},{requestId:r,actionType:"response",payload:JSON.stringify(l.serverResponse),serverCode:l.code,success:200===l.code,responseTime:Date.now()-d})),200!==l.code&&this.handleResponseError(l),l}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e="4.19.1"===OC?"0.0.1":OC;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case Kv.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void WC.warning("live stream response already exists stream");case Kv.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case Kv.LIVE_STREAM_RESPONSE_BAD_STREAM:case Kv.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new Mv(xg.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case Kv.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new Mv(xg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Kv.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new Mv(xg.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case Kv.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new Mv(xg.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(Wv.WARNING,t,e.serverResponse.url)}case Kv.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new Mv(xg.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(Wv.WARNING,t,e.serverResponse.url)}case Kv.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new Mv(xg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Kv.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new Mv(xg.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case Kv.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new Mv(xg.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(Wv.WARNING,t,e.serverResponse.url)}case Kv.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new Mv(xg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case Kv.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new Mv(xg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case Kv.LIVE_STREAM_RESPONSE_WORKER_LOST:case Kv.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new Mv(xg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Kv.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new Mv(xg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new Mv(xg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Kv.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Kv.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Kv.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Kv.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new Mv(xg.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval((()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(FS)}),6e3)}}function TP(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function RP(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?TP(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):TP(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class CP extends iS{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:JS,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:JS;super(),nu(this,"onLiveStreamWarning",void 0),nu(this,"onLiveStreamError",void 0),nu(this,"onInjectStatusChange",void 0),nu(this,"spec",void 0),nu(this,"retryTimeout",1e4),nu(this,"connection",void 0),nu(this,"httpRetryConfig",void 0),nu(this,"wsRetryConfig",void 0),nu(this,"streamingTasks",new Map),nu(this,"isStartingStreamingTask",!1),nu(this,"taskMutex",new YS("live-streaming")),nu(this,"cancelToken",EC.CancelToken.source()),nu(this,"transcodingConfig",void 0),nu(this,"injectConfig",RP({},Gv)),nu(this,"injectLoopTimes",0),nu(this,"uapResponse",void 0),nu(this,"lastTaskId",1),nu(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=RP(RP({},jv),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(WC.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map((e=>RP(RP(RP({},Vv),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){Kg(e.width)||jg(e.width,"config.width",0,1e4),Kg(e.height)||jg(e.height,"config.height",0,1e4),Kg(e.videoBitrate)||jg(e.videoBitrate,"config.videoBitrate",1,1e6),Kg(e.videoFrameRate)||jg(e.videoFrameRate,"config.videoFrameRate"),Kg(e.lowLatency)||Fg(e.lowLatency,"config.lowLatency"),Kg(e.audioSampleRate)||Bg(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),Kg(e.audioBitrate)||jg(e.audioBitrate,"config.audioBitrate",1,128),Kg(e.audioChannels)||Bg(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),Kg(e.videoGop)||jg(e.videoGop,"config.videoGop"),Kg(e.videoCodecProfile)||Bg(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),Kg(e.userCount)||jg(e.userCount,"config.userCount",0,17),Kg(e.backgroundColor)||jg(e.backgroundColor,"config.backgroundColor",0,16777215),Kg(e.userConfigExtraInfo)||Wg(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!Kg(e.transcodingUsers)&&(Hg(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach(((e,t)=>{xv(e.uid),Kg(e.x)||jg(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),Kg(e.y)||jg(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),Kg(e.width)||jg(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),Kg(e.height)||jg(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),Kg(e.zOrder)||jg(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),Kg(e.alpha)||jg(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)}))),Kg(e.watermark)||Bv(e.watermark,"watermark"),Kg(e.backgroundImage)||Bv(e.backgroundImage,"backgroundImage"),e.images&&!Kg(e.images)&&(Hg(e.images,"config.images"),e.images.forEach(((e,t)=>{Bv(e,"images[".concat(t,"]"))})))}(t);const i=[];t.images&&i.push(...t.images.map((e=>RP(RP(RP({},Fv),e),{},{zOrder:255})))),t.backgroundImage&&(i.push(RP(RP(RP({},Fv),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push(RP(RP(RP({},Fv),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>RP({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map((e=>"number"==typeof e.uid?tg.resolve(e.uid):cP(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await tg.all(n)).forEach(((e,i)=>{t.userConfigs&&t.userConfigs[i]&&(t.userConfigs[i].uid=e)})),this.transcodingConfig=t,this.connection)try{var r;const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(Pv(r=this.streamingTasks).call(r)).map((e=>e.taskId)).join("#")});WC.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach((t=>{WC.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{WC.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))})).catch((e=>{WC.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}setInjectStreamConfig(e,t){this.injectConfig=Object.assign({},this.injectConfig,e),this.injectLoopTimes=t}async startLiveStreamingTask(e,t,i){var n;if(Array.from(Pv(n=this.streamingTasks).call(n)).find((e=>e.mode===vv.INJECT))&&t===vv.INJECT)return new Mv(xg.LIVE_STREAMING_TASK_CONFLICT,"inject stream over limit").throw();if(!this.transcodingConfig&&t===vv.TRANSCODE)throw new Mv(xg.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");let r={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};WC.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const s=await this.taskMutex.lock();if(!this.connection&&i)return void s();if(this.streamingTasks.get(e)&&!i)return s(),new Mv(xg.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw s(),e}switch(t){case vv.TRANSCODE:r.transcodingConfig=RP({},this.transcodingConfig);break;case vv.RAW:break;case vv.INJECT:r={cname:this.spec.cname,command:"InjectStream",sid:this.spec.sid,transcodingConfig:this.injectConfig,ts:Date.now(),url:e,loopTimes:this.injectLoopTimes}}this.uapResponse&&this.uapResponse.vid&&(r.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const n=new tg(((t,n)=>{US(this.retryTimeout).then((()=>{if(i)return n(i);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0}))})),a=await tg.race([this.connection.request("request",{clientRequest:r},!0,{url:e,command:"PublishStream",workerType:t===vv.TRANSCODE?1:2,requestByUser:!i,tid:o.toString()}),n]);this.isStartingStreamingTask=!1,WC.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(a.code)),this.streamingTasks.set(e,{clientRequest:r,mode:t,url:e,taskId:o}),s()}catch(n){if(s(),this.isStartingStreamingTask=!1,!n.data||!n.data.retry||i)throw n;return n.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,n)):await this.startLiveStreamingTask(e,t,n)}}stopLiveStreamingTask(e){return new tg(((t,i)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new Mv(xg.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=n.mode;n.abortTask=()=>{WC.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:r===vv.INJECT?"UninjectStream":"UnpublishStream",url:n.url}},!1,{url:e,command:"UnPublishStream",workerType:r===vv.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((i=>{WC.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&r!==vv.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0),t(),r===vv.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(Iv.INJECT_STREAM_STATUS_STOP_SUCCESS,this.spec.uid,e)})).catch(i)}))}async controlInjectStream(e,t,i,n){const r=this.streamingTasks.get(e);if(!r||!this.connection||r.mode!==vv.INJECT)throw new Mv(xg.INVALID_OPERATION,"can not find inject stream task to control");return(await this.connection.request("request",{clientRequest:{command:"ControlStream",url:e,control:t,audioVolume:i,position:n}})).serverResponse}resetAllTask(){var e;const t=Array.from(Pv(e=this.streamingTasks).call(e));this.terminate();for(const e of t)this.startLiveStreamingTask(e.url,e.mode).catch((t=>{this.onLiveStreamError&&this.onLiveStreamError(e.url,t)}))}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=EC.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new Mv(xg.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await fS(this,Hv.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new SP(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(Wv.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(Wv.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(Wv.INJECT_STREAM_STATUS,(e=>this.handleInjectStreamServerStatus(e))),this.connection.on(Wv.REQUEST_NEW_ADDRESS,((t,i)=>{if(!this.connection)return i(new Mv(xg.UNEXPECTED_ERROR,"can not get new live streaming address list"));fS(this,Hv.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(i)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",i=this.streamingTasks.get(t),n=e.reason;switch(e.code){case Kv.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Kv.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Kv.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Kv.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new Mv(xg.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return WC.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n)}case Kv.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new Mv(xg.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case Kv.LIVE_STREAM_RESPONSE_WORKER_LOST:case Kv.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(Pv(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(WC.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",i.url),this.startLiveStreamingTask(i.url,i.mode,new Mv(xg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then((()=>{WC.debug("[".concat(this.spec.clientId,"] republish live stream success"),i.url)})).catch((e=>{WC.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(i.url,e)})));return}}}handleInjectStreamServerStatus(e){const t=Number(e.uid),i=e.serverStatus&&e.serverStatus.url;switch(e.code){case 200:return void(this.onInjectStatusChange&&this.onInjectStatusChange(Iv.INJECT_STREAM_STATUS_START_SUCCESS,t,i));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(Iv.INJECT_STREAM_STATUS_START_ALREADY_EXISTS,t,i),void this.streamingTasks.delete(i);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(Iv.INJECT_STREAM_STATUS_START_UNAUTHORIZED,t,i),void this.streamingTasks.delete(i);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(Iv.INJECT_STREAM_STATUS_BROKEN,t,i),void this.streamingTasks.delete(i);case 499:return this.onInjectStatusChange&&this.onInjectStatusChange(Iv.INJECT_STREAM_STATUS_START_TIMEOUT,t,i),void this.streamingTasks.delete(i);default:return void WC.debug("inject stream server status",e)}}hasUrl(e){return this.streamingTasks.has(e)}}class vP{constructor(){nu(this,"destChannelMediaInfos",new Map),nu(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){nI(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){nI(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){Uv(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function IP(e){if(!(e instanceof vP))return new Mv(xg.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw();const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();return t?0===i.size?new Mv(xg.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw():void 0:new Mv(xg.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}class yP extends iS{constructor(e,t,i){super(),nu(this,"ws",void 0),nu(this,"requestId",1),nu(this,"heartBeatTimer",void 0),nu(this,"joinInfo",void 0),nu(this,"clientId",void 0),nu(this,"onOpen",(()=>{this.emit("open"),this.startHeartBeatCheck()})),nu(this,"onClose",(e=>{this.emit("close"),this.dispose()})),nu(this,"onMessage",(e=>{const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t)})),this.joinInfo=e,this.clientId=t,this.ws=new JI("cross-channel-".concat(this.clientId),i),this.ws.on(Cv.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(Cv.CONNECTED,this.onOpen),this.ws.on(Cv.ON_MESSAGE,this.onMessage),this.ws.on(Cv.CLOSED,this.onClose)}isConnect(){return"connected"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new tg(((t,i)=>{const n=window.setTimeout((()=>{i(new Mv(xg.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new Mv(xg.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(n),i(new Mv(xg.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new Mv(xg.WS_DISCONNECT);const t=()=>new tg(((e,t)=>{this.ws.once(Cv.CLOSED,(()=>t(new Mv(xg.WS_ABORT)))),this.ws.once(Cv.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const i=this.sendMessage(e),n=new tg(((e,t)=>{const n=()=>{t(new Mv(xg.WS_ABORT))};this.ws.once(Cv.RECONNECTING,n),this.ws.once(Cv.CLOSED,n),this.once("req_".concat(i),e),US(3e3).then((()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(Cv.RECONNECTING,n),this.ws.off(Cv.CLOSED,n),t(new Mv(xg.TIMEOUT,"cross channel ws request timeout"))}))})),r=await n;if(!r||200!==r.code)throw new Mv(xg.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(Cv.REQUEST_NEW_URLS),this.ws.on(Cv.REQUEST_NEW_URLS,(t=>{t(e)})),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval((()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})}),3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class AP extends iS{set state(e){e!==this._state&&(e!==zv.RELAY_STATE_FAILURE&&(this.errorCode=Xv.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,i,n,r){super(),nu(this,"joinInfo",void 0),nu(this,"sid",void 0),nu(this,"clientId",void 0),nu(this,"cancelToken",EC.CancelToken.source()),nu(this,"workerToken",void 0),nu(this,"requestId",0),nu(this,"signal",void 0),nu(this,"prevChannelMediaConfig",void 0),nu(this,"httpRetryConfig",void 0),nu(this,"_resolution",void 0),nu(this,"_state",zv.RELAY_STATE_IDLE),nu(this,"errorCode",Xv.RELAY_OK),nu(this,"onStatus",(e=>{WC.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",Jv.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",Jv.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=Xv.SRC_TOKEN_EXPIRED,this.state=zv.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=Xv.DEST_TOKEN_EXPIRED,this.state=zv.RELAY_STATE_FAILURE))})),nu(this,"onReconnect",(async()=>{WC.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",Jv.NETWORK_DISCONNECTED),this.state=zv.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==zv.RELAY_STATE_IDLE&&(WC.error("auto restart channel media relay failed",e.toString()),this.errorCode=Xv.SERVER_CONNECTION_LOST,this.state=zv.RELAY_STATE_FAILURE)}))})),this.joinInfo=e,this.clientId=t,this.sid=VS(),this.signal=new yP(this.joinInfo,this.clientId,i),this.httpRetryConfig=n,this._resolution=r}async startChannelMediaRelay(e){if(this.state!==zv.RELAY_STATE_IDLE)throw new Mv(xg.INVALID_OPERATION);this.state=zv.RELAY_STATE_CONNECTING,await this.connect(),WC.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new Mv(xg.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new Mv(xg.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new Mv(xg.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==zv.RELAY_STATE_RUNNING)throw new Mv(xg.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==zv.RELAY_STATE_RUNNING)throw new Mv(xg.INVALID_OPERATION);const t=this.genMessage(qv.SetVideoProfile);await this.signal.request(t),WC.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),WC.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=zv.RELAY_STATE_IDLE,this.dispose()}dispose(){WC.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=EC.CancelToken.source(),this.state=zv.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await uP(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",Jv.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(qv.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),WC.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const i=this.genMessage(qv.SetSdkProfile,e);await this.signal.request(i),WC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(qv.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",Jv.PACKET_JOINED_SRC_CHANNEL),WC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const r=this.genMessage(qv.SetSourceUserId,e);await this.signal.request(r),WC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const s=this.genMessage(qv.SetDestChannel,e);await this.signal.request(s),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",Jv.PACKET_JOINED_DEST_CHANNEL),WC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(qv.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",Jv.PACKET_SENT_TO_DEST_CHANNEL),this.state=zv.RELAY_STATE_RUNNING,WC.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(qv.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",Jv.PACKET_UPDATE_DEST_CHANNEL),WC.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(qv.StopPacketTransfer);await this.signal.request(e),WC.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){const i=[],n=[],r=[];this.requestId+=1;const s={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:OC,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.19.1"===s.sdkVersion&&(s.sdkVersion="0.0.1");let o=null,a=null;switch(e){case qv.SetSdkProfile:return s.clientRequest={command:"SetSdkProfile",type:"multi_channel"},s;case qv.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new Mv(xg.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceChannel",uid:"0",channelName:a.channelName,token:a.token||this.joinInfo.appId},s;case qv.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new Mv(xg.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceUserId",uid:a.uid+""},s;case qv.SetDestChannel:if(o=t&&t.getDestChannelMediaInfo(),!o)throw new Mv(xg.UNEXPECTED_ERROR,"can not find dest config");return o.forEach((e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),s.clientRequest={command:"SetDestChannel",channelName:i,uid:n,token:r},s;case qv.StartPacketTransfer:return s.clientRequest={command:"StartPacketTransfer"},s;case qv.Reconnect:return s.clientRequest={command:"Reconnect"},s;case qv.StopPacketTransfer:return s.clientRequest={command:"StopPacketTransfer"},s;case qv.UpdateDestChannel:if(o=t&&t.getDestChannelMediaInfo(),!o)throw new Mv(xg.UNEXPECTED_ERROR,"can not find dest config");return o.forEach((e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),s.clientRequest={command:"UpdateDestChannel",channelName:i,uid:n,token:r},s;case qv.SetVideoProfile:s.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return s}}class bP{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio)return this._audioTrack}get videoTrack(){if(this.hasVideo)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(e,t){nu(this,"uid",void 0),nu(this,"_uintid",void 0),nu(this,"_trust_in_room_",!0),nu(this,"_trust_audio_enabled_state_",!0),nu(this,"_trust_video_enabled_state_",!0),nu(this,"_trust_audio_mute_state_",!0),nu(this,"_trust_video_mute_state_",!0),nu(this,"_audio_muted_",!1),nu(this,"_video_muted_",!1),nu(this,"_audio_enabled_",!0),nu(this,"_video_enabled_",!0),nu(this,"_audio_added_",!1),nu(this,"_video_added_",!1),nu(this,"_trust_video_stream_added_state_",!0),nu(this,"_trust_audio_stream_added_state_",!0),nu(this,"_audioTrack",void 0),nu(this,"_videoTrack",void 0),nu(this,"_dataChannels",[]),nu(this,"_audioSSRC",void 0),nu(this,"_videoSSRC",void 0),nu(this,"_audioOrtc",void 0),nu(this,"_videoOrtc",void 0),nu(this,"_cname",void 0),nu(this,"_rtxSsrcId",void 0),this.uid=e,this._uintid=t}}var wP=eg,OP=rm;Mn({target:"Promise",stat:!0,forced:!0},{withResolvers:function(){var e=OP.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var NP=rm,DP=FE;Mn({target:"Promise",stat:!0,forced:!0},{try:function(e){var t=NP.f(this),i=DP(e);return(i.error?t.reject:t.resolve)(i.value),t.promise}});var PP=z(wP),LP=Bo.f("asyncIterator"),kP=z(LP);function MP(e,t){this.v=e,this.k=t}function UP(e){var t,i;function n(t,i){try{var s=e[t](i),o=s.value,a=o instanceof MP;PP.resolve(a?o.v:o).then((function(i){if(a){var c="return"===t?"return":"next";if(!o.k||i.done)return n(c,i);i=e[c](i).value}r(s.done?"return":"normal",i)}),(function(e){n("throw",e)}))}catch(e){r("throw",e)}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?n(t.key,t.arg):i=null}this._invoke=function(e,r){return new PP((function(s,o){var a={key:e,arg:r,resolve:s,reject:o,next:null};i?i=i.next=a:(t=i=a,n(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}function xP(e){return function(){return new UP(e.apply(this,arguments))}}function VP(e){return new MP(e,0)}function FP(e){var t={},i=!1;function n(t,n){return i=!0,{done:!1,value:new MP(n=new PP((function(i){i(e[t](n))})),1)}}return t[void 0!==Uh&&$h||"@@iterator"]=function(){return this},t.next=function(e){return i?(i=!1,e):n("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(i)throw i=!1,e;return n("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return i?(i=!1,e):n("return",e)}),t}UP.prototype["function"==typeof Uh&&kP||"@@asyncIterator"]=function(){return this},UP.prototype.next=function(e){return this._invoke("next",e)},UP.prototype.throw=function(e){return this._invoke("throw",e)},UP.prototype.return=function(e){return this._invoke("return",e)};var BP=z(LP),jP={exports:{}};!function(e,t){e.exports=(()=>{var e={8:(e,t,i)=>{i.r(t),i.d(t,{Parser:()=>C,Printer:()=>b,parse:()=>D,print:()=>P});const n="\n",r="".concat("\r").concat(n),s=" ";let o;function a(e){return e>="0"&&e<="9"}function c(e){return e>="!"&&e<="~"}function d(e){return c(e)||e>="€"&&e<="ÿ"}function l(e){return"!"===e||e>="#"&&e<="'"||e>="*"&&e<="+"||e>="-"&&e<="."||e>="0"&&e<="9"||e>="A"&&e<="Z"||e>="^"&&e<="~"}function h(e){return e>="1"&&e<="9"}function u(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function p(e){return"d"===e||"h"===e||"m"===e||"s"===e}function _(e){return e>""&&e<"\t"||e>"\v"&&e<"\f"||e>""&&e<"ÿ"}function E(e){return u(e)||a(e)||"+"===e||"/"===e}function m(e){return a(e)||u(e)||"+"===e||"/"===e||"-"===e||"_"===e}function f(e){return u(e)||a(e)||"+"===e||"/"===e}function g(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function S(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?g(Object(i),!0).forEach((function(t){T(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):g(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function T(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}!function(e){e.VERSION="v",e.ORIGIN="o",e.SESSION_NAME="s",e.INFORMATION="i",e.URI="u",e.EMAIL="e",e.PHONE="p",e.CONNECTION="c",e.BANDWIDTH="b",e.TIME="t",e.REPEAT="r",e.ZONE_ADJUSTMENTS="z",e.KEY="k",e.ATTRIBUTE="a",e.MEDIA="m"}(o||(o={}));class R{consumeText(e,t){let i=t;for(;i<e.length;){const t=e[i];if("\0"===t||"\r"===t||t===n)break;i+=1}if(i-t==0)throw new Error("Invalid text, at ".concat(e));return i}consumeUnicastAddress(e,t,i){return this.consumeTill(e,t,s)}consumeOneOrMore(e,t,i){let n=t;for(;i(e[n]);)n++;if(n-t==0)throw new Error("Invalid rule at ".concat(t,"."));return n}consumeSpace(e,t){if(e[t]===s)return t+1;throw new Error("Invalid space at ".concat(t,"."))}consumeIP4Address(e,t){let i=t;for(let t=0;t<4;t++)if(i=this.consumeDecimalUChar(e,i),3!==t){if("."!==e[i])throw new Error("Invalid IP4 address.");i++}return i}consumeDecimalUChar(e,t){let i=t;for(let t=0;t<3&&a(e[i]);t++,i++);if(i-t==0)throw new Error("Invalid decimal uchar.");const n=parseInt(e.slice(t,i));if(n>=0&&n<=255)return i;throw new Error("Invalid decimal uchar")}consumeIP6Address(e,t){let i=this.consumeHexpart(e,t);return":"===e[i]?(i+=1,i=this.consumeIP4Address(e,i),i):i}consumeHexpart(e,t){let i=t;if(":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}if(i=this.consumeHexseq(e,i),":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}return i}consumeHexseq(e,t){let i=t;for(;i=this.consumeHex4(e,i),":"===e[i]&&":"!==e[i+1];)i+=1;return i}consumeHex4(e,t){let i=0;for(;i<4;i++)if(!((n=e[t+i])>="0"&&n<="9"||n>="a"&&n<="f"||n>="A"&&n<="F")){if(0===i)throw new Error("Invalid hex 4");break}var n;return t+i}consumeFQDN(e,t){let i=t;for(;a(e[i])||u(e[i])||"-"===e[i]||"."===e[i];)i+=1;if(i-t<4)throw new Error("Invalid FQDN");return i}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d)}consumeMulticastAddress(e,t,i){switch(i){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(e,t);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t)}catch(i){return this.consumeExtnAddr(e,t)}}}consumeIP6MulticastAddress(e,t){const i=this.consumeHexpart(e,t);return"/"===e[i]?this.consumeInteger(e,i+1):i}consumeIP4MulticastAddress(e,t){let i=t+3;const n=e.slice(t,i),r=parseInt(n);if(r<224||r>239)throw new Error("Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.");for(let t=0;t<3;t++){if("."!==e[i])throw new Error("Invalid IP4 multicast address.");i+=1,i=this.consumeDecimalUChar(e,i)}return"/"===e[i]&&(i+=1),i=this.consumeTTL(e,i),"/"===e[i]&&(i=this.consumeInteger(e,i)),i}consumeInteger(e,t){if(!h(e[t]))throw new Error("Invalid integer.");for(t+=1;a(e[t]);)t+=1;return t}consumeTTL(e,t){if("0"===e[t])return t+1;if(!h(e[t]))throw new Error("Invalid TTL.");t+=1;for(let i=0;i<2&&a(e[t]);i++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,l)}consumeTime(e,t){let i=t;if("0"===e[i])return i+1;for(h(e[i])&&(i+=1);a(e[i]);)i++;if(i-t<10)throw new Error("Invalid time");return i}consumeAddress(e,t){return this.consumeTill(e,t,s)}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),p(e[i])?i+1:i}consumeRepeatInterval(e,t){if(!h(e[t]))throw new Error("Invalid repeat interval");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,a)}consume(e,t,i){for(let n=0;n<i.length;n++){if(t+n>=e.length)throw new Error("consume exceeding value length");if(e[t+n]!==i[n])throw new Error("consume ".concat(i," failed at ").concat(n))}return t+i.length}consumeTill(e,t,i){let n=t;for(;n<e.length&&("string"!=typeof i||e[n]!==i)&&("function"!=typeof i||!i(e[n]));)n++;return n}}class C extends R{constructor(){super(),T(this,"records",[]),T(this,"currentLine",0)}parse(e){const t=this.probeEOL(e);this.records=e.split(t).filter((e=>!!e.trim())).map(this.parseLine),this.currentLine=0;const i=this.parseVersion(),n=this.parseOrigin(),r=this.parseSessionName(),s=this.parseInformation(),o=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),h=this.parseTimeFields(),u=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return{version:i,origin:n,sessionName:r,information:s,uri:o,emails:a,phones:c,connection:d,bandwidths:l,timeFields:h,key:u,attributes:p,mediaDescriptions:_}}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error("Record doesn't exit.");return e}probeEOL(e){for(let t=0;t<e.length;t++)if(e[t]===n)return"\r"===e[t-1]?r:n;throw new Error("Invalid newline character.")}parseLine(e,t){if(e.length<2)throw new Error("Invalid sdp line, sdp line should be of form <type>=<value>.");const i=e[0];if("="!==e[1])throw new Error('Invalid sdp line, <type> should be a single character followed by an "=" sign.');return{type:i,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){const e=new I;for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==o.ATTRIBUTE)break;const i={attField:this.extractOneOrMore(t,(e=>l(e)&&":"!==e)),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,i.attValue=this.extractOneOrMore(t,_)),e.parse(i),this.currentLine++}return e.digest()}parseMediaAttributes(e){const t=new y(e);for(;this.currentLine<this.records.length;){const e=this.getCurrentRecord();if(e.type!==o.ATTRIBUTE)break;const i={attField:this.extractOneOrMore(e,(e=>l(e)&&":"!==e)),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,i.attValue=this.extractOneOrMore(e,_)),t.parse(i),this.currentLine++}return t.digest()}parseKey(){const e=this.getCurrentRecord();if(e.type===o.KEY){if("prompt"===e.value||"clear:"===e.value||"base64:"===e.value||"uri:"===e.value)return e.value;throw this.currentLine++,new Error("Invalid key.")}}parseZone(){const e=this.getCurrentRecord();if(e.type===o.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const i=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let n=!1;"-"===e.value[e.cur]&&(n=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:i,typedTime:r,back:n})}catch(e){break}if(0===t.length)throw new Error("Invalid zone adjustments");return this.currentLine++,t}return[]}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==o.REPEAT)break;{const i=this.extract(t,this.consumeRepeatInterval),n=this.parseTypedTime(t);e.push({repeatInterval:i,typedTimes:n}),this.currentLine++}}return e}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime))}catch(e){break}if(0===t.length)throw new Error("Invalid typed time.");return t}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:i}}parseBandWidth(){const e=[];for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==o.BANDWIDTH)break;{const i=this.extractOneOrMore(t,l);if(":"!==t.value[t.cur])throw new Error("Invalid bandwidth field.");t.cur++;const n=this.extractOneOrMore(t,a);e.push({bwtype:i,bandwidth:n}),this.currentLine++}}return e}parseVersion(){const e=this.getCurrentRecord();if(e.type!==o.VERSION)throw new Error("first sdp record must be version");const t=e.value.slice(0,this.consumeOneOrMore(e.value,0,a));if(t.length!==e.value.length)throw new Error('invalid proto version, "v='.concat(e.value,'"'));return this.currentLine++,t}parseOrigin(){const e=this.getCurrentRecord();if(e.type!==o.ORIGIN)throw new Error("second line of sdp must be origin");const t=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const n=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const r=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const s=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const c=this.extract(e,this.consumeUnicastAddress);return this.currentLine++,{username:t,sessId:i,sessVersion:n,nettype:r,addrtype:s,unicastAddress:c}}parseSessionName(){const e=this.getCurrentRecord();if(e.type===o.SESSION_NAME){const t=this.extract(e,this.consumeText);return this.currentLine++,t}}parseInformation(){const e=this.getCurrentRecord();if(e.type!==o.INFORMATION)return;const t=this.extract(e,this.consumeText);return this.currentLine++,t}parseUri(){const e=this.getCurrentRecord();if(e.type===o.URI)return this.currentLine++,e.value}parseEmail(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==o.EMAIL)break;e.push(t.value),this.currentLine++}return e}parsePhone(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==o.PHONE)break;e.push(t.value),this.currentLine++}return e}parseConnection(){const e=this.getCurrentRecord();if(e.type===o.CONNECTION){const t=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const n=this.extract(e,this.consumeAddress);return this.currentLine++,{nettype:t,addrtype:i,address:n}}}parseMedia(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeToken);this.consumeSpaceForRecord(e);let i=this.extract(e,this.consumePort);"/"===e.value[e.cur]&&(e.cur+=1,i+=this.extract(e,this.consumeInteger)),this.consumeSpaceForRecord(e);const n=[];for(n.push(this.extract(e,this.consumeToken));"/"===e.value[e.cur];)e.cur+=1,n.push(this.extract(e,this.consumeToken));if(0===n.length)throw new Error("Invalid proto");const r=this.parseFmt(e);return this.currentLine++,{mediaType:t,port:i,protos:n,fmts:r}}parseTimeFields(){const e=[];for(;this.getCurrentRecord().type===o.TIME;){const t=this.parseTime(),i=this.parseRepeat(),n=this.parseZone();e.push({time:t,repeats:i,zones:n})}return e}parseMediaDescription(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===o.MEDIA;){const t=this.parseMedia(),i=this.parseInformation(),n=this.parseConnections(),r=this.parseBandWidth(),s=this.parseKey(),o=this.parseMediaAttributes(t);e.push({media:t,information:i,connections:n,bandwidths:r,key:s,attributes:o})}return e}parseConnections(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===o.CONNECTION;)e.push(this.parseConnection());return e}parseFmt(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeToken))}catch(e){break}if(0===t.length)throw new Error("Invalid fmts");return t}extract(e,t,...i){const n=t.call(this,e.value,e.cur,...i),r=e.value.slice(e.cur,n);return e.cur=n,r}extractOneOrMore(e,t){const i=this.consumeOneOrMore(e.value,e.cur,t),n=e.value.slice(e.cur,i);return e.cur=i,n}consumeSpaceForRecord(e){if(e.value[e.cur]!==s)throw new Error("Invalid space at ".concat(e.cur,"."));e.cur+=1}}class v extends R{constructor(...e){super(...e),T(this,"attributes",void 0),T(this,"digested",!1)}extractOneOrMore(e,t,i){const n=this.consumeOneOrMore(e.attValue,e._cur,t),r=e.attValue.slice(e._cur,n),[s,o]=i||[];if("number"==typeof s&&r.length<s)throw new Error("error in length, should be more or equal than ".concat(s," characters."));if("number"==typeof o&&r.length>o)throw new Error("error in length, should be less or equal than ".concat(o," characters."));return e._cur=n,r}consumeAttributeSpace(e){if(e.attValue[e._cur]!==s)throw new Error("Invalid space at ".concat(e._cur,"."));e._cur+=1}extract(e,t,...i){if(!e.attValue)throw new Error("Nothing to extract from attValue.");const n=t.call(this,e.attValue,e._cur,...i),r=e.attValue.slice(e._cur,n);return e._cur=n,r}atEnd(e){if(!e.attValue)throw new Error;return e._cur>=e.attValue.length}peekChar(e){if(!e.attValue)throw new Error;return e.attValue[e._cur]}peek(e,t){if(!e.attValue)throw new Error;for(let i=0;i<t.length;i++)if(t[i]!==e.attValue[e._cur+i])return!1;return!0}parseIceUfrag(e){if(this.attributes.iceUfrag)throw new Error("Invalid ice-ufrag, should be only a single line if 'a=ice-ufrag'");this.attributes.iceUfrag=this.extractOneOrMore(e,E,[4,256])}parseIcePwd(e){if(this.attributes.icePwd)throw new Error("Invalid ice-pwd, should be only a single line if 'a=ice-pwd'");this.attributes.icePwd=this.extractOneOrMore(e,E,[22,256])}parseIceOptions(e){if(this.attributes.iceOptions)throw new Error("Invalid ice-options, should be only one 'ice-options' line");const t=[];for(;!this.atEnd(e);){t.push(this.extractOneOrMore(e,E));try{this.consumeAttributeSpace(e)}catch(t){if(this.atEnd(e))break;throw t}}this.attributes.iceOptions=t}parseFingerprint(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill);this.attributes.fingerprints.push({hashFunction:t,fingerprint:i})}parseExtmap(e){const t=this.extractOneOrMore(e,a);let i;"/"===this.peekChar(e)&&(this.extract(e,this.consume,"/"),i=this.extract(e,this.consumeToken)),this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,s),r=S(S({entry:parseInt(t,10)},i&&{direction:i}),{},{extensionName:n});this.peekChar(e)===s&&(this.consumeAttributeSpace(e),r.extensionAttributes=this.extract(e,this.consumeTill)),this.attributes.extmaps.push(r)}parseSetup(e){if(this.attributes.setup)throw new Error("must only be one single 'a=setup' line.");const t=this.extract(e,this.consumeTill);if("active"!==t&&"passive"!==t&&"actpass"!==t&&"holdconn"!==t)throw new Error("role must be one of 'active', 'passive', 'actpass', 'holdconn'.");this.attributes.setup=t}}class I extends v{constructor(...e){super(...e),T(this,"attributes",{unrecognized:[],groups:[],extmaps:[],fingerprints:[],identities:[]})}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"group":this.parseGroup(e);break;case"ice-lite":this.parseIceLite();break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"fingerprint":this.parseFingerprint(e);break;case"setup":this.parseSetup(e);break;case"tls-id":this.parseTlsId(e);break;case"identity":this.parseIdentity(e);break;case"extmap":this.parseExtmap(e);break;case"msid-semantic":this.parseMsidSemantic(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing session attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error")}digest(){return this.digested=!0,this.attributes}parseGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;!this.atEnd(e)&&this.peekChar(e)===s;)this.consumeAttributeSpace(e),i.push(this.extract(e,this.consumeToken));this.attributes.groups.push({semantic:t,identificationTag:i})}parseIceLite(){if(this.attributes.iceLite)throw new Error("Invalid ice-lite, should be only a single line of 'a=ice-lite'");this.attributes.iceLite=!0}parseTlsId(e){if(this.attributes.tlsId)throw new Error("must be only one tld-id line");this.attributes.tlsId=this.extractOneOrMore(e,m)}parseIdentity(e){const t=this.extractOneOrMore(e,f),i=[];for(;!this.atEnd(e)&&this.peekChar(e)===s;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.extract(e,this.consume,"=");const n=this.extractOneOrMore(e,(e=>e!==s&&_(e)));i.push({name:t,value:n})}this.attributes.identities.push({assertionValue:t,extensions:i})}parseMsidSemantic(e){this.peekChar(e)===s&&this.consumeAttributeSpace(e);const t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e)}catch(e){break}if("*"===this.peekChar(e)){this.extract(e,this.consume,"*"),t.applyForAll=!0;break}{const i=this.extract(e,this.consumeTill,s);t.identifierList.push(i)}}this.attributes.msidSemantic=t}}class y extends v{constructor(e){super(),T(this,"attributes",void 0),-1!==e.protos.indexOf("RTP")||e.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"extmap":this.parseExtmap(e);break;case"setup":this.parseSetup(e);break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"candidate":this.parseCandidate(e);break;case"remote-candidate":this.parseRemoteCandidate(e);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(e);break;case"rtpmap":this.parseRtpmap(e);break;case"ptime":this.parsePtime(e);break;case"maxptime":this.parseMaxPtime(e);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(e);break;case"ssrc":this.parseSSRC(e);break;case"fmtp":this.parseFmtp(e);break;case"rtcp-fb":this.parseRtcpFb(e);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(e);break;case"mid":this.parseMid(e);break;case"msid":this.parseMsid(e);break;case"imageattr":this.parseImageAttr(e);break;case"rid":this.parseRid(e);break;case"simulcast":this.parseSimulcast(e);break;case"sctp-port":this.parseSctpPort(e);break;case"max-message-size":this.parseMaxMessageSize(e);break;case"ssrc-group":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing media attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error")}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const o=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,"typ"),this.consumeAttributeSpace(e);const l={foundation:t,componentId:i,transport:n,priority:r,connectionAddress:o,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e," raddr")&&(this.extract(e,this.consume," raddr"),this.consumeAttributeSpace(e),l.relAddr=this.extract(e,this.consumeAddress)),this.peek(e," rport")&&(this.extract(e,this.consume," rport"),this.consumeAttributeSpace(e),l.relPort=this.extract(e,this.consumePort));this.peekChar(e)===s;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),l.extension[t]=this.extractOneOrMore(e,c)}this.attributes.candidates.push(l)}parseRemoteCandidate(e){const t=[];for(;;){const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:i,connectionAddress:n,port:r});try{this.consumeAttributeSpace(e)}catch(e){break}}this.attributes.remoteCandidatesList.push(t)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");const n={encodingName:i,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),n.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.rtpMap=n:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:n,rtcpFeedbacks:[]})}parsePtime(e){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(e,this.consumeTill)}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(e,this.consumeTill)}parseDirection(e){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=e.attField}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,":");let n;":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),n=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find((e=>e.ssrcId===parseInt(t,10)));r?r.attributes[i]=n:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[i]:n}})}parseFmtp(e){const t=this.extract(e,this.consumeTill,s);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill),n={};i.split(";").forEach((e=>{let[t,i]=e.split("=");t=t.trim();const r="string"==typeof i?i.trim():null;"string"==typeof t&&t.length>0&&(n[t]=r)}));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.fmtp={parameters:n}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:n}})}parseFmtParameters(e){const t={},i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");for(t[i]=n;";"===e.attValue[e._cur];){const i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");t[i]=n}return t}parseRtcpFb(e){let t="";t="*"===this.peekChar(e)?this.extract(e,this.consume,"*"):this.extract(e,this.consumeTill,s),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,s);let n;if("trr-int"===i)n={type:i,interval:this.extract(e,this.consumeTill)};else{const t={type:i};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===s&&(t.additional=this.extract(e,this.consumeTill))),n=t}if("*"===t)this.attributes.rtcpFeedbackWildcards.push(n);else{const e=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));e?e.rtcpFeedbacks.push(n):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[n]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0}parseRTCP(e){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t}parseMsid(e){const t={id:this.extractOneOrMore(e,l,[1,64])};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,l,[1,64])),this.attributes.msids.push(t)}parseImageAttr(e){this.attributes.imageattr.push(e.attValue)}parseRid(e){const t=this.extractOneOrMore(e,(e=>u(e)||a(e)||"_"===e||"-"===e));this.consumeAttributeSpace(e);const i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===s){if(this.consumeAttributeSpace(e),this.peek(e,"pt=")){this.extract(e,this.consume,"pt=");const t=[];for(;;){const i=this.extract(e,this.consumeToken);t.push(i);try{this.extract(e,this.consume,",")}catch(e){break}}i.payloads=t,this.peekChar(e)===s&&this.extract(e,this.consume,s)}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case"depend":{const n={type:t,rids:this.extract(e,this.consume,"=").split(",")};i.params.push(n);break}default:{const n={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),n.val=this.extract(e,this.consumeTill,";")),i.params.push(n)}}try{this.extract(e,this.consume,";")}catch(e){break}}}this.attributes.rids.push(i)}parseSimulcast(e){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill)}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken)}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);i.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:i})}}function A(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class b{constructor(){A(this,"eol",r)}print(e,t){let i="";return t&&(this.eol=t),i+=this.printVersion(e.version),i+=this.printOrigin(e.origin),i+=this.printSessionName(e.sessionName),i+=this.printInformation(e.information),i+=this.printUri(e.uri),i+=this.printEmail(e.emails),i+=this.printPhone(e.phones),i+=this.printConnection(e.connection),i+=this.printBandwidth(e.bandwidths),i+=this.printTimeFields(e.timeFields),i+=this.printKey(e.key),i+=this.printSessionAttributes(e.attributes),i+=this.printMediaDescription(e.mediaDescriptions),i}printVersion(e){return"v=".concat(e).concat(this.eol)}printOrigin(e){return"o=".concat(e.username," ").concat(e.sessId," ").concat(e.sessVersion," ").concat(e.nettype," ").concat(e.addrtype," ").concat(e.unicastAddress).concat(this.eol)}printSessionName(e){return e?"s=".concat(e).concat(this.eol):""}printInformation(e){return e?"i=".concat(e).concat(this.eol):""}printUri(e){return e?"u=".concat(e).concat(this.eol):""}printEmail(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t}printPhone(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t}printConnection(e){return e?"c=".concat(e.nettype," ").concat(e.addrtype," ").concat(e.address).concat(this.eol):""}printBandwidth(e){let t="";for(const i of e)t+="b=".concat(i.bwtype,":").concat(i.bandwidth).concat(this.eol);return t}printTimeFields(e){let t="";for(const i of e){t+="t=".concat(i.time.startTime," ").concat(i.time.startTime).concat(this.eol);for(const e of i.repeats)t+="r=".concat(e.repeatInterval," ").concat(e.typedTimes.join(" ")).concat(this.eol);i.zoneAdjustments&&(t+="z=",t+="z=".concat(i.zoneAdjustments.map((e=>"".concat(e.time," ").concat(e.back?"-":""," ").concat(e.typedTime))).join(" ")).concat(this.eol),t+=this.eol)}return t}printKey(e){return e?"k=".concat(e).concat(this.eol):""}printAttributes(e){let t="";for(const i of e)t+="a=".concat(i.attField).concat(i.attValue?":".concat(i.attValue):"").concat(this.eol);return t}printMediaDescription(e){let t="";for(const i of e)t+=this.printMedia(i.media),t+=this.printInformation(i.information),t+=this.printConnections(i.connections),t+=this.printBandwidth(i.bandwidths),t+=this.printKey(i.key),t+=this.printMediaAttributes(i);return t}printConnections(e){let t="";for(const i of e)t+=this.printConnection(i);return t}printMedia(e){return"m=".concat(e.mediaType," ").concat(e.port," ").concat(e.protos.join("/")," ").concat(e.fmts.join(" ")).concat(this.eol)}printSessionAttributes(e){return new O(this.eol).print(e)}printMediaAttributes(e){return new N(this.eol).print(e)}}class w{constructor(e){A(this,"eol",void 0),this.eol=e}printIceUfrag(e){return void 0===e?"":"a=ice-ufrag:".concat(e).concat(this.eol)}printIcePwd(e){return void 0===e?"":"a=ice-pwd:".concat(e).concat(this.eol)}printIceOptions(e){return void 0===e?"":"a=ice-options:".concat(e.join(s)).concat(this.eol)}printFingerprints(e){return e.length>0?e.map((e=>"a=fingerprint:".concat(e.hashFunction).concat(s).concat(e.fingerprint))).join(this.eol)+this.eol:""}printExtmap(e){return e.map((e=>"a=extmap:".concat(e.entry).concat(e.direction?"/".concat(e.direction):"").concat(s).concat(e.extensionName).concat(e.extensionAttributes?"".concat(s).concat(e.extensionAttributes):"").concat(this.eol))).join("")}printSetup(e){return void 0===e?"":"a=setup:".concat(e).concat(this.eol)}printUnrecognized(e){return e.map((e=>"a=".concat(e.attField).concat(e.attValue?":".concat(e.attValue):"").concat(this.eol))).join("")}}class O extends w{print(e){let t="";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized),t}printGroups(e){let t="";return e.length>0&&(t+=e.map((e=>"a=group:".concat(e.semantic).concat(e.identificationTag.map((e=>"".concat(s).concat(e))).join("")).concat(this.eol))).join("")),t}printIceLite(e){return void 0===e?"":"a=ice-lite"+this.eol}printTlsId(e){return e?"a=tls-id:".concat(e).concat(this.eol):""}printIdentity(e){return 0===e.length?"":e.map((e=>"a=identity:".concat(e.assertionValue).concat(e.extensions.map((e=>"".concat(s).concat(e.name).concat(e.value?"=".concat(e.value):"")))))).join(this.eol)+this.eol}printMsidSemantic(e){if(!e)return"";let t="a=msid-semantic:".concat(e.semantic);return e.applyForAll?t+="".concat(s,"*"):e.identifierList.length>0&&(t+=e.identifierList.map((e=>"".concat(s).concat(e)))),t+this.eol}}class N extends w{print(e){const t=e.attributes;let i="";return i+=this.printRTCP(t.rtcp),i+=this.printIceUfrag(t.iceUfrag),i+=this.printIcePwd(t.icePwd),i+=this.printIceOptions(t.iceOptions),i+=this.printCandidates(t.candidates),i+=this.printRemoteCandidatesList(t.remoteCandidatesList),i+=this.printEndOfCandidates(t.endOfCandidates),i+=this.printFingerprints(t.fingerprints),i+=this.printSetup(t.setup),i+=this.printMid(t.mid),i+=this.printExtmap(t.extmaps),i+=this.printRTPRelated(t),i+=this.printPtime(t.ptime),i+=this.printMaxPtime(t.maxPtime),i+=this.printDirection(t.direction),i+=this.printSSRCGroups(t.ssrcGroups),i+=this.printSSRC(t.ssrcs),i+=this.printRTCPMux(t.rtcpMux),i+=this.printRTCPMuxOnly(t.rtcpMuxOnly),i+=this.printRTCPRsize(t.rtcpRsize),i+=this.printMSId(t.msids),i+=this.printImageattr(t.imageattr),i+=this.printRid(t.rids),i+=this.printSimulcast(t.simulcast),i+=this.printSCTPPort(t.sctpPort),i+=this.printMaxMessageSize(t.maxMessageSize),i+=this.printUnrecognized(t.unrecognized),i}printCandidates(e){return e.map((e=>"a=candidate:".concat(e.foundation).concat(s).concat(e.componentId).concat(s).concat(e.transport).concat(s).concat(e.priority).concat(s).concat(e.connectionAddress).concat(s).concat(e.port).concat(s,"typ").concat(s).concat(e.type).concat(e.relAddr?"".concat(s,"raddr").concat(s).concat(e.relAddr):"").concat(e.relPort?"".concat(s,"rport").concat(s).concat(e.relPort):"").concat(Object.keys(e.extension).map((t=>"".concat(s).concat(t).concat(s).concat(e.extension[t]))).join("")).concat(this.eol))).join("")}printRemoteCandidatesList(e){return e.map((e=>"a=remote-candidates:".concat(e.join(s)).concat(this.eol))).join("")}printEndOfCandidates(e){return void 0===e?"":"a=end-of-candidates"+this.eol}printRTPRelated(e){if(!e.payloads)return"";const t=e.payloads;let i="";i+=e.rtcpFeedbackWildcards.map((e=>this.printRTCPFeedback("*",e))).join("");for(const e of t)i+=this.printRtpMap(e.payloadType,e.rtpMap),i+=this.printFmtp(e.payloadType,e.fmtp),i+=e.rtcpFeedbacks.map((t=>this.printRTCPFeedback(e.payloadType,t))).join("");return i}printFmtp(e,t){if(!t)return"";const i=Object.keys(t.parameters);return 1===i.length&&null===t.parameters[i[0]]?"a=fmtp:".concat(e).concat(s).concat(i[0]).concat(this.eol):"a=fmtp:".concat(e).concat(s).concat(Object.keys(t.parameters).map((e=>"".concat(e,"=").concat(t.parameters[e]))).join(";")).concat(this.eol)}printRtpMap(e,t){return t?"a=rtpmap:".concat(e).concat(s).concat(t.encodingName,"/").concat(t.clockRate).concat(t.encodingParameters?"/".concat(t.encodingParameters):"").concat(this.eol):""}printRTCPFeedback(e,t){let i="a=rtcp-fb:".concat(e).concat(s),n=t;return"trr-int"===n.type?i+="ttr-int".concat(s).concat(n.interval):(i+="".concat(n.type),n.parameter&&(i+="".concat(s).concat(n.parameter),n.additional&&(i+="".concat(s).concat(n.additional)))),i+this.eol}printPtime(e){return void 0===e?"":"a=ptime:".concat(e).concat(this.eol)}printMaxPtime(e){return void 0===e?"":"a=maxptime:".concat(e).concat(this.eol)}printDirection(e){return void 0===e?"":"a=".concat(e).concat(this.eol)}printSSRC(e){return e.map((e=>Object.keys(e.attributes).map((t=>"a=ssrc:".concat(e.ssrcId.toString(10)).concat(s).concat(t).concat(e.attributes[t]?":".concat(e.attributes[t]):"").concat(this.eol))).join(""))).join("")}printRTCPMux(e){return void 0===e?"":"a=rtcp-mux".concat(this.eol)}printRTCPMuxOnly(e){return void 0===e?"":"a=rtcp-mux-only".concat(this.eol)}printRTCPRsize(e){return void 0===e?"":"a=rtcp-rsize".concat(this.eol)}printRTCP(e){if(void 0===e)return"";let t="a=rtcp:".concat(e.port);return e.netType&&(t+="".concat(s).concat(e.netType)),e.addressType&&(t+="".concat(s).concat(e.addressType)),e.address&&(t+="".concat(s).concat(e.address)),t+this.eol}printMSId(e){return e.map((e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(s).concat(e.appdata):"").concat(this.eol))).join("")}printImageattr(e){return e.map((e=>"a=imageattr:".concat(e).concat(this.eol))).join("")}printRid(e){return e.map((e=>{let t="a=rid:".concat(e.id).concat(s).concat(e.direction);return e.payloads&&(t+="".concat(s,"pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(s).concat(e.params.map((e=>"depend"===e.type?"depend=".concat(e.rids.join(",")):"".concat(e.type,"=").concat(e.val))).join(";"))),t+this.eol})).join("")}printSimulcast(e){return void 0===e?"":"a=simulcast:".concat(e).concat(this.eol)}printSCTPPort(e){return void 0===e?"":"a=sctp-port:".concat(e).concat(this.eol)}printMaxMessageSize(e){return void 0===e?"":"a=max-message-size:".concat(e).concat(this.eol)}printMid(e){return void 0===e?"":"a=mid:".concat(e).concat(this.eol)}printSSRCGroups(e){return e.map((e=>"a=ssrc-group:".concat(e.semantic).concat(e.ssrcIds.map((e=>"".concat(s).concat(e.toString(10)))).join("")).concat(this.eol))).join("")}}function D(e){return(new C).parse(e)}function P(e,t){return(new b).print(e,t)}}},t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={exports:{}};return e[n](r,r.exports,i),r.exports}return i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i(8)})()}(jP);var GP=jP.exports;function WP(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function HP(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?WP(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):WP(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function KP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:r,filterVideoFec:s,filterAudioFec:o,filterAudioCodec:a,filterVideoCodec:c}=t,{useXR:d}=i;let l=[],h=[],u=[],p=[],_=!1,E=!1;if(GP.parse(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||_||(h=e.attributes.payloads,p=e.attributes.extmaps,_=!0),"audio"!==e.media.mediaType||E||(l=e.attributes.payloads,u=e.attributes.extmaps,E=!0))})),!p||0===h.length)throw new Error("Cannot get video capabilities from SDP.");if(!u||0===l.length)throw new Error("Cannot get audio capabilities from SDP.");return h.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"})})),l.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"})})),r&&(l=l.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),h=h.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),s&&(h=h.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),o&&(l=l.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),a&&(null==a?void 0:a.length)>0&&(l=l.filter((e=>{var t;return Lr(a).call(a,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),c&&(null==c?void 0:c.length)>0&&(h=h.filter((e=>{var t;return Lr(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),{audioCodecs:l,videoCodecs:h,audioExtensions:u,videoExtensions:p}}function YP(e){const t=GP.parse(e);let i,n;for(const e of t.mediaDescriptions){if(!i){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error("Cannot get iceUfrag or icePwd from SDP.");i={iceUfrag:t,icePwd:n}}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t})}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!i)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:i,dtlsParameters:n}}function qP(e,t){const i=[],n=e.attributes.ssrcGroups.filter((e=>"FID"===e.semantic)),r=e.attributes.ssrcGroups.find((e=>"SIM"===e.semantic)),s=e.attributes.ssrcs;if(r)r.ssrcIds.forEach((e=>{var r;const s=null===(r=n.find((t=>t.ssrcIds[0]===e)))||void 0===r?void 0:r.ssrcIds[1];i.push({ssrcId:e,rtx:t?s:void 0})}));else if(n.length>0){const e=n[0].ssrcIds[0],r=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?r:void 0})}else{if(0===s.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:s[0].ssrcId})}return i}function JP(e,t){const{cname:i}=e;let n;t&&t.ip&&"number"==typeof t.port?(n=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip,port:t.port.toString(),type:"host",extension:{}}],WC.debug("Using remote candidate from AP ".concat(t.ip,":").concat(t.port)),t.ip6&&(n.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip6,port:t.port.toString(),type:"host",extension:{}}),WC.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))):n=e.iceParameters.candidates.map((e=>({foundation:e.foundation,componentId:"1",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}})));const r={fingerprints:e.dtlsParameters.fingerprints.map((e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint})))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let o;switch(e.dtlsParameters.role){case"server":o="passive";break;case"client":o="active";break;case"auto":o="actpass"}return{dtlsParameters:r,iceParameters:s,candidates:n,rtpCapabilities:rL(e.rtpCapabilities),setup:o,cname:i}}function zP(e,t,i){const n=[],r=[];return e.forEach((e=>{let{ssrcId:s,rtx:o}=e;const a=xS(8,"track-"),c={ssrcId:s,attributes:HP({label:a,mslabel:i=i||xS(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==o){const e={ssrcId:o,attributes:HP({label:a,mslabel:i,msid:"".concat(i," ").concat(a)},t&&{cname:t})};n.push(e),r.push({semantic:"FID",ssrcIds:[s,o]})}})),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map((e=>{let{ssrcId:t}=e;return t}))}),{ssrcs:n,ssrcGroups:r}}function XP(e,t){t instanceof zA&&e.attributes.payloads.forEach((e=>{var i;const n=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!n||-1===["opus","pcmu","pcma","g722"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&"pcmu"!==n&&"pcma"!==n&&"g722"!==n&&(r.bitrate&&!Rg()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*r.bitrate))),r.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(r.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(r.sampleRate)),r.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"))}))}function QP(e){const t=e.attributes.unrecognized.findIndex((e=>"x-google-flag"===e.attField&&"conference"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}function ZP(e,t){var i;if(!(t instanceof fb&&t._encoderConfig&&-1===t._hints.indexOf(Dy.SCREEN_TRACK)))return;const n=t._encoderConfig;hA().supportMinBitrate&&n.bitrateMin&&e.attributes.payloads.forEach((e=>{var t,i;Lr(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(n.bitrateMin))})),hA().supportMinBitrate&&!Lr(i=t._hints).call(i,Dy.LOW_STREAM)&&n.bitrateMax&&e.attributes.payloads.forEach((e=>{var t,i;Lr(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(kC("X_GOOGLE_START_BITRATE")||Math.floor(n.bitrateMax)))}))}function $P(e){if("video"!==e.media.mediaType)return;const t=pg();if(t.name!==cg.SAFARI&&t.os!==ag.IOS)return;const i=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==i&&e.attributes.extmaps.splice(i,1)}function eL(e,t,i){if(!t)return;let n,r;if("video"===e.media.mediaType?(n=i.videoExtensions,r=i.videoCodecs):(n=i.audioExtensions,r=i.audioCodecs),!0===t.twcc){const t=n.find((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName));if(t){e.attributes.extmaps.find((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName))||e.attributes.extmaps.push({entry:t.entry,extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))||e.rtcpFeedbacks.push({type:"transport-cc"})}))}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}if(!0===t.remb){const t=n.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName));if(t){e.attributes.extmaps.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName))||e.attributes.extmaps.push({entry:t.entry,extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))||e.rtcpFeedbacks.push({type:"goog-remb"})}))}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"goog-remb"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}}function tL(e,t,i){if(Rg())return;if("video"!==e.media.mediaType)return;if(!(t instanceof fb))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!kC("SIMULCAST"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const n="vp8"===i?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],s=e.attributes.ssrcGroups.find((e=>"FID"===e.semantic&&e.ssrcIds[0]===r.ssrcId)),o={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let t=1;t<n;t++)e.attributes.ssrcs.push({ssrcId:r.ssrcId+t,attributes:bS(r.attributes)}),o.ssrcIds.push(r.ssrcId+t),s&&(e.attributes.ssrcs.push({ssrcId:s.ssrcIds[1]+t,attributes:bS(r.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+t,s.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(o)}async function iL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{filterRTX:i,filterVideoFec:n,filterAudioFec:r,filterAudioCodec:s,filterVideoCodec:o}=e,{useXR:a}=t,c=new RTCPeerConnection;c.addTransceiver("video",{direction:"sendonly"}),c.addTransceiver("audio",{direction:"sendonly"}),c.addTransceiver("video",{direction:"recvonly"}),c.addTransceiver("audio",{direction:"recvonly"});const d=(await c.createOffer()).sdp,l=KP(d,{filterRTX:i,filterVideoFec:n,filterAudioFec:r,filterAudioCodec:s,filterVideoCodec:o},{useXR:a},"sendonly"),h=KP(d,{filterRTX:i,filterVideoFec:n,filterAudioFec:r,filterAudioCodec:s,filterVideoCodec:o},{useXR:a},"recvonly"),u={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},p={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},_={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(nL(l,h,"videoExtensions",u,p,_),nL(l,h,"videoCodecs",u,p,_),nL(l,h,"audioExtensions",u,p,_),nL(l,h,"audioCodecs",u,p,_),kC("RAISE_H264_BASELINE_PRIORITY")){const e=_.videoCodecs.findIndex((e=>{var t,i;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"===(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])}));if(-1!==e){const t=_.videoCodecs.findIndex((e=>{var t;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())}));if(t<e){WC.debug("raising H264 baseline profile priority");const i=_.videoCodecs[e];_.videoCodecs.splice(e,1),_.videoCodecs.splice(t,0,i)}-1!==t&&(p.videoCodecs=p.videoCodecs.filter((e=>{var t,i;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]))}))),-1!==t&&kC("FILTER_SEND_H264_BASELINE")&&(u.videoCodecs=u.videoCodecs.filter((e=>{var t,i;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]))})))}}try{c.close()}catch(e){}return{send:u,recv:p,sendrecv:_}}function nL(e,t,i,n,r,s){if("videoExtensions"===i||"audioExtensions"===i){const o=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return o.push(i),!0}))?s[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===o.indexOf(t)&&r[i].push(e)}))}if("videoCodecs"===i||"audioCodecs"===i){const o=[];return e[i].forEach((e=>{t[i].some(((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return o.push(i),!0}))?s[i].push(e):n[i].push(e)})),void t[i].forEach(((e,t)=>{-1===o.indexOf(t)&&r[i].push(e)}))}}function rL(e){const{send:t,recv:i,sendrecv:n}=e;if(!n){if(!t||!i)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:i}}let r,s;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...n.audioCodecs],r.videoCodecs=[...t.videoCodecs,...n.videoCodecs],r.audioExtensions=[...t.audioExtensions,...n.audioExtensions],r.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):r=n,i?(s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s.audioCodecs=[...i.audioCodecs,...n.audioCodecs],s.videoCodecs=[...i.videoCodecs,...n.videoCodecs],s.audioExtensions=[...i.audioExtensions,...n.audioExtensions],s.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):s=n,{send:r,recv:s}}function sL(e){"audio"===e.media.mediaType&&e.attributes.payloads.filter((e=>{var t;return"opus"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"}))}function oL(e){e.mediaDescriptions.forEach((e=>{"video"!==e.media.mediaType&&"audio"!==e.media.mediaType||e.attributes.payloads.forEach((e=>{-1===e.rtcpFeedbacks.findIndex((e=>"rrtr"===e.type))&&e.rtcpFeedbacks.push({type:"rrtr"})}))}))}function aL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function cL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?aL(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):aL(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function dL(e){if(Array.isArray(e))return e.map((e=>e));if(!lL(e))return e;const t={};for(const i in e){const n=e[i];lL(n)||Array.isArray(n)?t[i]=dL(n):t[i]=n}return t}function lL(e){return!("object"!=typeof e||Array.isArray(e)||!e)}class hL{constructor(e){nu(this,"input",[]),nu(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}diffMean(){return 0===this.input.length?0:(this.input[this.input.length-1]-this.input[0])/this.input.length}}const uL={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},pL={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:uL,remoteCandidate:uL}},_L={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,qpSumPerFrame:0},EL={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},mL={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},fL={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};function gL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function SL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?gL(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):gL(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class TL{constructor(e,t){nu(this,"onFirstVideoReceived",void 0),nu(this,"onFirstVideoDecoded",void 0),nu(this,"onFirstAudioReceived",void 0),nu(this,"onFirstVideoDecodedTimeout",void 0),nu(this,"onFirstAudioDecoded",void 0),nu(this,"onSelectedLocalCandidateChanged",void 0),nu(this,"onSelectedRemoteCandidateChanged",void 0),nu(this,"videoIsReady",!1),nu(this,"videoIsReady2",{}),nu(this,"pc",void 0),nu(this,"options",void 0),nu(this,"intervalTimer",void 0),nu(this,"stats",dL(pL)),nu(this,"isFirstVideoReceived",{}),nu(this,"isFirstVideoDecoded",{}),nu(this,"isFirstAudioReceived",{}),nu(this,"isFirstAudioDecoded",{}),nu(this,"isFirstVideoDecodedTimeout",{}),nu(this,"lossRateWindowStats",[]),this.pc=e,this.options=t,this.intervalTimer=window.setInterval((async()=>{this.updateStats()}),this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new tg((e=>{e({local:SL({},uL),remote:SL({},uL)})}))}setVideoIsReady(e){this.videoIsReady=e}setVideoIsReady2(e,t){this.videoIsReady2[e]=t}getVideoIsReady(e){return this.videoIsReady2[e]||!1}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const t=this.lossRateWindowStats.length,i=["videoSend","audioSend","videoRecv","audioRecv"];let n=0,r=0,s=0,o=0;for(const a of i)e[a].forEach(((e,i)=>{if(!this.lossRateWindowStats[t-1][a][i]||!this.lossRateWindowStats[0][a][i])return;const c=this.lossRateWindowStats[t-1][a][i].packets-this.lossRateWindowStats[0][a][i].packets,d=this.lossRateWindowStats[t-1][a][i].packetsLost-this.lossRateWindowStats[0][a][i].packetsLost;"videoSend"===a||"audioSend"===a?(n+=c,s+=d):(r+=c,o+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d)}));e.sendPacketLossRate=n<=0||s<=0?0:s/(n+s),e.recvPacketLossRate=r<=0||o<=0?0:o/(r+o)}}function RL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function CL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?RL(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):RL(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class vL extends TL{constructor(){super(...arguments),nu(this,"_stats",pL),nu(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=dL(pL);const i=t.filter((e=>"ssrc"===e.type));this.processSSRCStats(i);const n=t.find((e=>"VideoBwe"===e.type));n&&this.processBandwidthStats(n),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth)}processSSRCStats(e){e.forEach((e=>{var t;const i=Lr(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(i?"send":"recv")){case"video_send":{const t=dL(EL);t.codec=e.googCodecName,t.adaptionChangeReason="none",e.googCpuLimitedResolution&&(t.adaptionChangeReason="cpu"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason="bandwidth"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.plisCount=Number(e.googPlisReceived),t.frameCount=Number(e.framesEncoded),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(t),this._stats.rtt=t.rttMs;break}case"video_recv":{const t=dL(_L),i=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),i){const n=i.stats,r=Date.now()-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<i.stats.framesDecodeCount&&(t.framesDecodeInterval=0)}this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:CL({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break}case"audio_recv":{const t=dL(fL);t.codec=e.googCodecName,t.outputLevel=Math.abs(Number(e.audioOutputLevel))/32767,t.decodingCNG=Number(e.googDecodingCNG),t.decodingCTN=Number(e.googDecodingCTN),t.decodingCTSG=Number(e.googDecodingCTSG),t.decodingNormal=Number(e.googDecodingNormal),t.decodingPLC=Number(e.googDecodingPLC),t.decodingPLCCNG=Number(e.googDecodingPLCCNG),t.expandRate=Number(e.googExpandRate),t.accelerateRate=Number(e.googAccelerateRate),t.preemptiveExpandRate=Number(e.googPreemptiveExpandRate),t.secondaryDecodedRate=Number(e.googSecondaryDecodedRate),t.speechExpandRate=Number(e.googSpeechExpandRate),t.preferredJitterBufferMs=Number(e.googPreferredJitterBufferMs),t.jitterBufferMs=Number(e.googJitterBufferMs),t.jitterMs=Number(e.googJitterReceived),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.receivedFrames=Number(e.googDecodingCTN)||Number(e.packetsReceived),t.droppedFrames=Number(e.googDecodingPLC)+Number(e.googDecodingPLCCNG)||Number(e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.decodingNormal>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),this._stats.audioRecv.push(t);break}case"audio_send":{const t=dL(mL);t.codec=e.googCodecName,t.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,t.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),t.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),t.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),t.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.rtt=t.rttMs,this._stats.audioSend.push(t);break}}}))}_getStats(){return new tg(((e,t)=>{this.pc.getStats(e,t)}))}statsResponsesToObjects(e){const t=[];return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t.push(i)})),t}}function IL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function yL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?IL(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):IL(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class AL extends TL{constructor(){super(...arguments),nu(this,"_stats",pL),nu(this,"report",void 0),nu(this,"lastDecodeVideoReceiverStats",new Map),nu(this,"lastVideoFramesRecv",new Map),nu(this,"lastVideoFramesSent",new Map),nu(this,"lastVideoFramesDecode",new Map),nu(this,"lastVideoJBDelay",new Map),nu(this,"lastAudioJBDelay",new Map),nu(this,"mediaBytesSent",new Map),nu(this,"mediaBytesRetransmit",new Map),nu(this,"mediaBytesTargetEncode",new Map),nu(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=dL(pL),this.report.forEach((e=>{switch(e.type){case dv.OUTBOUND:case dv.INBOUND:{const t=e.mediaType||e.kind,i=!t&&"frameWidth"in e,n=!t&&!("frameWidth"in e);e.type===dv.OUTBOUND?"audio"===t||n?this.processAudioOutboundStats(e):("video"===t||i)&&this.processVideoOutboundStats(e):e.type===dv.INBOUND&&("audio"===t||n?this.processAudioInboundStats(e):("video"===t||i)&&this.processVideoInboundStats(e));break}case dv.TRANSPORT:{const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case dv.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e)}})),this.updateSendBitrate(),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}async getSelectedCandidatePair(){const e=await this.pc.getStats(),t={local:yL({},uL),remote:yL({},uL)};return e.forEach((i=>{let n;if(i.type===dv.TRANSPORT&&(n=e.get(i.selectedCandidatePairId)),i.type===dv.CANDIDATE_PAIR&&i.selected&&(n=i),n){const i=(e,t)=>{e.type=t.type,e.id=t.id,t.address&&(e.address=t.address),t.candidateType&&(e.candidateType=t.candidateType),t.port&&(e.port=t.port),t.priority&&(e.priority=t.priority),t.protocol&&(e.protocol=t.protocol),t.relayProtocol&&(e.relayProtocol=t.relayProtocol)};if(n.localCandidateId){const r=e.get(n.localCandidateId);r&&i(t.local,r)}if(n.remoteCandidateId){const r=e.get(n.remoteCandidateId);r&&i(t.remote,r)}}})),t}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.audioSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t)}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t)}}processCandidateStats(e){let t;e.type===dv.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===dv.REMOTE_CANDIDATE&&(t=this._stats.selectedCandidatePair.remoteCandidate),t&&(t.type=e.type,t.id=e.id,e.address&&(t.address=e.address),e.candidateType&&(t.candidateType=e.candidateType),e.port&&(t.port=e.port),e.priority&&(t.priority=e.priority),e.protocol&&(t.protocol=e.protocol),e.relayProtocol&&(t.relayProtocol=e.relayProtocol),e.type===dv.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(yL({},t),yL({},this.stats.selectedCandidatePair.localCandidate)),e.type===dv.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(yL({},t),yL({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find((t=>t.ssrc===e.ssrc));t||(t=dL(fL),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,this.processAudioTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),"number"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples)}processVideoInboundStats(e){let t=this._stats.videoRecv.find((t=>t.ssrc===e.ssrc));t||(t=dL(_L),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay;const i=this.lastDecodeVideoReceiverStats.get(t.ssrc),n=this.lastVideoFramesDecode.get(t.ssrc),r=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const e=t.decodedFrame?t.decodedFrame.width:0,i=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,i),this.isFirstVideoDecoded[t.ssrc]=!0}if(i){const n=i.stats,s=r-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&s>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=s,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<n.framesDecodeCount&&(t.framesDecodeInterval=0),e.framesDecoded&&e.qpSum&&(i.stats.framesDecodeCount>e.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-i.qpSum)/(e.framesDecoded-i.stats.framesDecodeCount))}n&&r-n.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-n.count)/((r-n.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,rate:t.decodeFrameRate})):n?t.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,rate:0}),e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:yL({},t),lts:i?i.lts:Date.now(),qpSum:e.qpSum})}processVideoOutboundStats(e){let t=this._stats.videoSend.find((t=>t.ssrc===e.ssrc));t||(t=dL(EL),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{const t=new hL(10);t.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,t)}if(void 0!==e.retransmittedBytesSent){const t=this.mediaBytesRetransmit.get(e.ssrc);if(t)t.add(e.retransmittedBytesSent);else{const t=new hL(10);t.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,t)}}if(e.totalEncodedBytesTarget){const t=this.mediaBytesTargetEncode.get(e.ssrc);if(t)t.add(e.totalEncodedBytesTarget);else{const t=new hL(10);t.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,t)}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,e.totalEncodeTime&&e.framesEncoded){const i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const n=e.framesEncoded-i.lastFrameCount,r=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*r/n}}if(e.framesEncoded&&e.qpSum){const i=this.lastEncoderMs.get(e.ssrc);!i||i.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-i.lastQpSum)/(e.framesEncoded-i.lastFrameCount)}if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,dv.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find((t=>t.ssrc===e.ssrc));if(t||(t=dL(mL),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,dv.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}findRemoteStatsId(e,t){var i;const n=Array.from(Pv(i=this.report).call(i)).find((i=>i.type===t&&i.ssrc===e));return n?n.id:null}processVideoMediaSource(e,t){const i=this.report.get(e);i&&i.width&&i.height&&i.framesPerSecond&&(t.inputFrame={width:i.width,height:i.height,frameRate:i.framesPerSecond})}processAudioMediaSource(e,t){const i=this.report.get(e);i&&(t.inputLevel=i.audioLevel)}processVideoTrackSenderStats(e,t,i){var n,r,s,o;const a=t?this.report.get(t):void 0,c=null!==(n=null==a?void 0:a.framesSent)&&void 0!==n?n:e.framesSent;if("number"!=typeof c)return;let d=null!==(r=null==a?void 0:a.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(s=null==a?void 0:a.frameHeight)&&void 0!==s?s:e.frameHeight,h=null!==(o=null==a?void 0:a.framesPerSecond)&&void 0!==o?o:e.framesPerSecond;if("number"==typeof d&&"number"==typeof l||(d=0,l=0),null==h){const e=Date.now(),t=this.lastVideoFramesSent.get(i.ssrc);t&&e-t.lts>=800?(h=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:h})):t?h=t.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:0})}i.sentFrame={width:d,height:l,frameRate:Math.max(0,h)}}processVideoTrackReceiverStats(e,t,i){var n,r,s,o,a;const c=t?this.report.get(t):void 0,d=null!==(n=null==c?void 0:c.framesReceived)&&void 0!==n?n:e.framesReceived,l=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,h=null!==(s=null==c?void 0:c.frameHeight)&&void 0!==s?s:e.frameHeight,u=null!==(o=null==c?void 0:c.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if("number"==typeof d){const e=this.lastVideoFramesRecv.get(i.ssrc),t=Date.now();i.framesReceivedCount=d;let n=0;e&&t-e.lts>=800?(n=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:n})):e?n=e.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:0}),i.receivedFrame={width:l||0,height:h||0,frameRate:n||0},i.decodedFrame={width:l||0,height:h||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:h||0,frameRate:i.decodeFrameRate||0}}if(u&&p){const e=this.lastVideoJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=p-e.jitterBufferEmittedCount;n>0&&(t=1e3*(u-e.jitterBufferDelay)/n),i.jitterBufferMs=t,i.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:u,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs})}}processAudioTrackSenderStats(e,t,i){var n,r,s,o;const a=t?this.report.get(t):void 0,c=null!==(n=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==n?n:0,d=null!==(s=null!==(o=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==o?o:e.echoReturnLossEnhancement)&&void 0!==s?s:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,i){var n,r,s,o,a,c,d;const l=t?this.report.get(t):void 0,h=null!==(n=null==l?void 0:l.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,u=null!==(r=null==l?void 0:l.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,p=null!==(s=null==l?void 0:l.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,_=null!==(o=null==l?void 0:l.jitterBufferEmittedCount)&&void 0!==o?o:e.jitterBufferEmittedCount,E=null!==(a=null==l?void 0:l.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,m=null!==(c=null==l?void 0:l.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,f=null!==(d=null==l?void 0:l.concealedSamples)&&void 0!==d?d:e.concealedSamples;if(h&&u&&(i.accelerateRate=h/u),p&&_){const e=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=_-e.jitterBufferEmittedCount;n>0&&(t=1e3*(p-e.jitterBufferDelay)/n),i.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:p,jitterBufferEmittedCount:_,jitterBufferMs:i.jitterBufferMs})}i.outputLevel=E;let g=1920;m&&u&&(g=u/m/50,i.receivedFrames=Math.round(u/g)),f&&(i.droppedFrames=Math.round(f/g))}processRemoteInboundStats(e,t){const i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime),i.jitter&&(t.jitterMs=1e3*i.jitter),i.timestamp&&(t.timestamp=i.timestamp))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return"";const i=t.mimeType.match(/\/(.*)$/);return i&&i[1]?i[1]:""}updateSendBitrate(){let e=0,t=null,i=null;this.mediaBytesSent.forEach((t=>{e+=t.diffMean()})),this.mediaBytesRetransmit.forEach((e=>{t=null===t?e.diffMean():t+e.diffMean()})),this.mediaBytesTargetEncode.forEach((e=>{i=null===i?e.diffMean():i+e.diffMean()}));const n=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*n/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==i&&(this._stats.bitrate.targetEncoded=8*i/(this.options.updateInterval/1e3))}}class bL extends TL{updateStats(){return tg.resolve()}}function wL(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4;const s=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null}();return s?s<76?new vL(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new AL(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(e){return!!window.RTCStatsReport&&e.getStats()instanceof tg}(e)?new AL(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new bL(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r})}function OL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function NL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?OL(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):OL(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class DL extends NI{get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}constructor(e,t){super(e,t),nu(this,"store",void 0),nu(this,"peerConnection",void 0),nu(this,"remoteSDP",void 0),nu(this,"initialOffer",void 0),nu(this,"statsFilter",void 0),nu(this,"useRTX",!1),nu(this,"localCapabilities",void 0),nu(this,"localCandidateCount",0),nu(this,"allCandidatesReceived",!1),nu(this,"establishPromise",void 0),nu(this,"mutex",new YS("P2PConnection-mutex")),this.store=t,this.peerConnection=new RTCPeerConnection(DL.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.statsFilter=wL(this.peerConnection,kC("STATS_UPDATE_INTERVAL"),void 0,Rg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=YP(e.sdp),i=KP(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:kC("FILTER_VIDEO_FEC"),filterAudioFec:kC("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=i,this.initialOffer=e,NL(NL({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new Vg(xg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new class{constructor(e){nu(this,"sessionDesc",void 0),nu(this,"localCapabilities",void 0),nu(this,"rtpCapabilities",void 0),nu(this,"candidates",void 0),nu(this,"iceParameters",void 0),nu(this,"dtlsParameters",void 0),nu(this,"setup",void 0),nu(this,"currentMidIndex",void 0),nu(this,"cname",void 0),e=bS(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,sdkCodec:a,cname:c}=e,d=GP.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE audio video\na=msid-semantic: WMS\na=ice-lite\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:audio\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:video\n");this.rtpCapabilities=r,this.candidates=n,this.iceParameters=t,this.dtlsParameters=i,this.setup=s,this.localCapabilities=o,this.cname=c;for(let e=0;e<d.mediaDescriptions.length;e++){const o=d.mediaDescriptions[e];o.attributes.iceUfrag=t.iceUfrag,o.attributes.icePwd=t.icePwd,o.attributes.fingerprints=i.fingerprints,o.attributes.candidates=n,o.attributes.setup=s,"video"===o.media.mediaType&&(o.media.fmts=r.videoCodecs.map((e=>e.payloadType.toString(10))),o.attributes.payloads=r.videoCodecs,o.attributes.extmaps=r.videoExtensions),"audio"===o.media.mediaType&&(o.media.fmts=r.audioCodecs.map((e=>e.payloadType.toString(10))),o.attributes.payloads=r.audioCodecs,o.attributes.extmaps=r.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(o)}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1}toString(){return GP.print(this.sessionDesc)}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=zP(t,this.cname),s=this.sessionDesc.mediaDescriptions.find((t=>e===dI.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType)),o=n[0].attributes.label,a=n[0].attributes.mslabel;return s.attributes.ssrcs=s.attributes.ssrcs.concat(n),s.attributes.ssrcGroups=s.attributes.ssrcGroups.concat(r),{id:o,mslabel:a}}batchSend(e){return e.map((e=>{let{kind:t,ssrcMsg:i}=e;return this.send(t,i,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const i=[],n=[],r=[];t.attributes.ssrcs.forEach((t=>{Lr(e).call(e,t.attributes.label||"")?r.push(t):i.push(t)})),t.attributes.ssrcGroups.forEach((e=>{var t;Lr(t=r.map((e=>e.ssrcId))).call(t,e.ssrcIds[0])||n.push(e)})),t.attributes.ssrcs=i,t.attributes.ssrcGroups=n}))}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}receive(e,t,i){e.forEach(((e,t)=>{const i=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===i.kind)),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=r}))}stopReceiving(e){}updateCandidates(e){e===lI.TCP?this.candidates.forEach((e=>{-1===this.candidates.findIndex((t=>"tcp"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port))&&this.candidates.push(cL(cL({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})):this.candidates=this.candidates.filter((e=>"tcp"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=bS(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}mungRecvMediaDsec(e,t){const i=bS(e);return XP(i,t),ZP(i,t),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,i){const n=this.sessionDesc.mediaDescriptions.find((t=>e===dI.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid));if(n){const e=n.attributes.ssrcs.find((e=>e.attributes.label===t));var r;e&&(e.attributes.label=i,null===(r=e.attributes.msid)||void 0===r||r.replace(t,i))}}mungMediaDesc(e){const t=bS(e);return QP(t),function(e){const t=e.attributes.extmaps.find((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName));t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}(t),t}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const i of t.attributes.ssrcs)if(i.attributes.label===e)return[i]}}({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n.send,remoteSetup:r,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec,cname:s});const o=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}send(e,t){var i=this;return xP((function*(){const n=yield VP(i.mutex.lock());try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const n=e.map((e=>i.peerConnection.addTrack(e._mediaStreamTrack))),r=yield VP(i.peerConnection.createOffer()),s=GP.parse(r.sdp),o=e.map((e=>{const t=e._mediaStreamTrack,n=s.mediaDescriptions.find((e=>e.attributes.mid===t.kind));if(!n)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,i){const n=e.attributes.ssrcs.filter((e=>e.attributes.label===t)),r=e.attributes.ssrcGroups;if(0===n.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(r&&n.length>1){const e=r.find((e=>-1!==e.ssrcIds.indexOf(n[0].ssrcId)));return e?[{ssrcId:e.ssrcIds[0],rtx:i?e.ssrcIds[1]:void 0}]:[{ssrcId:n[0].ssrcId}]}return[{ssrcId:n[0].ssrcId}]}(n,t.id,i.useRTX)}));let a;try{a=yield o}catch(e){throw n.forEach((e=>{Tg()&&e.replaceTrack(null),i.peerConnection.removeTrack(e)})),e}const c=i.mungSendOfferSDP(r.sdp,e);i.remoteSDP.receive(e,t,a);const d=i.remoteSDP.toString();return yield VP(i.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield VP(i.applySendEncodings(n,e)),yield VP(i.peerConnection.setRemoteDescription({type:"answer",sdp:d})),e.map(((e,t)=>{const i=e._mediaStreamTrack.id;return{localSSRC:o[t],id:i}}))}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{n()}}))()}async stopSending(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")}));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{Tg()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)}));const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{id:i,mslabel:r}=this.remoteSDP.send(e,t,n),s=new tg(((t,n)=>{const s=setTimeout((()=>{n(new Error("Cannot receive track, id: ".concat(i)))}),1e4),o=n=>{const a=pg();if(("Safari"===a.name&&11===Number(a.version)||Cg())&&n.track.id!==i&&n.streams[0].id===r){var c;const r=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,i,n.track.id),this.peerConnection.removeEventListener("track",o),clearTimeout(s),void t(r)}if(n.track.id===i)return this.peerConnection.removeEventListener("track",o),clearTimeout(s),void t(n.track)};this.peerConnection.addEventListener("track",o)})),o=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const a=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(a),{track:await s,id:i}}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(i)}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")}));if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map((e=>{if(Tg()&&e.track)e.track.enabled=!1;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!1)),e.setParameters(t)}}))}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")}));if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map((async e=>{if(Tg()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!0)),await e.setParameters(t)}}));const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return xP((function*(){const i=yield VP(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(hA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===lI.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(WC.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===lI.RELAY)return;e!==lI.RELAY&&t.remoteSDP.updateCandidates(e);const i=yield VP(t.peerConnection.createOffer({iceRestart:!0}));if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const n=YP(i.sdp),{remoteIceParameters:r}=yield n.iceParameters;t.remoteSDP.restartICE(r);const s=t.remoteSDP.toString();yield VP(t.peerConnection.setLocalDescription(i)),yield VP(t.peerConnection.setRemoteDescription({type:"answer",sdp:s}))}catch(e){WC.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const e=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getSenders().filter((t=>{var i;return(null===(i=t.track)||void 0===i?void 0:i.id)===e}));1===i.length&&await this.applySendEncodings(i,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getSenders().find((e=>{var i;return(null===(i=e.track)||void 0===i?void 0:i.id)===t}));i&&await i.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new Vg(xg.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new Vg(xg.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,WC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,WC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),kC("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(e){const t={iceServers:[],sdpSemantics:"plan-b"};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(_S(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...DL.turnServerConfigToIceServers(e.turnServer.servers)),kC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...DL.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(t.iceTransportPolicy="relay")})))),t}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}async updateRtpSenderEncodings(e,t){var i;if(t||(t=this.peerConnection.getSenders().find((t=>{var i;return(null===(i=t.track)||void 0===i?void 0:i.id)===e._mediaStreamTrack.id}))),!t)return WC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!hA().supportSetRtpSenderParameters)return WC.warn("Browser not support set rtp-sender parameters");const n={},r={};if(e instanceof fb)switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced"}if(kC("DSCP_TYPE")&&kg()){var s;const e=kC("DSCP_TYPE");Lr(s=["very-low","low","medium","high"]).call(s,e)&&(r.networkPriority=e)}const o=t.getParameters(),a=null===(i=o.encodings)||void 0===i?void 0:i[0];a&&Object.assign(a,r),Object.assign(o,n),WC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(o.encodings))),await t.setParameters(o)}async applySendEncodings(e,t){try{if(!hA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];n&&r&&await this.updateRtpSenderEncodings(r,n)}}catch(e){WC.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t){const i=GP.parse(e);return t.forEach(((e,t)=>{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find((e=>e.attributes.mid===n.kind));r&&XP(r,e)})),GP.print(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map(((t,i)=>{let{id:n,mslabel:r}=t;const{kind:s}=e[i];return new tg(((e,t)=>{const i=setTimeout((()=>{t(new Error("Cannot receive track, id: ".concat(n)))}),1e4),o=t=>{const a=pg();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(s,n,t.track.id),this.peerConnection.removeEventListener("track",o),clearTimeout(i),void e({track:r,id:n})}if(t.track.id===n)return this.peerConnection.removeEventListener("track",o),clearTimeout(i),void e({track:t.track,id:n})};this.peerConnection.addEventListener("track",o)}))})),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await tg.all(t)}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(e){if(hA().supportPCSetConfiguration){const t=DL.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t)}}}function PL(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("Locking from P2PConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s)}finally{i()}},i}function LL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function kL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?LL(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):LL(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}Lv([PL,kv("design:type",Function),kv("design:paramtypes",[Object,Object,Array,Object,String,String]),kv("design:returntype",tg)],DL.prototype,"connect",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],DL.prototype,"stopSending",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[String,Array,String,Object]),kv("design:returntype",tg)],DL.prototype,"receive",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],DL.prototype,"stopReceiving",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],DL.prototype,"muteRemote",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],DL.prototype,"unmuteRemote",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],DL.prototype,"muteLocal",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],DL.prototype,"unmuteLocal",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],DL.prototype,"close",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[String,$y]),kv("design:returntype",tg)],DL.prototype,"updateEncoderConfig",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[String,$y]),kv("design:returntype",tg)],DL.prototype,"updateSendParameters",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[$y,String]),kv("design:returntype",tg)],DL.prototype,"replaceTrack",null),Lv([PL,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],DL.prototype,"getRemoteSSRC",null);const ML="9",UL=4e4;function xL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function VL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?xL(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):xL(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let FL=class e extends NI{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}constructor(t,i){super(t,i),nu(this,"store",void 0),nu(this,"peerConnection",void 0),nu(this,"remoteSDP",void 0),nu(this,"initialOffer",void 0),nu(this,"transportEventReceiver",void 0),nu(this,"statsFilter",void 0),nu(this,"useXR",kC("USE_XR")),nu(this,"localCapabilities",void 0),nu(this,"localCandidateCount",0),nu(this,"allCandidatesReceived",!1),nu(this,"dataStreamChannelMap",new Map),nu(this,"establishPromise",void 0),nu(this,"mutex",new YS("P2PConnection-mutex")),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=wL(this.peerConnection,kC("STATS_UPDATE_INTERVAL"),void 0,Rg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=YP(e.sdp),i=await iL({filterRTX:!kC("USE_PUB_RTX")&&!kC("USE_SUB_RTX"),filterVideoFec:kC("FILTER_VIDEO_FEC"),filterAudioFec:kC("FILTER_AUDIO_FEC")},{useXR:this.useXR});return this.localCapabilities=rL(i),this.initialOffer=e,VL(VL({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new Vg(xg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new class{get localCapabilities(){return bS(this._localCapabilities)}get rtpCapabilities(){return bS(this._rtpCapabilities)}get candidates(){return bS(this._candidates)}get iceParameters(){return bS(this._iceParameters)}get dtlsParameters(){return bS(this._dtlsParameters)}constructor(e){nu(this,"sessionDesc",void 0),nu(this,"_localCapabilities",void 0),nu(this,"_rtpCapabilities",void 0),nu(this,"_candidates",void 0),nu(this,"_iceParameters",void 0),nu(this,"_dtlsParameters",void 0),nu(this,"setup",void 0),nu(this,"currentMidIndex",void 0),nu(this,"cname",void 0),nu(this,"firefoxSsrcMidMap",new Map),e=bS(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,cname:a}=e,c=GP.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=ice-lite\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n");this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=o,this.setup=s,this.cname=a;const d=this.rtpCapabilities.send;for(const e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=s,"video"===e.media.mediaType&&(e.media.fmts=d.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,kC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=zP([{ssrcId:UL,rtx:kC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if("audio"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,sL(e),kC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=zP([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}preloadRemoteMedia(){const e=kC("PRELOAD_MEDIA_COUNT");this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let s=1;s<e;s++){const e=2*s+2e4,o=2*s+UL,{ssrcs:a,ssrcGroups:c}=zP([{ssrcId:e}],this.cname),{ssrcs:d,ssrcGroups:l}=zP([{ssrcId:o,rtx:kC("USE_SUB_RTX")?o+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:ML,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.videoCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:ML,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.audioCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s+1)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return GP.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:s}=zP(t,this.cname,kC("SYNC_GROUP")?i:void 0),o=this.findPreloadMediaDesc(r);if(o){if(Rg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,o.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(o);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(o,n),{mid:o.attributes.mid,needExchangeSDP:!0}}return{mid:o.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let i;return-1===t||1===t&&(Tg()||Ag())||0===t&&kC("USE_SUB_RTX")||bg()?(i=this.createOrRecycleSendMedia(e,r,s,"sendonly",n),this.updateBundleMids()):(i=bS(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),Rg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const{mediaDesc:e,needExchangeSDP:t}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:e.attributes.mid,needExchangeSDP:t}}batchSend(e){const t=e.map((e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{"0"===e.attributes.mid||Rg()||bg()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Lr(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Lr(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}receive(e,t,i,n){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}updateCandidates(e){const t=this._candidates.filter((e=>"udp"===e.transport));if(e===lI.TCP){if(0===t.length)return;if(kC("TCP_CANDIDATE_ONLY")){const e=this._candidates.filter((e=>"tcp"===e.transport));t.forEach((t=>{-1===e.findIndex((e=>e.connectionAddress===t.connectionAddress))&&e.push(kL(kL({},t),{},{foundation:"tcpcandidate",priority:Number(t.priority)-1+"",transport:"tcp",port:Number(t.port)+90+""}))})),this._candidates=e}else{const e=[];t.forEach((t=>{e.push(kL(kL({},t),{},{foundation:"tcpcandidate",priority:Number(t.priority)-1+"",transport:"tcp",port:Number(t.port)+90+""}))})),this._candidates=[...t,...e]}}else if(e===lI.RELAY){if(0!==t.length)return;{const e=this._candidates.filter((e=>"tcp"===e.transport));e.forEach((e=>{t.push(kL(kL({},e),{},{foundation:"udpcandidate",priority:Number(e.priority)+1+"",transport:"udp",port:Number(e.port)-90+""}))})),this._candidates=[...t,...e]}}else 0===t.length?(this._candidates.filter((e=>"tcp"===e.transport)).forEach((e=>{t.push(kL(kL({},e),{},{foundation:"udpcandidate",priority:Number(e.priority)+1+"",transport:"udp",port:Number(e.port)-90+""}))})),this._candidates=t):this._candidates=this._candidates.filter((e=>"tcp"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=bS(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex((i=>{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(Rg()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return n}))}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if("application"===e.media.mediaType)return{mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:ML,protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,i,n,r,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=this.localCapabilities.send;let d=[];if(o===dI.VIDEO){var l,h;if(kC("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(d=a.videoCodecs.filter((e=>{var t,i,r;return Lr(t=(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"").call(t,n)&&(null==e||null===(r=e.fmtp)||void 0===r?void 0:r.parameters["profile-level-id"])===kC("H264_PROFILE_LEVEL_ID")}))),!d||0===(null===(l=d)||void 0===l?void 0:l.length)){const e=c.videoCodecs.filter((e=>{var t,i;return Lr(t=(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"").call(t,n)}));0!==e.length&&(d=a.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(kC("USE_PUB_RTX")){const e=d.map((e=>e.payloadType.toString())),t=a.videoCodecs.filter((t=>{var i,n;return"rtx"===(null===(i=t.rtpMap)||void 0===i?void 0:i.encodingName)&&Lr(e).call(e,(null===(n=t.fmtp)||void 0===n?void 0:n.parameters.apt)||"")}));d=[...d,...t]}0===d.length&&(WC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(null===(h=a.videoCodecs[0].rtpMap)||void 0===h?void 0:h.encodingName)),d=a.videoCodecs)}else d=a.audioCodecs.filter((e=>{var t,i;return Lr(t=(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"").call(t,r)})),0===d.length&&(WC.warning("codec ".concat(r," not included in rtpCapabilities, fallback to opus")),d=a.audioCodecs.filter((e=>{var t,i;return Lr(t=(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"").call(t,"opus")})));const u=o===dI.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const p="".concat(this.currentMidIndex);let _={media:{mediaType:o,port:ML,protos:["UDP","TLS","RTP","SAVPF"],fmts:d.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:u,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:d,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(p)}};_=this.mungRecvMediaDsec(_,e,s);const E=this.findFirstClosedMedia(o);if(E){const e=this.sessionDesc.mediaDescriptions.indexOf(E);this.sessionDesc.mediaDescriptions[e]=_}else this.sessionDesc.mediaDescriptions.push(_);return _}createOrRecycleSendMedia(e,t,i,n,r){const s=this.rtpCapabilities.send,o=e===dI.VIDEO?s.videoCodecs:s.audioCodecs,a=e===dI.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:ML,protos:["UDP","TLS","RTP","SAVPF"],fmts:o.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:o,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const n=bS(e);return QP(n),XP(n,t),ZP(n,t),$P(n),eL(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=bS(e);return eL(i,t,this.localCapabilities.recv),sL(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>Rg()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}}({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:this.localCapabilities,cname:s});const o=this.remoteSDP.toString(),a=GP.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find((e=>"audio"===e.media.mediaType));c&&sL(c),this.useXR&&oL(a);const d=GP.print(a),l=this.logSDPExchange(d||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});const h=this.peerConnection.getTransceivers()[0];if(null!=h&&h.receiver&&this.tryBindTransportEvents(h.receiver),kC("PRELOAD_MEDIA_COUNT")>0){this.remoteSDP.preloadRemoteMedia();const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t)}}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return xP((function*(){const r=yield VP(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[];e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t),e._updateRtpTransceiver(t)})),Rg()&&!0===kC("SIMULCAST")&&(yield VP(n.applySimulcastForFirefox(s,e)));const o=yield VP(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(o.sdp,e,a),d=GP.parse(c),l=a.map((e=>{const t=d.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return qP(t,kC("USE_PUB_RTX"))}));let h;try{h=yield l}catch(r){h=[],n.remoteSDP.receive(e,t,i,h);const s=n.remoteSDP.toString();throw yield VP(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield VP(n.peerConnection.setRemoteDescription({type:"answer",sdp:s})),yield VP(n.stopSending(a,!0)),r}n.remoteSDP.receive(e,t,i,h);const u=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield VP(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield VP(n.applySimulcastEncodings(s,e)),yield VP(n.applySendEncodings(s,e)),null==p||p(u),yield VP(n.peerConnection.setRemoteDescription({type:"answer",sdp:u})),s.map(((e,t)=>{const i=a[t];return{localSSRC:l[t],id:i,transceiver:e}}))}catch(e){throw e instanceof Vg?e:new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);i&&"open"===i.readyState?WC.debug("[P2PConnection] Channels are already available and can be reused directly."):(i=this.peerConnection.createDataChannel("datastream-channel",{ordered:!1,maxRetransmits:kC("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)),t.forEach((e=>{e._updateOriginDataChannel(i)}));const{needExchangeSDP:n}=this.remoteSDP.sendDataChannel();if(n){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),WC.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else WC.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof Vg?e:new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return null==t||t.close(),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof Vg?e:new Vg(xg.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),WC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else WC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:o.receiver.track,id:r,transceiver:o}}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||""),await this.peerConnection.setLocalDescription(i),WC.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))}else WC.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive no need to exchange SDP."));return t.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return xP((function*(){const i=yield VP(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(hA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===lI.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(WC.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===lI.RELAY)return;t.remoteSDP.updateCandidates(e);const i=yield VP(t.peerConnection.createOffer({iceRestart:!0}));if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const n=YP(i.sdp),{remoteIceParameters:r}=yield n.iceParameters;t.remoteSDP.restartICE(r);const s=t.remoteSDP.toString(),o=t.logSDPExchange(i.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield VP(t.peerConnection.setLocalDescription(i)),null==o||o(s),yield VP(t.peerConnection.setRemoteDescription({type:"answer",sdp:s}))}catch(e){WC.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?Rg()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:VL(VL({},uL),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:VL(VL({},uL),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,WC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,WC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),kC("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(_S(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),kC("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),kC("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(i.iceTransportPolicy="relay")})))),kC("ENABLE_ENCODED_TRANSFORM")&&hA().supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(hD(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!kC("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:e,remote:t}=i.getSelectedCandidatePair();WC.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port})," )"))}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(t||(t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))),!t)return WC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return WC.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!hA().supportSetRtpSenderParameters)return WC.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n={},r={};switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced"}if(e._encoderConfig){var s;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),Lr(s=e._hints).call(s,Dy.LOW_STREAM)&&(i&&(r.maxFramerate=pD(i)),n&&n>=1&&(r.scaleResolutionDownBy=n))}if(kC("DSCP_TYPE")&&kg()){var o;const e=kC("DSCP_TYPE");Lr(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e)}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];Rg()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),WC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!hA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];r instanceof fb&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,n.sender)}}catch(e){WC.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){const n=GP.parse(e);return t.forEach(((e,t)=>{const r=i[t],s=n.mediaDescriptions.find((e=>e.attributes.mid===r));s&&(XP(s,e),tL(s,e,this.store.codec))})),GP.print(n)}mungReceiveAnswerSDP(e,t,i){const n=GP.parse(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&(i===dI.AUDIO&&"audio"===r.media.mediaType&&sL(r),this.useXR&&oL(n)),GP.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var i,n,r,s,o;const c=e[a],d=t[a];if(d instanceof fb&&!Lr(i=d._hints).call(i,Dy.LOW_STREAM)&&null!==(n=d._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Rg()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof fb&&this.isVP8Simulcast(n)){const t=e[i],r={},s={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:s.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:s.medium,scaleResolutionDownBy:4}];const o=t.sender.getParameters();await t.sender.setParameters(Object.assign(o,r))}}}isVP8Simulcast(e){var t,i,n,r,s;return!!(e instanceof fb&&kC("SIMULCAST")&&"vp8"===this.store.codec&&!Lr(t=e._hints).call(t,Dy.LOW_STREAM)&&null!==(i=e._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(kC("SDP_LOGGING"))return WC.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(hA().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}};function BL(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s)}finally{i()}},i}function jL(e,t){let i=document.createElement("video"),n=document.createElement("canvas");i.setAttribute("style","display:none"),n.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),n.width=pD(t.width),n.height=pD(t.height);const r=pD(t.framerate||15);document.body.append(i),document.body.append(n);let s=e._mediaStreamTrack;i.srcObject=new MediaStream([s]),i.play();const o=n.getContext("2d");if(!o)throw new Mv(xg.UNEXPECTED_ERROR,"can not get canvas context");const a=hA(),c=n.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0];c.canvas||(c.canvas=n),n.startCapture=()=>{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,r=n.width*t;Math.abs(r-n.height)>=2&&(WC.debug("adjust low stream resolution","".concat(n.width,"x").concat(n.height," -> ").concat(n.width,"x").concat(r)),n.height=r)}o.drawImage(i,0,0,n.width,n.height),c.requestFrame&&c.requestFrame(),s!==e._mediaStreamTrack&&(s=e._mediaStreamTrack,i.srcObject=new MediaStream([s]))},n.stopCapture=dA((()=>n.startCapture&&n.startCapture()),r);const d=c.stop;return c.stop=()=>{d.call(c),i&&(i.remove(),i.srcObject=null,i=null),n&&(n.width=0,n.remove(),n.stopCapture&&n.stopCapture(),n.startCapture=void 0,n.stopCapture=void 0,n=null),WC.debug("clean low stream renderer")},c}function GL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function WL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?GL(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):GL(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}Lv([BL,kv("design:type",Function),kv("design:paramtypes",[Object,Object,Array,Object,String,String]),kv("design:returntype",tg)],FL.prototype,"connect",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[Object,Array]),kv("design:returntype",tg)],FL.prototype,"createDataChannels",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[String,Array,String,Object]),kv("design:returntype",tg)],FL.prototype,"receive",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],FL.prototype,"batchReceive",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],FL.prototype,"stopReceiving",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],FL.prototype,"muteRemote",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],FL.prototype,"unmuteRemote",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],FL.prototype,"muteLocal",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],FL.prototype,"unmuteLocal",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],FL.prototype,"close",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[String,$y]),kv("design:returntype",tg)],FL.prototype,"updateEncoderConfig",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[String,$y]),kv("design:returntype",tg)],FL.prototype,"updateSendParameters",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[$y,String]),kv("design:returntype",tg)],FL.prototype,"replaceTrack",null),Lv([BL,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],FL.prototype,"getRemoteSSRC",null);const HL="v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0\na=msid-semantic: WMS\na=ice-lite\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 127.0.0.1\na=mid:0\n",KL="9",YL=2e4,qL=4e4;class JL{get localCapabilities(){return bS(this._localCapabilities)}get rtpCapabilities(){return bS(this._rtpCapabilities)}get candidates(){return bS(this._candidates)}get iceParameters(){return bS(this._iceParameters)}get dtlsParameters(){return bS(this._dtlsParameters)}constructor(e){nu(this,"sessionDesc",void 0),nu(this,"_localCapabilities",void 0),nu(this,"_rtpCapabilities",void 0),nu(this,"_candidates",void 0),nu(this,"_iceParameters",void 0),nu(this,"_dtlsParameters",void 0),nu(this,"setup",void 0),nu(this,"currentMidIndex",void 0),nu(this,"cname",void 0),nu(this,"firefoxSsrcMidMap",new Map),e=bS(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,cname:a}=e,c=GP.parse(HL);this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=o,this.setup=s,this.cname=a;const d=this.rtpCapabilities.send;for(const e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=s,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=d.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,kC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=zP([{ssrcId:qL,rtx:kC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if("audio"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,sL(e),kC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=zP([{ssrcId:YL}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}updateRemoteRTPCapabilities(e){const t=GP.parse(HL);this._rtpCapabilities=e;const i=this.rtpCapabilities.send;for(const e of t.mediaDescriptions){if(e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=i.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=i.videoCodecs,e.attributes.extmaps=i.videoExtensions,kC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=zP([{ssrcId:qL,rtx:kC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if("audio"===e.media.mediaType&&(e.media.fmts=i.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=i.audioCodecs,e.attributes.extmaps=i.audioExtensions,kC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=zP([{ssrcId:YL}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1}preloadRemoteMedia(e){this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let s=1;s<e;s++){const e=2*s+YL,o=2*s+qL,{ssrcs:a,ssrcGroups:c}=zP([{ssrcId:e}],this.cname),{ssrcs:d,ssrcGroups:l}=zP([{ssrcId:o,rtx:kC("USE_SUB_RTX")?o+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:KL,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.videoCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s-1)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:KL,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.audioCodecs.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return GP.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:s}=zP(t,this.cname,kC("SYNC_GROUP")?i:void 0),o=this.findPreloadMediaDesc(r);if(o){if(Rg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,o.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(o);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(o,n),{mid:o.attributes.mid,needExchangeSDP:!0}}return{mid:o.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let i;return-1===t||Tg()||Cg()||Ag()||0===t&&kC("USE_SUB_RTX")?(i=this.createOrRecycleSendMedia(e,r,s,"sendonly",n),this.updateBundleMids()):(i=bS(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),Rg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}batchSend(e){const t=e.map((e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)})),i=[];let n=!1;return t.forEach((e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t)})),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{"0"===e.attributes.mid||Rg()||Tg()||Cg()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Lr(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Lr(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}receive(e,t,i,n){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}updateCandidates(e){e===lI.TCP?this._candidates.forEach((e=>{-1===this._candidates.findIndex((t=>"tcp"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port))&&this._candidates.push(WL(WL({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})):this._candidates=this._candidates.filter((e=>"tcp"!==e.transport));for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}restartICE(e){e=bS(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex((i=>{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(Rg()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return n}))}createOrRecycleRecvMedia(e,t,i,n,r,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=this.localCapabilities.send;let d=[];if(o===dI.VIDEO){var l,h;if(kC("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(d=a.videoCodecs.filter((e=>{var t,i,r;return Lr(t=(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"").call(t,n)&&(null==e||null===(r=e.fmtp)||void 0===r?void 0:r.parameters["profile-level-id"])===kC("H264_PROFILE_LEVEL_ID")}))),!d||0===(null===(l=d)||void 0===l?void 0:l.length)){const e=c.videoCodecs.filter((e=>{var t,i;return Lr(t=(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"").call(t,n)}));0!==e.length&&(d=a.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(kC("USE_PUB_RTX")){const e=d.map((e=>e.payloadType.toString())),t=a.videoCodecs.filter((t=>{var i,n;return"rtx"===(null===(i=t.rtpMap)||void 0===i?void 0:i.encodingName)&&Lr(e).call(e,(null===(n=t.fmtp)||void 0===n?void 0:n.parameters.apt)||"")}));d=[...d,...t]}0===d.length&&(WC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(null===(h=a.videoCodecs[0].rtpMap)||void 0===h?void 0:h.encodingName)),d=a.videoCodecs)}else d=a.audioCodecs.filter((e=>{var t,i;return Lr(t=(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"").call(t,r)})),0===d.length&&(WC.warning("codec ".concat(r," not included in rtpCapabilities, fallback to opus")),d=a.audioCodecs.filter((e=>{var t,i;return Lr(t=(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"").call(t,"opus")})));const u=o===dI.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const p="".concat(this.currentMidIndex);let _={media:{mediaType:o,port:KL,protos:["UDP","TLS","RTP","SAVPF"],fmts:d.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:u,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:d,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(p)}};_=this.mungRecvMediaDsec(_,e,s);const E=this.findFirstClosedMedia(o);if(E){const e=this.sessionDesc.mediaDescriptions.indexOf(E);this.sessionDesc.mediaDescriptions[e]=_}else this.sessionDesc.mediaDescriptions.push(_);return _}createOrRecycleSendMedia(e,t,i,n,r){const s=this.rtpCapabilities.send,o=e===dI.VIDEO?s.videoCodecs:s.audioCodecs,a=e===dI.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:KL,protos:["UDP","TLS","RTP","SAVPF"],fmts:o.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:o,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,i){const n=bS(e);return QP(n),XP(n,t),ZP(n,t),$P(n),eL(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=bS(e);return eL(i,t,this.localCapabilities.recv),sL(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>Rg()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var i;return(null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}}function zL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function XL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?zL(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):zL(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class QL extends NI{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}constructor(e,t,i){super(e,t),nu(this,"store",void 0),nu(this,"peerConnection",void 0),nu(this,"remoteSDP",void 0),nu(this,"initialOffer",void 0),nu(this,"transportEventReceiver",void 0),nu(this,"statsFilter",void 0),nu(this,"useXR",kC("USE_XR")),nu(this,"localCapabilities",void 0),nu(this,"localCandidateCount",0),nu(this,"allCandidatesReceived",!1),nu(this,"dataStreamChannelMap",new Map),nu(this,"establishPromise",void 0),nu(this,"mutex",new YS("NVExtentionsConnection-mutex")),nu(this,"rtcMedia",void 0),this.store=t,this.peerConnection=i,this.statsFilter=wL(this.peerConnection,kC("STATS_UPDATE_INTERVAL"),void 0,Rg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(e){try{const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=YP(e.sdp),i=await iL({filterRTX:!kC("USE_PUB_RTX")&&!kC("USE_SUB_RTX"),filterVideoFec:kC("FILTER_VIDEO_FEC"),filterAudioFec:kC("FILTER_AUDIO_FEC")},{useXR:this.useXR});return this.localCapabilities=i,this.initialOffer=e,XL(XL({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new Mv(xg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnection without initial offer.");this.remoteSDP=new JL({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:rL(this.localCapabilities),cname:s});const o=this.remoteSDP.toString(),a=GP.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find((e=>"audio"===e.media.mediaType));c&&sL(c),this.useXR&&oL(a);const d=GP.print(a),l=this.logSDPExchange(d||"","offer","local","connect");await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new Mv(xg.EXCHANGE_SDP_FAILED,"NV.connect failed; ".concat(e.toString()))}}async updateRemoteConnect(e){var t,i,n;null===(t=this.remoteSDP)||void 0===t||t.updateRemoteRTPCapabilities(e),null===(i=this.remoteSDP)||void 0===i||i.preloadRemoteMedia(2);const r=null===(n=this.remoteSDP)||void 0===n?void 0:n.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:r});const s=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(s),WC.debug("[NVExtentionsConnection] updateRemoteRTPCapabilities by exchanging SDP.")}send(e,t,i){var n=this;return xP((function*(){const r=yield VP(n.mutex.lock("From NVExtentionsConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.send before remote SDP created");const s=[];e.forEach((e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t)})),Rg()&&!0===kC("SIMULCAST")&&(yield VP(n.applySimulcastForFirefox(s,e)));const o=yield VP(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(o.sdp,e,a),d=GP.parse(c),l=a.map((e=>{const t=d.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return qP(t,kC("USE_PUB_RTX"))}));let h;try{h=yield l}catch(r){h=[],n.remoteSDP.receive(e,t,i,h);const s=n.remoteSDP.toString();throw yield VP(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield VP(n.peerConnection.setRemoteDescription({type:"answer",sdp:s})),yield VP(n.stopSending(a,!0)),r}n.remoteSDP.receive(e,t,i,h);const u=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield VP(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield VP(n.applySimulcastEncodings(s,e)),yield VP(n.applySendEncodings(s,e)),null==p||p(u),yield VP(n.peerConnection.setRemoteDescription({type:"answer",sdp:u})),s.map(((e,t)=>{const i=a[t];return{localSSRC:l[t],id:i,transceiver:e}}))}catch(e){throw e instanceof Mv?e:new Mv(xg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From NVExtentionsConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call NVExtentionsConnection.stopSending.");t.map((e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Mv(xg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);return i&&"open"===i.readyState?WC.debug("[P2PConnection] Channels are already available and can be reused directly."):(i=this.peerConnection.createDataChannel("datastream-channel",{ordered:!1,maxRetransmits:kC("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)),void t.forEach((e=>{e._updateOriginDataChannel(i)}))}catch(e){throw e instanceof Mv?e:new Mv(xg.DATACHANNEL_FAILED,"NVExtentionsConnection.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return null==t||t.close(),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof Mv?e:new Mv(xg.DATACHANNEL_FAILED,"NVExtentionsConnection.stopDataChannels failed; ".concat(e.toString()))}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),WC.debug("[NVExtentionsConnection] receive ".concat(e," by exchanging SDP."))}else WC.debug("[NVExtentionsConnection] receive ".concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:o.receiver.track,id:r}}catch(e){throw new Mv(xg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||""),await this.peerConnection.setLocalDescription(i),WC.debug("[NVExtentionsConnection] batchReceive by exchanging SDP.")}else WC.debug("[NVExtentionsConnection] batchReceive no need to exchange SDP.");return t.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e}}))}catch(e){throw new Mv(xg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new Mv(xg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new Mv(xg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new Mv(xg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Mv(xg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Mv(xg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return xP((function*(){const i=yield VP(t.mutex.lock("From NVExtentionsConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(hA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===lI.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(WC.debug("restartICE change iceTransportPolicy from [".concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}else if(e===lI.RELAY)return;e!==lI.RELAY&&t.remoteSDP.updateCandidates(e);const i=yield VP(t.peerConnection.createOffer({iceRestart:!0}));if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const n=YP(i.sdp),{remoteIceParameters:r}=yield n.iceParameters;t.remoteSDP.restartICE(r);const s=t.remoteSDP.toString(),o=t.logSDPExchange(i.sdp||"","offer","local","restartICE");yield VP(t.peerConnection.setLocalDescription(i)),null==o||o(s),yield VP(t.peerConnection.setRemoteDescription({type:"answer",sdp:s}))}catch(e){WC.warning("restart ICE failed, abort operation",e)}finally{i()}}))()}close(){var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Mv(xg.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?Rg()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}getP2PConnectionParams(){var e;if(null===(e=this.peerConnection.currentLocalDescription)||void 0===e||!e.sdp||!this.localCapabilities)throw new Error;return XL(XL({},YP(this.peerConnection.currentLocalDescription.sdp)),{},{rtpCapabilities:this.localCapabilities})}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,WC.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,WC.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),kC("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(_S(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...QL.turnServerConfigToIceServers(e.turnServer.servers)),kC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...QL.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),kC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(t.iceTransportPolicy="relay")})))),t}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(hD(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!kC("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}async applySendEncodings(e,t){try{if(!hA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let l=0;l<e.length;l++){const h=e[l],u=t[l];if(u&&u instanceof fb){var i,n,r;if(this.isVP8Simulcast(u))continue;const e={},t={};switch(u._optimizationMode){case"motion":e.degradationPreference="maintain-framerate";break;case"detail":e.degradationPreference="maintain-resolution";break;default:e.degradationPreference="balanced"}var s,o,a,c;if(null!==(i=u._encoderConfig)&&void 0!==i&&i.bitrateMax&&(t.maxBitrate=1e3*(null===(s=u._encoderConfig)||void 0===s?void 0:s.bitrateMax)),Lr(n=u._hints).call(n,Dy.LOW_STREAM)&&(null!==(o=u._encoderConfig)&&void 0!==o&&o.frameRate&&(t.maxFramerate=pD(u._encoderConfig.frameRate)),null!==(a=u._encoderConfig)&&void 0!==a&&a.scaleResolutionDownBy&&(null===(c=u._encoderConfig)||void 0===c?void 0:c.scaleResolutionDownBy)>1&&(t.scaleResolutionDownBy=u._encoderConfig.scaleResolutionDownBy)),kC("DSCP_TYPE")&&kg()){var d;const e=kC("DSCP_TYPE");Lr(d=["very-low","low","medium","high"]).call(d,e)&&(t.networkPriority=e)}const l=h.sender.getParameters(),p=null===(r=l.encodings)||void 0===r?void 0:r[0];Rg()&&!p&&(e.encodings=[t]),p&&Object.assign(p,t),Object.assign(l,e),await h.sender.setParameters(l)}}}catch(e){WC.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(e,t,i){const n=GP.parse(e);return t.forEach(((e,t)=>{const r=i[t],s=n.mediaDescriptions.find((e=>e.attributes.mid===r));s&&(XP(s,e),tL(s,e,this.store.codec))})),GP.print(n)}mungReceiveAnswerSDP(e,t,i){const n=GP.parse(e),r=n.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&i===dI.AUDIO&&"audio"===r.media.mediaType&&sL(r),this.useXR&&oL(n),GP.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var i,n,r,s,o;const c=e[a],d=t[a];if(d instanceof fb&&!Lr(i=d._hints).call(i,Dy.LOW_STREAM)&&null!==(n=d._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Rg()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof fb&&this.isVP8Simulcast(n)){const t=e[i],r={},s={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:s.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:s.medium,scaleResolutionDownBy:4}];const o=t.sender.getParameters();await t.sender.setParameters(Object.assign(o,r))}}}isVP8Simulcast(e){var t,i,n,r,s;return!!(e instanceof fb&&kC("SIMULCAST")&&"vp8"===this.store.codec&&!Lr(t=e._hints).call(t,Dy.LOW_STREAM)&&null!==(i=e._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(kC("SDP_LOGGING"))return WC.upload("exchanging ".concat(i," ").concat(t," SDP during NVExtentionsConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(e){if(hA().supportPCSetConfiguration){const t=QL.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t)}}}function ZL(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From NVExtentionsConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s)}finally{i()}},i}function $L(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=BP,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new ek(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function ek(e){function t(e){if(Object(e)!==e)return tg.reject(new TypeError(e+" is not an object."));var t=e.done;return tg.resolve(e.value).then((function(e){return{value:e,done:t}}))}return ek=function(e){this.s=e,this.n=e.next},ek.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?tg.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?tg.reject(e):t(i.apply(this.s,arguments))}},new ek(e)}Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[Object,Object,Array,Object,String,String]),kv("design:returntype",tg)],QL.prototype,"connect",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],QL.prototype,"updateRemoteConnect",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[Object,Array]),kv("design:returntype",tg)],QL.prototype,"createDataChannels",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[String,Array,String,Object]),kv("design:returntype",tg)],QL.prototype,"receive",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],QL.prototype,"batchReceive",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],QL.prototype,"stopReceiving",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],QL.prototype,"muteRemote",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],QL.prototype,"unmuteRemote",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],QL.prototype,"muteLocal",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],QL.prototype,"unmuteLocal",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],QL.prototype,"close",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[String,$y]),kv("design:returntype",tg)],QL.prototype,"updateEncoderConfig",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[String,$y]),kv("design:returntype",tg)],QL.prototype,"updateSendParameters",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[$y,String]),kv("design:returntype",tg)],QL.prototype,"replaceTrack",null),Lv([ZL,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],QL.prototype,"getRemoteSSRC",null);class tk extends NI{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}constructor(e,t){super(e,t),nu(this,"store",void 0),nu(this,"peerConnection",void 0),nu(this,"cname",void 0),nu(this,"mutex",new YS("DataChannelConnection-mutex")),nu(this,"dataChannel",void 0),nu(this,"_p2pConnection",void 0),nu(this,"establishPromise",void 0),nu(this,"_nvMedia",void 0),this.store=t,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(tk.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new QL(e,t,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}async establish(){var e;const t=null===(e=this._nvMedia)||void 0===e?void 0:e.getLocalRtpCapabilities();return await this._p2pConnection.establish(t)}getP2PConnectionParams(){return this._p2pConnection.getP2PConnectionParams()}async connect(e,t,i,n,r,s){return this.cname=s,await this._p2pConnection.connect(e,t,i,n,r,s),await new tg(((e,t)=>{const n=setTimeout((()=>{this.closeSignal(),t(new Mv(xg.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(i))))}),2e3);this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(n),void e()},this.dataChannel.onerror=e=>{this.closeSignal(),t(e)}})),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}send(e,t,i){var n=this;return xP((function*(){const r=yield VP(n.mutex.lock("From DataChannelConnection.send"));try{return yield*FP($L(n._p2pConnection.send(e,t,i)))}finally{r()}}))()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t)}async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e)}async receive(e,t,i,n){return this._nvMedia?(WC.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(WC.debug("[DataChannelConnection] receive ".concat(e," by WebRTC.")),await this._p2pConnection.receive(e,t,i,n))}async batchReceive(e){return[...await this._p2pConnection.batchReceive(e)]}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e)}async muteRemote(e){return await this._p2pConnection.muteRemote(e)}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e)}async muteLocal(e){return await this._p2pConnection.muteLocal(e)}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e)}restartICE(e){var t=this;return xP((function*(){return yield*FP($L(t._p2pConnection.restartICE(e)))}))()}close(){var e;null===(e=this._nvMedia)||void 0===e||e.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e)}updateRemoteConnect(e){var t;null===(t=this._nvMedia)||void 0===t||t.setRemoteRtpCapabilities(e),this._p2pConnection.updateRemoteConnect(e)}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t)}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t)}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t)}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t)}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e)}logSDPExchange(e,t,i,n){if(kC("SDP_LOGGING"))return WC.upload("exchanging ".concat(i," ").concat(t," SDP during DataChannelConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(_S(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...tk.turnServerConfigToIceServers(e.turnServer.servers)),kC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...tk.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),kC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(t.iceTransportPolicy="relay")})))),t}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(hD(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!kC("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null===(t=this.onICEConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoDecoded=(e,t,i)=>{var n;return null===(n=this.onFirstVideoDecoded)||void 0===n?void 0:n.call(this,e,t,i)},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedLocalCandidateChanged)||void 0===i?void 0:i.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i?void 0:i.call(this,e,t)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0}setConfiguration(e){this._p2pConnection.setConfiguration(e)}}function ik(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From DataChannelConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s)}finally{i()}},i}function nk(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function rk(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?nk(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):nk(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}Lv([ik,kv("design:type",Function),kv("design:paramtypes",[Object,Object,Array,Object,String,String]),kv("design:returntype",tg)],tk.prototype,"connect",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[Object,Array]),kv("design:returntype",tg)],tk.prototype,"createDataChannels",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[String,Array,String,Object]),kv("design:returntype",tg)],tk.prototype,"receive",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],tk.prototype,"stopReceiving",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],tk.prototype,"muteRemote",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],tk.prototype,"unmuteRemote",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],tk.prototype,"muteLocal",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],tk.prototype,"unmuteLocal",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],tk.prototype,"close",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[String,$y]),kv("design:returntype",tg)],tk.prototype,"updateEncoderConfig",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[String,$y]),kv("design:returntype",tg)],tk.prototype,"updateSendParameters",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[$y,String]),kv("design:returntype",tg)],tk.prototype,"replaceTrack",null),Lv([ik,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],tk.prototype,"getRemoteSSRC",null);class sk extends iS{constructor(){super(),nu(this,"uplinkStatsUploadInterval",void 0),nu(this,"uplinkRelatedStatsUploadInterval",void 0),nu(this,"uplinkDenoiserStatsUploadInterval",void 0),nu(this,"transportStatsUploadInterval",void 0),nu(this,"uplinkExtensionStatsUploadInterval",void 0),nu(this,"downlinkExtensionStatsUploadInterval",void 0),nu(this,"extensionUsageStatsUploadInterval",void 0),nu(this,"downlinkStatsUploadInterval",void 0),nu(this,"downlinkRelatedStatsUploadInterval",void 0),nu(this,"lastStats",void 0),nu(this,"uploadUnplinkStarted",!1),nu(this,"uploadDownlinkStarted",!1),nu(this,"uploadTransportStarted",!1),nu(this,"uploadExtensionUsageStarted",!1),nu(this,"requestStats",void 0),nu(this,"requestTransportStats",void 0),nu(this,"requestLocalMedia",void 0),nu(this,"requestRemoteMedia",void 0),nu(this,"requestAllTracks",void 0),nu(this,"requestVideoIsReady",void 0),nu(this,"requestUpload",void 0)}startUploadTransportStats(e){this.uploadTransportStarted||(this.uploadTransportStarted=!0,this.transportStatsUploadInterval&&window.clearInterval(this.transportStatsUploadInterval),this.transportStatsUploadInterval=window.setInterval((()=>{var t;const i=null===(t=this.requestStats)||void 0===t?void 0:t.call(this);if(i){const t=ED(i);if(e){var n;const e=null===(n=this.requestStats)||void 0===n?void 0:n.call(this,!0);if(e){const i=ED(e);t.connectionType+=i.connectionType<<3}t.connectionType+=110}else t.connectionType+=100;AS((()=>{var e;null===(e=this.requestUpload)||void 0===e||e.call(this,gv.TRANSPORT_STATS,t)}))}}),1e3))}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.extensionUsageStatsUploadInterval&&window.clearInterval(this.extensionUsageStatsUploadInterval);const e=new Map;this.extensionUsageStatsUploadInterval=window.setInterval((async()=>{var t,i,n;const r=Date.now(),s={connectionInterval:kC("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:r};let o=[];const a=(null===(t=this.requestAllTracks)||void 0===t?void 0:t.call(this))||[];for(const e of a)!e.muted&&e.enabled&&(o=o.concat(await e.getProcessorUsage()));const c=(null===(i=this.requestRemoteMedia)||void 0===i?void 0:i.call(this))||[];for(const[e,t]of c)t.has(dI.VIDEO)&&e.videoTrack&&(o=o.concat(await e.videoTrack.getProcessorUsage())),t.has(dI.AUDIO)&&e.audioTrack&&(o=o.concat(await e.audioTrack.getProcessorUsage()));if(0===o.length)return;s.details=function(e,t){const i={};for(const{id:o,value:a,level:c,direction:d}of e){var n;const e=null!==(n=t.get(o))&&void 0!==n?n:0,l=2===a?e+kC("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:e;var r,s;t.set(o,l),i[o]?(2===a&&(i[o].value=a),c>i[o].level&&(i[o].level=c),"remote"===d&&(i[o].remoteUidCount+=1),i[o].totalTs=null!==(r=t.get(o))&&void 0!==r?r:0):i[o]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(s=t.get(o))&&void 0!==s?s:0}}return Object.keys(i).map((e=>{const{level:t,value:n,totalTs:r}=i[e];return{id:e,level:t,value:n,totalTs:r}}))}(o,e);const d=Date.now(),l=d>r?d:r+1;null===(n=this.requestUpload)||void 0===n||n.call(this,gv.EXTENSION_USAGE_STATS,{usageStats:s,sendTs:l})}),kC("EXTENSION_USAGE_UPLOAD_INTERVAL"))}startUploadUplinkStats(){this.uploadUnplinkStarted||(this.uploadUnplinkStarted=!0,this.uplinkStatsUploadInterval&&window.clearInterval(this.uplinkStatsUploadInterval),this.uplinkStatsUploadInterval=window.setInterval((()=>{var e;const t=null===(e=this.requestStats)||void 0===e?void 0:e.call(this);t&&(this.uploadUplinkStats(t),this.lastStats=t)}),3e3),this.uplinkRelatedStatsUploadInterval&&window.clearInterval(this.uplinkRelatedStatsUploadInterval),this.uplinkRelatedStatsUploadInterval=window.setInterval((()=>{var e;const t=null===(e=this.requestStats)||void 0===e?void 0:e.call(this);t&&this.uploadRelatedUplinkStats(t,this.lastStats),this.lastStats=t}),1e3),this.uplinkDenoiserStatsUploadInterval&&window.clearInterval(this.uplinkDenoiserStatsUploadInterval),this.uplinkDenoiserStatsUploadInterval=window.setInterval((()=>{var e;const t=null===(e=this.requestAllTracks)||void 0===e?void 0:e.call(this);t&&this.uploadDenoiserStats(t)}),2e3),this.uplinkExtensionStatsUploadInterval&&window.clearInterval(this.uplinkExtensionStatsUploadInterval),this.uplinkExtensionStatsUploadInterval=window.setInterval((()=>{var e;const t=null===(e=this.requestAllTracks)||void 0===e?void 0:e.call(this);t&&this.uploadExtensionStats(t)}),2e3))}uploadUplinkStats(e){var t;((null===(t=this.requestLocalMedia)||void 0===t?void 0:t.call(this))||[]).forEach((t=>{let[i,{track:n,ssrcs:r}]=t;switch(i){case uI.LocalVideoLowTrack:case uI.LocalVideoTrack:{const t=function(e,t,i){var n;const r=t.videoSend.find((t=>t.ssrc===e));if(!r)return null;const s={id:xS(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:r.ssrc.toString()};switch(s.A_vstd=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?"1":"0",r.sentFrame&&(s.A_fhs=r.sentFrame.height.toString(),s.A_frs=r.sentFrame.frameRate.toString(),s.A_fws=r.sentFrame.width.toString()),r.adaptionChangeReason){case"none":s.A_ac="0";break;case"cpu":s.A_ac="1";break;case"bandwidth":s.A_ac="2";break;case"other":s.A_ac="3"}return s.A_lvps=Xy[i._player?i._player.videoElementStatus:"uninit"].toString(),s.A_nr=null===(n=r.nacksCount)||void 0===n?void 0:n.toString(),r.avgEncodeMs&&(s.A_aem=r.avgEncodeMs.toFixed(0).toString()),kC("P2P")&&(r.bytes&&(s.bytesSent=r.bytes.toString()),"number"==typeof r.packetsLost&&(s.packetsLost=r.packetsLost.toString()),r.packets&&(s.packetsSent=r.packets.toString())),s}(r[0].ssrcId,e,n),s=i===uI.LocalVideoTrack?function(e,t,i){var n,r,s,o,a,c,d,l;const h=t.videoSend.find((t=>t.ssrc===e));if(!h)return null;const u={id:xS(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:h.ssrc.toString()},p=null!==(n=null!==(r=null===(s=h.inputFrame)||void 0===s?void 0:s.height)&&void 0!==r?r:null==i?void 0:i._videoHeight)&&void 0!==n?n:0,_=null!==(o=null!==(a=null===(c=h.inputFrame)||void 0===c?void 0:c.width)&&void 0!==a?a:null==i?void 0:i._videoWidth)&&void 0!==o?o:0,E=null!==(d=null===(l=h.inputFrame)||void 0===l?void 0:l.frameRate)&&void 0!==d?d:0;return p&&(u.A_fhi=p+""),_&&(u.A_fwi=_+""),E&&(u.A_fri=E+""),u}(r[0].ssrcId,e,n):null;t&&AS((()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,gv.PUBLISH_STATS,{stream_type:i===uI.LocalVideoLowTrack?"low":"high",stats:rk(rk({},t),s)})}));const o=function(e){const t={id:"bweforvideo",timestamp:new Date(e.timestamp).toISOString(),type:"VideoBwe"};return e.bitrate.retransmit&&(t.A_rb=e.bitrate.retransmit.toString()),e.bitrate.targetEncoded&&(t.A_teb=e.bitrate.targetEncoded.toString()),t.A_aeb=e.bitrate.actualEncoded.toString(),t.A_tb=e.bitrate.transmit.toString(),void 0!==e.sendBandwidth&&(t.A_asb=e.sendBandwidth.toString()),t}(e);o&&setTimeout((()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,gv.PUBLISH_STATS,{stream_type:i===uI.LocalVideoLowTrack?"low":"high",stats:o})}),1e3);break}case uI.LocalAudioTrack:{const t=function(e,t,i){const n=t.audioSend.find((t=>t.ssrc===e));if(!n)return null;const r={id:xS(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"audio",type:"ssrc",ssrc:n.ssrc.toString()};return r.A_astd=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?"1":"0",n.inputLevel?r.A_ail=Math.round(100*n.inputLevel).toString():r.A_ail=Math.round(100*i._source.getAccurateVolumeLevel()).toString(),r.A_apil=Math.round(100*i._source.getAccurateVolumeLevel()).toString(),n.aecReturnLoss&&(r.A_ecrl=Math.round(n.aecReturnLoss).toString()),n.aecReturnLossEnhancement&&(r.A_ecrle=Math.round(n.aecReturnLossEnhancement).toString()),kC("P2P")&&(n.bytes&&(r.bytesSent=n.bytes.toString()),"number"==typeof n.packetsLost&&(r.packetsLost=n.packetsLost.toString()),n.packets&&(r.packetsSent=n.packets.toString())),r}(r[0].ssrcId,e,n);t&&AS((()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,gv.PUBLISH_STATS,{stream_type:"high",stats:t})}));break}}}))}uploadRelatedUplinkStats(e,t){var i;((null===(i=this.requestLocalMedia)||void 0===i?void 0:i.call(this))||[]).filter((e=>{let[t]=e;return t===uI.LocalVideoLowTrack||t===uI.LocalVideoTrack})).forEach((t=>{let[i,{ssrcs:n}]=t;const r=function(e,t){const i=t.videoSend.find((t=>t.ssrc===e));return i?{mediaType:"video",isVideoMute:!1,frameRateInput:i.inputFrame&&i.inputFrame.frameRate.toString(),frameRateSent:i.sentFrame&&i.sentFrame.frameRate.toString(),googRtt:i.rttMs.toString(),qpSumPerFrame:Math.floor(i.qpSumPerFrame).toString()}:null}(n[0].ssrcId,e);r&&AS((()=>{var e;null===(e=this.requestUpload)||void 0===e||e.call(this,gv.PUBLISH_RELATED_STATS,{stream_type:i===uI.LocalVideoLowTrack?"low":"high",stats:r})}))}))}uploadDenoiserStats(e){for(let r=0;r<e.length;r++){const s=e[r];if(s instanceof XA){var t,i,n;const e=null===(t=(i=s._external).getDenoiserStats)||void 0===t?void 0:t.call(i);return void(e&&(null===(n=this.requestUpload)||void 0===n||n.call(this,gv.DENOISER_STATS,e)))}}}uploadExtensionStats(e){for(let t=0;t<e.length;t++)e[t].getProcessorStats().forEach((e=>{var t;null===(t=this.requestUpload)||void 0===t||t.call(this,e.type,e.stats)}))}stopUploadUplinkStats(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStatsUploadInterval&&window.clearInterval(this.uplinkStatsUploadInterval),this.uplinkRelatedStatsUploadInterval&&window.clearInterval(this.uplinkRelatedStatsUploadInterval),this.uplinkDenoiserStatsUploadInterval&&window.clearInterval(this.uplinkDenoiserStatsUploadInterval),this.uplinkStatsUploadInterval=void 0,this.uplinkRelatedStatsUploadInterval=void 0,this.uplinkDenoiserStatsUploadInterval=void 0)}startUploadDownlinkStats(){if(this.uploadDownlinkStarted)return;let e;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);let t=!1;this.downlinkStatsUploadInterval=window.setInterval((()=>{var i;const n=null===(i=this.requestStats)||void 0===i?void 0:i.call(this,!0);n&&(this.uploadDownlinkStats(n,t,e),e=n),t=!t}),3e3),this.downlinkRelatedStatsUploadInterval&&window.clearInterval(this.downlinkRelatedStatsUploadInterval),this.downlinkRelatedStatsUploadInterval=window.setInterval((()=>{var e;const t=null===(e=this.requestStats)||void 0===e?void 0:e.call(this,!0);t&&(this.uploadRelatedDownlinkStats(t,this.lastStats),this.lastStats=t)}),1e3),this.downlinkExtensionStatsUploadInterval&&window.clearInterval(this.downlinkExtensionStatsUploadInterval),this.downlinkExtensionStatsUploadInterval=window.setInterval((()=>{var e;const t=null===(e=this.requestRemoteMedia)||void 0===e?void 0:e.call(this);t&&this.uploadDownlinkExtensionStats(t)}),2e3)}uploadDownlinkStats(e,t,i){var n;((null===(n=this.requestRemoteMedia)||void 0===n?void 0:n.call(this))||[]).forEach((n=>{let[r,s]=n;if(s.has(dI.VIDEO)&&r.videoTrack){const n=r.videoTrack?function(e,t,i,n,r){const s=t.videoRecv.find((t=>t.ssrc===e));if(!s)return null;const o={id:xS(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:s.ssrc.toString()};var a,c;if(o.bytesReceived=s.bytes.toString(),o.packetsLost=s.packetsLost.toString(),o.packetsReceived=s.packets.toString(),s.framesRateFirefox&&(o.A_frr=s.framesRateFirefox.toString()),s.receivedFrame?(o.A_frr=s.receivedFrame.frameRate.toString(),o.A_fhr=s.receivedFrame.height.toString(),o.A_fwr=s.receivedFrame.width.toString()):(o.A_fhr=null===(a=n._videoHeight)||void 0===a?void 0:a.toString(),o.A_fwr=null===(c=n._videoWidth)||void 0===c?void 0:c.toString()),o.A_frd=s.decodeFrameRate.toString(),s.outputFrame&&(o.A_fro=s.outputFrame.frameRate.toString()),void 0!==s.jitterBufferMs&&(o.A_jbm=Math.floor(s.jitterBufferMs).toString()),void 0!==s.currentDelayMs&&(o.A_cdm=Math.floor(s.currentDelayMs).toString()),o.A_fs=s.firsCount.toString(),o.A_ns=s.nacksCount.toString(),o.A_ps=s.plisCount.toString(),n&&(o.A_vrtd=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?"0":"1"),n._player&&n._player.freezeTimeCounterList.length>0&&(o.A_vrft=Math.round(n._player.freezeTimeCounterList.splice(0,1)[0]).toString()),r&&n._player&&"visible"===ob.visibility){const e=Math.min(6e3,n._player.renderFreezeAccTime);o.A_vrrft=Math.round(e).toString(),n._player.renderFreezeAccTime=Math.max(0,n._player.renderFreezeAccTime-e)}if(o.A_rvps=Xy[n._player?n._player.videoElementStatus:"uninit"].toString(),i){const t=i.videoRecv.find((t=>t.ssrc===e));if(t&&void 0!==s.totalInterFrameDelay&&void 0!==s.totalSquaredInterFrameDelay&&void 0!==t.totalInterFrameDelay&&void 0!==t.totalSquaredInterFrameDelay){const e=s.totalInterFrameDelay-t.totalInterFrameDelay,i=s.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,n=s.framesDecodeCount-t.framesDecodeCount,r=e/n*1e3,a=Math.round(1e3*Math.sqrt((i-Math.pow(e,2)/n)/n));!isNaN(a)&&r+a>Math.max(3*r,r+150)&&(o.A_ifdsd=a.toString())}}return o}(r._videoSSRC,e,i,r.videoTrack,t):void 0;n&&AS((()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,gv.SUBSCRIBE_STATS,{stream_id:r.uid,stats:n})}))}if(s.has(dI.AUDIO)&&r.audioTrack){const t=r.audioTrack?function(e,t,i,n){const r=t.audioRecv.find((t=>t.ssrc===e));if(!r)return null;const s={id:xS(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"audio",type:"ssrc",ssrc:r.ssrc.toString()};if(s.bytesReceived=r.bytes.toString(),s.packetsLost=r.packetsLost.toString(),s.packetsReceived=r.packets.toString(),r.outputLevel?s.A_aol=Math.round(100*r.outputLevel).toString():s.A_aol=Math.round(100*n._source.getAccurateVolumeLevel()).toString(),s.A_apol=Math.round(100*n._source.getAccurateVolumeLevel()).toString(),n&&(s.A_artd=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?"0":"1"),s.A_jr=r.jitterMs.toString(),s.A_jbm=Math.floor(r.jitterBufferMs).toString(),s.A_cdm=Math.floor(r.jitterBufferMs).toString(),s.A_raps=Xy[kA.getPlayerState(n.getTrackId())].toString(),i){const t=i.audioRecv.find((t=>t.ssrc===e));if(t){const e=r.concealedSamples-t.concealedSamples;e>0&&(s.A_cs=Math.round(e).toString())}}return s}(r._audioSSRC,e,i,r.audioTrack):void 0;t&&AS((()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,gv.SUBSCRIBE_STATS,{stream_id:r.uid,stats:t})}))}}))}uploadRelatedDownlinkStats(e,t){var i;((null===(i=this.requestRemoteMedia)||void 0===i?void 0:i.call(this))||[]).forEach((i=>{let[n,r]=i;if(r.has(dI.VIDEO)&&n.videoTrack){var s;const i=!0===(n._videoSSRC&&(null===(s=this.requestVideoIsReady)||void 0===s?void 0:s.call(this,n._videoSSRC))||!1),r=function(e,t,i,n,r,s){const o=i.videoRecv.find((t=>t.ssrc===e)),a=r?r.videoRecv.find((t=>t.ssrc===e)):void 0;if(!o)return null;const c=cD.isRemoteVideoFreeze(s,o,a)&&t,d={mediaType:"video",isVideoMute:!1,peerId:n,frameRateReceived:o.receivedFrame&&o.receivedFrame.frameRate.toString(),frameRateDecoded:o.decodedFrame&&o.decodedFrame.frameRate.toString(),isFreeze:c,bytesReceived:o.bytes.toString(),packetsReceived:o.packets.toString(),packetsLost:o.packetsLost.toString(),qpSumPerFrame:Math.floor(o.qpSumPerFrame).toString()};return o.framesRateFirefox&&(d.frameRateDecoded=o.framesRateFirefox.toString(),d.frameRateReceived=o.framesRateFirefox.toString()),d}(n._videoSSRC,i,e,n.uid,t,n.videoTrack);r&&AS((()=>{var e;null===(e=this.requestUpload)||void 0===e||e.call(this,gv.SUBSCRIBE_RELATED_STATS,{stream_id:n.uid,stats:r})}))}if(r.has(dI.AUDIO)&&n.audioTrack){const t=function(e,t,i,n){const r=t.audioRecv.find((t=>t.ssrc===e));if(!r)return null;const s=cD.isRemoteAudioFreeze(n);return{mediaType:"audio",isAudioMute:!1,peerId:i,googJitterReceived:r.jitterMs.toString(),isFreeze:s,bytesReceived:r.bytes.toString(),packetsReceived:r.packets.toString(),packetsLost:r.packetsLost.toString(),frameReceived:r.receivedFrames.toString(),frameDropped:r.droppedFrames.toString()}}(n._audioSSRC,e,n.uid,n.audioTrack);t&&AS((()=>{var e;null===(e=this.requestUpload)||void 0===e||e.call(this,gv.SUBSCRIBE_RELATED_STATS,{stream_id:n.uid,stats:t})}))}}))}stopUploadDownlinkStats(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval),this.downlinkRelatedStatsUploadInterval&&window.clearInterval(this.downlinkRelatedStatsUploadInterval),this.downlinkStatsUploadInterval=void 0,this.downlinkRelatedStatsUploadInterval=void 0)}stopUploadTransportStats(){this.uploadTransportStarted&&(this.uploadTransportStarted=!1,this.transportStatsUploadInterval&&window.clearInterval(this.transportStatsUploadInterval),this.transportStatsUploadInterval=void 0)}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.extensionUsageStatsUploadInterval&&window.clearInterval(this.extensionUsageStatsUploadInterval),this.extensionUsageStatsUploadInterval=void 0)}uploadDownlinkExtensionStats(e){e.forEach((e=>{let[t,i]=e;i.has(dI.VIDEO)&&t.videoTrack&&t.videoTrack.getProcessorStats().forEach((e=>{var t;null===(t=this.requestUpload)||void 0===t||t.call(this,e.type,e.stats)})),i.has(dI.AUDIO)&&t.audioTrack&&t.audioTrack.getProcessorStats().forEach((e=>{var t;null===(t=this.requestUpload)||void 0===t||t.call(this,e.type,e.stats)}))}))}}function ok(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function ak(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ok(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ok(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function ck(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=BP,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new dk(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function dk(e){function t(e){if(Object(e)!==e)return tg.reject(new TypeError(e+" is not an object."));var t=e.done;return tg.resolve(e.value).then((function(e){return{value:e,done:t}}))}return dk=function(e){this.s=e,this.n=e.next},dk.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?tg.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?tg.reject(e):t(i.apply(this.s,arguments))}},new dk(e)}class lk extends iS{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(_I.StateChange,t,this._state)}constructor(e,t){super(),nu(this,"store",void 0),nu(this,"statsUploader",void 0),nu(this,"connection",void 0),nu(this,"localTrackMap",new Map),nu(this,"remoteUserMap",new Map),nu(this,"localDataChannels",[]),nu(this,"remoteDataChannelMap",new Map),nu(this,"pendingLocalTracks",[]),nu(this,"pendingRemoteTracks",[]),nu(this,"pendingLocalDataChannels",[]),nu(this,"pendingRemoteDataChannels",[]),nu(this,"statsCollector",void 0),nu(this,"isPlanB",!1),nu(this,"shouldForwardP2PCreation",void 0),nu(this,"iceFailedCount",0),nu(this,"dtlsFailedCount",0),nu(this,"mutex",new YS("P2PChannel-mutex")),nu(this,"_state",pI.Disconnected),nu(this,"_pcStatsUploadType",kC("NEW_ICE_RESTART")?hI.FIRST_CONNECTION:hI.OLD_FIRST_CONNECTION),nu(this,"_isInRestartIce",!1),nu(this,"_isStartRestartIce",!1),nu(this,"_restartStates",["disconnected","failed"]),nu(this,"_restartTimer",void 0),nu(this,"_isFirstConnected",!0),nu(this,"handleMuteLocalTrack",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==pI.Connected)return void i(new Vg(xg.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const n=this.filterTobeMutedTracks(e);if(0===n.length)return void t();const r=n.find((e=>"videoLowTrack"===e[0]));r&&r[1].track._originMediaStreamTrack.stop(),await this.connection.muteLocal(n.map((e=>{let[,{id:t}]=e;return t})));const s=this.createMuteMessage(n);await gS(this,_I.RequestMuteLocal,s),t()}catch(e){i(e)}finally{n()}})),nu(this,"handleUnmuteLocalTrack",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==pI.Connected)return void i(new Vg(xg.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const n=this.filterTobeUnmutedTracks(e);if(0===n.length)return void t();const r=n.find((e=>"videoLowTrack"===e[0]));if(r){const t=r[1];if(t.track._originMediaStreamTrack.stop(),!kC("DISABLE_DUAL_STREAM_USE_ENCODING")&&hA().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=jL(e,TS(this,_I.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new tg(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}await this.connection.unmuteLocal(n.map((e=>{let[,{id:t}]=e;return t})));const s=this.createUnmuteMessage(n);await gS(this,_I.RequestUnmuteLocal,s),t()}catch(e){i(e)}finally{n()}})),nu(this,"handleUpdateVideoEncoder",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetVideoEncoder");try{const i=this.localTrackMap.get(uI.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==pI.Connected)return void t();const{id:n,track:r}=i;await this.connection.updateSendParameters(n,r),await this.connection.updateEncoderConfig(n,r),this.emit(_I.UpdateVideoEncoder,r),t()}catch(e){i(e)}finally{n()}})),nu(this,"handleSetOptimizationMode",(async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetOptimizationMode");try{const i=this.localTrackMap.get(uI.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==pI.Connected)return;const{id:n,track:r}=i;await this.connection.updateSendParameters(n,r),t()}catch(e){i(e)}finally{n()}})),nu(this,"handleReplaceTrack",(async(e,t,i,n)=>{let r;WC.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var s;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.connection||!i||this.state!==pI.Connected)return void t();if(await(null===(s=this.connection)||void 0===s?void 0:s.replaceTrack(e,i[1].id)),this.isPlanB){const t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t)}if(i[0]===uI.LocalVideoTrack&&!kC("DISABLE_DUAL_STREAM_USE_ENCODING")&&hA().supportDualStreamEncoding){const t=this.localTrackMap.get(uI.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new tg(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var o;null===(o=r)||void 0===o||o()}})),nu(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),nu(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),nu(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),nu(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new sk,this.bindStatsUploaderEvents(),this.isPlanB=!hA().supportUnifiedPlan||kC("CHROME_FORCE_PLAN_B")&&kg(),this.shouldForwardP2PCreation=kC("FORWARD_P2P_CREATION")&&hA().supportPCSetConfiguration&&function(){const e=_g();return e===ag.ANDROID||e===ag.IOS||e===ag.HARMONY_OS}(),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new tk({},this.store):this.isPlanB?new DL({},this.store):new FL({},this.store),this.bindConnectionEvents(this.connection))}async startP2PConnection(e,t){var i;this.state=pI.New;const n=this.shouldForwardP2PCreation&&"closed"===(null===(i=this.connection)||void 0===i?void 0:i.peerConnectionState);if(this.shouldForwardP2PCreation&&!n||(n&&this.connection&&(WC.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.connection.close(),this.unbindConnectionEvents(this.connection)),this.connection=this.store.useDataChannel?new tk(e,this.store):this.isPlanB?new DL(e,this.store):new FL(e,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new Vg(xg.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=kC("NEW_ICE_RESTART")?hI.FIRST_CONNECTION:hI.OLD_FIRST_CONNECTION,this._isFirstConnected=!0,this._isInRestartIce=!1,this._isStartRestartIce=!1,this.connection.setConfiguration(e),this.connection.establishPromise}async connect(e,t,i,n,r,s){if(!this.connection)throw new Vg(xg.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.connection instanceof tk?this.connection.updateRemoteConnect(n):(this.store.peerConnectionStart(),await this.connection.connect(e,t,i,n,r,s),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=pI.Connected)}async preConnect(e,t,i,n,r,s){if(!this.connection)throw new Vg(xg.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.store.peerConnectionStart();const o=await this.connection.connect(e,t,i,n,r,s);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=pI.Connected,o}getEstablishParams(){if(this.connection instanceof tk)return this.connection.getP2PConnectionParams();throw new Error("Only DataChannelConnection needs to obtain establishParams")}async publishDataChannel(e){if(!this.connection){if(this.state===pI.Disconnected)throw new Vg(xg.UNEXPECTED_ERROR,"PeerConnection already disconnected.");const t=e.filter((e=>-1!==this.pendingLocalDataChannels.findIndex((t=>t.id===e.id))));return void(this.pendingLocalDataChannels=this.pendingLocalDataChannels.concat(t))}const t=this.filterTobePublishedDataChannels(e);0!==t.length&&(t.forEach((e=>{const t=Date.now();this.store.publish(e.id.toString(),"datachannel",t)})),await this.connection.createDataChannels(this.store.uid,t),t.forEach((e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t)})))}publish(e,t,i){var n=this;return xP((function*(){const r=yield VP(n.mutex.lock("From P2PChannel.publish"));try{if(!n.connection||n.state!==pI.Connected){if(n.state===pI.Disconnected)throw new Vg(xg.UNEXPECTED_ERROR,"PeerConnection already disconnected.");n.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===n.pendingLocalTracks.indexOf(e)));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t))}n.store.pubId=n.store.pubId+1,sD.markPublishStart(n.store.clientId,n.store.pubId);const r=n.filterTobePublishedTracks(e,t,i);if(0===r.length)return void(yield VP(n.tryToUnmuteAudio(e)));yield*FP(ck(n.doPublish(n.connection,r)))}finally{r()}}))()}doPublish(e,t){var i=this;return xP((function*(){t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===uI.LocalAudioTrack?"audio":"video",r)})),i.bindLocalTrackEvents(t);const n=yield VP(e.send(t.map((e=>{let{track:t}=e;return t})),i.store.codec,i.store.audioCodec)),r=(yield VP(n.next())).value,s=i.createGatewayPublishMessage(t,r);let o;try{o=yield s}catch(e){throw n.throw(e),(null==e?void 0:e.code)===xg.WS_ABORT&&t.forEach((e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(t),e}const a=i.mapPubResToRemoteConfig(s,o),c=(yield VP(n.next(a))).value;t.forEach((e=>{let{type:t}=e;i.statsCollector.addLocalStats(t)})),i.assignLocalTracks(t,c),i.statsUploader.startUploadUplinkStats(),t.forEach((e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===uI.LocalAudioTrack?"audio":"video",void 0,r)}))}))()}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i)return;if(!(i.track instanceof fb))return WC.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");if(!(this.connection instanceof FL||this.connection instanceof DL))return WC.warn("[updateVideoStreamParameter]: connection is not P2PConnection or P2PConnectionPlanB");const{track:n}=i,r=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=SD(e,t)),i.maxFramerate=e.framerate?pD(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,n);if(n._encoderConfig||(n._encoderConfig={}),t!==uI.LocalVideoLowTrack||!kC("DISABLE_DUAL_STREAM_USE_ENCODING")&&hA().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const t=n._originMediaStreamTrack;if(!t.canvas)return WC.warn("[".concat(n.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=pD(t.width)),t.height&&(i.height=pD(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=dA((()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()}),pD(t.framerate)))}(t,e)}null!=r.maxBitrate&&(n._encoderConfig.bitrateMax=r.maxBitrate/1e3),null!=r.maxFramerate&&(n._encoderConfig.frameRate&&"object"==typeof n._encoderConfig.frameRate?n._encoderConfig.frameRate.max=r.maxFramerate:n._encoderConfig.frameRate={max:r.maxFramerate}),WC.debug("[".concat(n.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(n._encoderConfig))),await this.connection.updateRtpSenderEncodings(n)}publishLowStream(e){var t=this;return xP((function*(){if(!t.connection||t.state!==pI.Connected)return;const i=yield VP(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const i=t.localTrackMap.get(uI.LocalVideoTrack);if(!i)throw new Vg(xg.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(uI.LocalVideoLowTrack))throw new Vg(xg.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const r=[{track:t.getLowVideoTrack(i.track,e),type:uI.LocalVideoLowTrack}];if(yield*FP(ck(t.doPublish(t.connection,r))),i.track.muted||!i.track.enabled){var n;const e=null===(n=t.localTrackMap.get(uI.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield VP(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(WC.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await fS(this,_I.RequestRePublish,this.pendingLocalTracks),this.emit(_I.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(WC.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await fS(this,_I.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[])}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==dI.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==dI.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await fS(this,_I.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===dI.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach((e=>{let{user:t}=e;this.emit(_I.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==pI.Connected)return void e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find((e=>"videoLowTrack"===e[0]));return i&&i[1].track.close(),this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==pI.Connected)return void e.forEach((e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1)}));const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach((e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1)})),0===this.localDataChannels.length&&await this.connection.stopDataChannels(this.store.uid),t.map((e=>e.id))):void 0}async unpublishLowStream(){if(!this.connection||this.state!==pI.Connected)return;const e=this.localTrackMap.get(uI.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[uI.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map((e=>{let[,{id:t}]=e;return t}))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadUplinkStats(),i}async subscribeDataChannel(e,t){if(!this.connection||this.state!==pI.Connected)throw new Vg(xg.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const i=t.filter((t=>{var i;return!(null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.get(t.id))}));if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEach((t=>{var i;this.remoteDataChannelMap.has(e)?null===(i=this.remoteDataChannelMap.get(e))||void 0===i||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const n=this.pendingRemoteDataChannels.findIndex((i=>{let{user:n,id:r}=i;return n.uid===e.uid&&r===t.id}));-1!==n&&this.pendingRemoteDataChannels.splice(n,1)})),i.map((e=>e.id))}async subscribe(e,t,i,n,r){var s;if(!this.connection||this.state!==pI.Connected)throw new Vg(xg.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(s=this.remoteUserMap.get(e))&&void 0!==s&&s.has(t))return;let o,a,c;if(r){const i=r.find((e=>{let{stream_type:i}=e;return i===t}));if(!i)throw new Vg(xg.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);this.connection instanceof FL&&(c=n.transceiver),o=n.track,a=n.id}else{const r=await this.connection.receive(t,[{ssrcId:i,rtx:n}],String(e._uintid),void 0);this.connection instanceof FL&&(c=r.transceiver),o=r.track,a=r.id}t===dI.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new Ab(o,e.uid,e._uintid,this.store),WC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(o):(e._videoTrack=new yb(o,e.uid,e._uintid,this.store),WC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack));const d=this.remoteUserMap.get(e);d?d.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadDownlinkStats();const l=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(_I.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==pI.Connected)throw new Vg(xg.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter((e=>{var t;let{user:i,mediaType:n}=e;return!(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n))}));const t=await this.connection.batchReceive(e.map((e=>{let{user:t,mediaType:i,ssrcId:n,rtxSsrcId:r}=e;return{kind:i,ssrcMsg:[{ssrcId:n,rtx:r}],mslabel:String(t._uintid)}})));e.forEach(((e,i)=>{let{user:n,mediaType:r}=e;const{track:s,id:o,transceiver:a}=t[i];r===dI.AUDIO?(n._audioTrack?n._audioTrack._updateOriginMediaStreamTrack(s):(n._audioTrack=new Ab(s,n.uid,n._uintid,this.store),WC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(n._audioTrack.getTrackId()))),a&&n._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(n,n._audioTrack)):(n._videoTrack?n._videoTrack._updateOriginMediaStreamTrack(s):(n._videoTrack=new yb(s,n.uid,n._uintid,this.store),WC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(n._videoTrack.getTrackId()))),a&&n._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(n,n._videoTrack));const c=this.remoteUserMap.get(n);c?c.set(r,o):this.remoteUserMap.set(n,new Map([[r,o]])),this.statsCollector.addRemoteStats(n.uid),this.statsUploader.startUploadDownlinkStats();const d=this.pendingRemoteTracks.findIndex((e=>{let{user:t,kind:i}=e;return t.uid===n.uid&&r===i}));-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(_I.MediaReconnectEnd,n.uid))}))}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter((i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid}));if(n.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===pI.Connected||i||n.forEach((t=>{let{kind:i}=t;var n;if(i===dI.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===dI.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==pI.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map((e=>{let[,{id:t}]=e;return t})));const s=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadDownlinkStats(),r.forEach((e=>{let[t,{kind:n}]=e;var r,s;if(n===dI.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1)),n===dI.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(s=t._videoTrack)||void 0===s||s._destroy(),t._videoTrack=void 0);else if(n===dI.AUDIO){var o;this.unbindRemoteTrackEvents(t._audioTrack),i||(null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0)}})),s}async unsubscribeDataChannel(e,t){if(t.forEach((e=>{const t=this.pendingRemoteDataChannels.findIndex((t=>t.id===e.id));-1!==t&&this.pendingRemoteDataChannels.splice(t,1)})),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach((e=>{e._close()}));const n=this.remoteDataChannelMap.get(e);return i.forEach((e=>{n&&n.delete(e.id)})),n&&0===n.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const{user:i,mediaType:n}of e){const e=this.pendingRemoteTracks.filter((e=>{let{user:t,kind:r}=e;return void 0!==n?t.uid===i.uid&&n===r:t.uid===i.uid}));e.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(e)}if(!this.connection||this.state!==pI.Connected)return void t.forEach((e=>{let{user:t,kind:i}=e;var n;if(i===dI.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===dI.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}}));const i=cT(e).call(e,((e,t)=>{let{user:i,mediaType:n}=t;const r=this.filterTobeUnSubscribedTracks(i,n);return e.concat(r)}),[]);if(0===i.length)return;await this.connection.stopReceiving(i.map((e=>{let[,{id:t}]=e;return t})));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadDownlinkStats(),i.forEach((e=>{let[t,{kind:i}]=e;var n,r;if(i===dI.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1)),i===dI.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===dI.AUDIO){var s;this.unbindRemoteTrackEvents(t._audioTrack),null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}})),n}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void WC.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void WC.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===dI.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.connection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);i?i.get(t)||WC.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,".")):WC.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."))}getAllTracks(e){const t=this.localTrackMap.get(uI.LocalAudioTrack);if((null==t?void 0:t.track)instanceof ZA){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==uI.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===uI.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===uI.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(uI.LocalAudioTrack),s=n?this.localTrackMap.get(uI.LocalVideoLowTrack):this.localTrackMap.get(uI.LocalVideoTrack);iv.publish(this.store.sessionId,{eventElapse:sD.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==s?void 0:s.track.getTrackLabel(),screenshare:-1!==(null==s?void 0:s.track._hints.indexOf(Dy.SCREEN_TRACK)),audio:!!i,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var s;i||(i=[]);const o=i.find((e=>e instanceof zA)),a=n?null===(s=this.localTrackMap.get(uI.LocalVideoTrack))||void 0===s?void 0:s.track:i.find((e=>e instanceof fb));iv.publish(this.store.sessionId,{eventElapse:sD.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==o?void 0:o.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(Dy.SCREEN_TRACK)),audio:!!o,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===dI.VIDEO?i._videoSSRC:i._audioSSRC;r&&iv.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===dI.VIDEO,audio:n===dI.AUDIO,peerid:i.uid,subscribeRequestid:n===dI.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:sD.measureFromSubscribeStart(this.store.clientId,r)})}reset(){WC.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new YS("P2PChannel-mutex"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new tk({},this.store):this.isPlanB?new DL({},this.store):new FL({},this.store),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(uI.LocalAudioTrack);if((null==e?void 0:e.track)instanceof ZA){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=pI.Disconnected}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(uI.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(uI.LocalVideoTrack);if(e)return{width:e.track._videoWidth||0,height:e.track._videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof fb||t&&t.track instanceof zA?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;const i=Array.from(hu(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(uI.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=Zu(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(WC.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=pI.Reconnecting,kC("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new tk({},this.store):this.isPlanB?new DL({},this.store):new FL({},this.store),this.bindConnectionEvents(this.connection)),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[i,{track:n}]=e;switch(i){case uI.LocalVideoTrack:Lr(t=n._hints).call(t,Dy.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case uI.LocalAudioTrack:n instanceof ZA?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case uI.LocalVideoLowTrack:}})),this.emit(_I.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(hu(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(_I.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach((e=>{this.pendingLocalDataChannels.push(e)})),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach((e=>{let[t,i]=e;Array.from(hu(i).call(i)).forEach((e=>{this.setPendingRemoteDataChannel(t,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),WC.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(const i of this.pendingRemoteDataChannels){const{user:n,id:r}=i;if((e instanceof bP?e.uid:e)===n.uid&&r===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof bP?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return xP((function*(){if(!t.connection||t.state!==pI.Connected||t.connection instanceof tk)return;const i=yield VP(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield VP(t.connection.restartICE(e));const i=yield VP(n.next());if(i.done)return;const r=i.value,s=yield r;switch(t.reportPCDisconnectedOrFailed(e),e){case lI.TCP:t._pcStatsUploadType=hI.TCP_RESTART;break;case lI.RELAY:t._pcStatsUploadType=hI.RELAY_RESTART;break;default:t._pcStatsUploadType=hI.OLD_RESTART}t._isInRestartIce=!0,n.next(s)}catch(e){var r;null===(r=n)||void 0===r||r.throw(e)}finally{i()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(uI.LocalVideoTrack),i=this.localTrackMap.get(uI.LocalAudioTrack),n=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),r=e.audioSend.find((e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId)));if(!n||!r)return 1;const s=SS(this,_I.NeedSignalRTT),o=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=o&&a?(o+a)/2:o||a,d=(c&&s?(c+s)/2:c||s)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,h=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,u=null==t?void 0:t.track;if(u&&u._encoderConfig&&-1===u._hints.indexOf(Dy.SCREEN_TRACK)){const t=u._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return sv[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][h]}}return h}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const r=n._audioSSRC,s=n._videoSSRC,o=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===s));if(!o&&!a)return void(t+=1);const c=SS(this,_I.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,h=o?o.jitterMs:void 0,u=e.recvPacketLossRate;let p=.7*u*100/50+.3*l/1500;h&&(p=.6*u*100/50+.2*l/1500+.2*h/400),t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new tg(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}filterTobePublishedTracks(e,t,i){const n=[],r=hA(),s=this.getAllTracks();e=yS(e=e.filter((e=>-1===s.indexOf(e))));let o=!1,a=!1;for(const s of e){if(s instanceof fb&&(this.localTrackMap.has(uI.LocalVideoTrack)||o?new Vg(xg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:s,type:uI.LocalVideoTrack}),o=!0),t)){const e=this.getLowVideoTrack(s,i);n.push({track:e,type:uI.LocalVideoLowTrack})}if(s instanceof zA){const e=this.localTrackMap.get(uI.LocalAudioTrack);if(e){if(!(e.track instanceof ZA))throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(s._bypassWebAudio)throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(s),this.bindLocalAudioTrackEvents(s,!0)}else if(a){const e=n.find((e=>{let{type:t}=e;return t===uI.LocalAudioTrack}));if(!(e.track instanceof ZA))throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(s._bypassWebAudio)throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(s)}else{if(!r.webAudioMediaStreamDest||s instanceof ZA||s._bypassWebAudio)n.push({track:s,type:uI.LocalAudioTrack});else{const e=new ZA;e.addAudioTrack(s),n.push({track:e,type:uI.LocalAudioTrack})}a=!0}}}return n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=yS(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof zA){const e=this.localTrackMap.get(uI.LocalAudioTrack);if(!e)continue;e.track instanceof ZA?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([uI.LocalAudioTrack,e]),e.track.close())):t.push([uI.LocalAudioTrack,e])}if(i instanceof fb){const e=this.localTrackMap.get(uI.LocalVideoTrack);if(!e)continue;t.push([uI.LocalVideoTrack,e]);const i=this.localTrackMap.get(uI.LocalVideoLowTrack);i&&t.push([uI.LocalVideoLowTrack,i])}}return t}filterTobePublishedDataChannels(e){return(e=yS(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return(e=(e=yS(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case uI.LocalVideoTrack:t.addListener(Ny.GET_STATS,this.handleGetLocalVideoStats),t.addListener(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(Ny.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(Ny.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(Ny.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case uI.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case uI.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof ZA?e.trackList.forEach((e=>{e.addListener(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Ny.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(Ny.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(Ny.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case uI.LocalVideoTrack:t.off(Ny.GET_STATS,this.handleGetLocalVideoStats),t.off(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(Ny.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(Ny.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(Ny.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case uI.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case uI.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof ZA?e.trackList.forEach((e=>{e.off(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Ny.GET_STATS,this.handleGetLocalAudioStats),e.off(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(Ny.GET_STATS,this.handleGetLocalAudioStats),e.off(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Ny.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof yb&&t.addListener(Ny.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof Ab&&t.addListener(Ny.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(Ny.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(dI.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(dI.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,i)=>{var n;let r,s,{track:o,type:a}=e;switch(a){case uI.LocalAudioTrack:r=Qv.Audio,s={dtx:o instanceof XA&&o._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case uI.LocalVideoTrack:r=Lr(n=o._hints).call(n,Dy.SCREEN_TRACK)?Qv.Screen:Qv.High,s=ak(ak({},_D(o)),{},{codec:this.store.codec});break;case uI.LocalVideoLowTrack:r=Qv.Low,s=ak(ak({},_D(o)),{},{codec:this.store.codec})}return{stream_type:r,attributes:s,ssrcs:t[i]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case uI.LocalVideoTrack:i=Lr(t=r._hints).call(t,Dy.SCREEN_TRACK)?Qv.Screen:Qv.High;break;case uI.LocalAudioTrack:i=Qv.Audio;break;case uI.LocalVideoLowTrack:i=Qv.Low}return{stream_type:i,ssrcs:s,mid:o}}))}assignLocalTracks(e,t){e.forEach(((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(_I.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(this._restartTimer&&(clearTimeout(this._restartTimer),this._restartTimer=void 0),(this._isFirstConnected||this._isInRestartIce)&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isInRestartIce=!1,this._isFirstConnected=!1,this._isStartRestartIce=!1),kC("NEW_ICE_RESTART")){var i;if(Lr(i=this._restartStates).call(i,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{"disconnected"!==e.iceConnectionState&&"checking"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||(WC.debug("[".concat(this.store.clientId,"] [P2PChannel] start use restartICE, type is ").concat(t)),"CONNECTED"===SS(this,_I.QueryClientConnectionState)&&this.emit(_I.RequestRestartICE,t))},i=()=>{"disconnected"!==e.iceConnectionState&&"checking"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),WC.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(_I.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())},n=kC("ICE_RESTART_INTERVAL");return void(this._restartTimer=window.setTimeout((()=>{if(kC("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&hA().supportPCSetConfiguration)t(lI.RELAY),this._restartTimer=window.setTimeout(i,n);else if(Rg())t(lI.UDP),this._restartTimer=window.setTimeout(i,4e3);else{if(t(lI.TCP),hA().supportPCSetConfiguration)return void(this._restartTimer=window.setTimeout((()=>{t(lI.RELAY),this._restartTimer=window.setTimeout(i,n)}),n));this._restartTimer=window.setTimeout(i,n)}}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{"disconnected"===e.iceConnectionState&&kC("ICE_RESTART")&&"CONNECTED"===SS(this,_I.QueryClientConnectionState)&&this.emit(_I.RequestRestartICE)}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(WC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isInRestartIce=!1,setTimeout((()=>this.emit(_I.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(WC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCDisconnectedOrFailed(),setTimeout((()=>this.emit(_I.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),iv.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:oS.TRACER}).onSuccess(),this.emit(_I.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(hu(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var n;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(xy.FIRST_FRAME_DECODED),iv.firstRemoteFrame(this.store.sessionId,JC.FIRST_AUDIO_DECODE,zC.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:sD.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(hu(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&iv.firstRemoteFrame(this.store.sessionId,JC.FIRST_AUDIO_RECEIVED,zC.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:sD.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;const i=Array.from(hu(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&iv.firstRemoteFrame(this.store.sessionId,JC.FIRST_VIDEO_RECEIVED,zC.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:sD.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(_I.ConnectionTypeChange,i),WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(TD(t))," -> ").concat(JSON.stringify(TD(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(TD(t))," -> ").concat(JSON.stringify(TD(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(uI.LocalAudioTrack);if(e instanceof zA&&(null==i?void 0:i.track)instanceof ZA)return i.track.isActive||t.push([uI.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n&&(t.push(n),n[0]===uI.LocalVideoTrack)){const e=this.localTrackMap.get(uI.LocalVideoLowTrack);e&&t.push([uI.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(uI.LocalAudioTrack);if(e instanceof zA&&(null==i?void 0:i.track)instanceof ZA)return i.track.isActive&&t.push([uI.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===uI.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(uI.LocalVideoLowTrack);e&&t.push([uI.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case uI.LocalAudioTrack:i=Qv.Audio;break;case uI.LocalVideoTrack:i=Lr(t=r._hints).call(t,Dy.SCREEN_TRACK)?Qv.Screen:Qv.High;break;case uI.LocalVideoLowTrack:i=Qv.Low}return{stream_type:i,ssrcs:s,mid:o}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case uI.LocalAudioTrack:i=Qv.Audio;break;case uI.LocalVideoTrack:i=Lr(t=r._hints).call(t,Dy.SCREEN_TRACK)?Qv.Screen:Qv.High;break;case uI.LocalVideoLowTrack:i=Qv.Low}return{stream_type:i,ssrcs:s,mid:o}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])}));return i}filterTobeUnSubscribedDataChannels(e,t){const i=[];return t.forEach((t=>{var n;null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.has(t.id)&&i.push(t)})),i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:r}]=e;switch(n){case dI.VIDEO:return void(i._videoSSRC&&t.push({stream_type:dI.VIDEO,ssrcId:i._videoSSRC}));case dI.AUDIO:return void(i._audioSSRC&&t.push({stream_type:dI.AUDIO,ssrcId:i._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let[i,{kind:n}]=e;if(t.has(i)){let e=t.get(i);n===dI.VIDEO?e|=eI.Video:e|=eI.Audio,t.set(i,e)}else n===dI.VIDEO?t.set(i,eI.Video):t.set(i,eI.Audio)})),{users:Array.from(t.entries()).map((e=>{let[t,i]=e;return{stream_id:t.uid,stream_type:i}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(uI.LocalVideoTrack),i=this.localTrackMap.get(uI.LocalVideoLowTrack);t&&await t.track.setBitrateLimit(e.uplink),i&&e.low_stream_uplink&&await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0})}isP2PDisconnected(){return!this.connection||"connected"!==this.connection.peerConnectionState}mapPubResToRemoteConfig(e,t){return e.map(((e,i)=>{var n;let{stream_type:r}=e;return null===(n=t.find((e=>{let{stream_type:t}=e;return r===t})))||void 0===n?void 0:n.attributes}))}async tryToUnmuteAudio(e){for(let i=0;i<e.length;i++)if(e[i]instanceof zA){var t;const n=this.filterTobeUnmutedTracks(e[i]);if(0===n.length)continue;await(null===(t=this.connection)||void 0===t?void 0:t.unmuteLocal(n.map((e=>{let[,{id:t}]=e;return t}))));const r=this.createUnmuteMessage(n);return void await gS(this,_I.RequestUnmuteLocal,r)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.connection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(_I.RequestUploadStats,e,t),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await US(zS(this.dtlsFailedCount,JS)),this.emit(_I.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await fS(this,_I.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(_I.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(uI.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof fb))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof fb)).length>1)throw new Vg(xg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof zA)).length>1&&(e.some((e=>e instanceof zA&&e._bypassWebAudio))||!hA().webAudioMediaStreamDest))throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof fb&&this.pendingLocalTracks.some((e=>e instanceof fb)))throw new Vg(xg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof zA&&this.pendingLocalTracks.some((e=>e instanceof zA))&&(!hA().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof zA&&e._bypassWebAudio))))throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const i=!kC("DISABLE_DUAL_STREAM_USE_ENCODING")&&hA().supportDualStreamEncoding,n=ak(ak({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():jL(e,n);const s=xS(8,"track-low-"),o=new fb(r,ak(ak({},i&&{scaleResolutionDownBy:SD(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,s);return o.on(My.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,Py.LOW_STREAM)})),o._hints.push(Dy.LOW_STREAM),e.addListener(Ny.NEED_CLOSE,(()=>{o.close()})),o}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof FL){var r,s,o,a;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:h}=this.connection,{local:u,remote:p}=await this.connection.getSelectedCandidatePair();iv.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:h,intSucc:t?1:2,error:n,selectedLocalCandidateProtocol:null!==(r=null==u?void 0:u.protocol)&&void 0!==r?r:"",selectedLocalCandidateType:null!==(s=u.candidateType)&&void 0!==s?s:"",selectedLocalCandidateAddress:"".concat(u.address,":").concat(u.port),selectedRemoteCandidateProtocol:null!==(o=p.protocol)&&void 0!==o?o:"",selectedRemoteCandidateType:null!==(a=p.candidateType)&&void 0!==a?a:"",selectedRemoteCandidateAddress:"".concat(p.address,":").concat(p.port),restartCnt:i})}}reportVideoFirstFrameDecoded(e,t,i,n){var r;const s=Array.from(hu(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(s){n||this.store.subscribe(s.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,o=r.subscribe.find((e=>e.userId===s.uid&&"video"===e.type));iv.firstRemoteVideoDecode(this.store.sessionId,JC.FIRST_VIDEO_DECODE,zC.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:sD.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==o?void 0:o.subscribeEnd)||0,subscriberStart:(null==o?void 0:o.subscribeStart)||0,videoAddNotify:(null==o?void 0:o.streamAdded)||0,state:n?1:0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const s=await this.connection.getRemoteSSRC(r);return void 0!==s&&s!==i}resetConnection(e){WC.debug("[".concat(this.store.clientId,"] [P2PChannel] reset connection to ").concat(e)),this.state===pI.Connected?(WC.debug("[".concat(this.store.clientId,"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first")),this.disconnectForReconnect()):(this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=e===tI.datachannel?new tk({},this.store):this.isPlanB?new DL({},this.store):new FL({},this.store),this.bindConnectionEvents(this.connection)))}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===uI.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,Py.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}reportPCDisconnectedOrFailed(e){this.connection&&this.connection instanceof FL&&("disconnected"!==this.connection.iceConnectionState&&"checking"!==this.connection.iceConnectionState&&"failed"!==this.connection.iceConnectionState||(this._isFirstConnected?(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isFirstConnected=!1):this._pcStatsUploadType===hI.TCP_RESTART&&e===lI.RELAY?this.reportPCStats(Date.now(),!1,this._pcStatsUploadType):this.reportPCStats(Date.now(),!1,hI.DISCONNECTED_OR_FAILED)))}}function hk(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PChannel.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s)}finally{i()}},i}function uk(e){let t=vk();return function(e,t){let i=e.appId;void 0!==i&&(xk(t,10),Nk(t,i));let n=e.cid;void 0!==n&&(xk(t,16),xk(t,n));let r=e.cname;void 0!==r&&(xk(t,26),Nk(t,r));let s=e.deviceId;void 0!==s&&(xk(t,34),Nk(t,s));let o=e.elapse;void 0!==o&&(xk(t,40),Vk(t,o));let a=e.fileSize;void 0!==a&&(xk(t,48),Vk(t,Rk(a)));let c=e.height;void 0!==c&&(xk(t,56),Vk(t,Rk(c)));let d=e.jpg;void 0!==d&&(xk(t,66),xk(t,d.length),function(e,t){let i=bk(e,t.length);e.bytes.set(t,i)}(t,d));let l=e.networkType;void 0!==l&&(xk(t,72),Vk(t,Rk(l)));let h=e.osType;void 0!==h&&(xk(t,80),Vk(t,Rk(h)));let u=e.requestId;void 0!==u&&(xk(t,90),Nk(t,u));let p=e.sdkVersion;void 0!==p&&(xk(t,98),Nk(t,p));let _=e.sequence;void 0!==_&&(xk(t,104),Vk(t,Rk(_)));let E=e.sid;void 0!==E&&(xk(t,114),Nk(t,E));let m=e.timestamp;void 0!==m&&(xk(t,120),Vk(t,m));let f=e.uid;void 0!==f&&(xk(t,128),xk(t,f));let g=e.vid;void 0!==g&&(xk(t,136),xk(t,g));let S=e.width;void 0!==S&&(xk(t,144),Vk(t,Rk(S)));let T=e.service;void 0!==T&&(xk(t,152),xk(t,T));let R=e.callbackData;void 0!==R&&(xk(t,162),Nk(t,R));let C=e.jpgEncryption;void 0!==C&&(xk(t,168),xk(t,C));let v=e.requestType;void 0!==v&&(xk(t,176),xk(t,v));let I=e.scorePorn;void 0!==I&&(xk(t,185),Mk(t,I));let y=e.scoreSexy;void 0!==y&&(xk(t,193),Mk(t,y));let A=e.scoreNeutral;void 0!==A&&(xk(t,201),Mk(t,A));let b=e.scene;void 0!==b&&(xk(t,208),xk(t,b));let w=e.ossFilePrefix;void 0!==w&&(xk(t,218),Nk(t,w));let O=e.serviceVendor;if(void 0!==O)for(let e of O){xk(t,226);let i=vk();Ek(e,i),xk(t,i.limit),Dk(t,i),Ik(i)}}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function pk(e){return function(e){let t={};e:for(;!Ak(e);){let i=Uk(e);switch(i>>>3){case 0:break e;case 1:t.code=Uk(e);break;case 2:t.msg=Ok(e,Uk(e));break;case 3:{let i=mk(e);t.data=_k(e),e.limit=i;break}default:fk(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function _k(e){let t={};e:for(;!Ak(e);){let i=Uk(e);switch(i>>>3){case 0:break e;case 1:t.requestId=Ok(e,Uk(e));break;case 2:t.requestType=Uk(e)>>>0;break;case 3:t.scorePorn=kk(e);break;case 4:t.scoreSexy=kk(e);break;case 5:t.scoreNeutral=kk(e);break;case 6:t.requestScene=Uk(e)>>>0;break;case 7:t.scene=Uk(e)>>>0;break;default:fk(e,7&i)}}return t}function Ek(e,t){let i=e.service;void 0!==i&&(xk(t,8),xk(t,i));let n=e.vendor;void 0!==n&&(xk(t,16),xk(t,n));let r=e.token;void 0!==r&&(xk(t,26),Nk(t,r));let s=e.callbackUrl;void 0!==s&&(xk(t,34),Nk(t,s))}function mk(e){let t=Uk(e),i=e.limit;return e.limit=e.offset+t,i}function fk(e,t){switch(t){case 0:for(;128&Pk(e););break;case 2:yk(e,Uk(e));break;case 5:yk(e,4);break;case 1:yk(e,8);break;default:throw new Error("Unimplemented type: "+t)}}Lv([hk,kv("design:type",Function),kv("design:paramtypes",[Object,Boolean]),kv("design:returntype",tg)],lk.prototype,"startP2PConnection",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[Object,Object,Array,Object,String,String]),kv("design:returntype",tg)],lk.prototype,"connect",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[Object,Object,Array,Object,String,String]),kv("design:returntype",tg)],lk.prototype,"preConnect",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],lk.prototype,"publishDataChannel",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],lk.prototype,"unpublish",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],lk.prototype,"unpublishDataChannel",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],lk.prototype,"unpublishLowStream",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[bP,Array]),kv("design:returntype",tg)],lk.prototype,"subscribeDataChannel",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[bP,String,Number,Number,Array]),kv("design:returntype",tg)],lk.prototype,"subscribe",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],lk.prototype,"massSubscribe",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[bP,String,Boolean]),kv("design:returntype",tg)],lk.prototype,"unsubscribe",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[bP,Array]),kv("design:returntype",tg)],lk.prototype,"unsubscribeDataChannel",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],lk.prototype,"massUnsubscribe",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[bP,String]),kv("design:returntype",tg)],lk.prototype,"muteRemote",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[bP,String]),kv("design:returntype",tg)],lk.prototype,"unmuteRemote",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[bP,String]),kv("design:returntype",tg)],lk.prototype,"hasRemoteMediaWithLock",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],lk.prototype,"disconnectForReconnect",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],lk.prototype,"updateBitrateLimit",null),Lv([hk,kv("design:type",Function),kv("design:paramtypes",[bP,String,Number]),kv("design:returntype",tg)],lk.prototype,"remoteMediaSsrcChanged",null);let gk=new Float32Array(1);new Uint8Array(gk.buffer);let Sk=new Float64Array(1),Tk=new Uint8Array(Sk.buffer);function Rk(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let Ck=[];function vk(){const e=Ck.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function Ik(e){Ck.push(e)}function yk(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function Ak(e){return e.offset>=e.limit}function bk(e,t){let i=e.bytes,n=e.offset,r=e.limit,s=n+t;if(s>i.length){let t=new Uint8Array(2*s);t.set(i),e.bytes=t}return e.offset=s,s>r&&(e.limit=s),n}function wk(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function Ok(e,t){let i=wk(e,t),n=String.fromCharCode,r=e.bytes,s="�",o="";for(let e=0;e<t;e++){let a,c,d,l,h=r[e+i];0==(128&h)?o+=n(h):192==(224&h)?e+1>=t?o+=s:(a=r[e+i+1],128!=(192&a)?o+=s:(l=(31&h)<<6|63&a,l<128?o+=s:(o+=n(l),e++))):224==(240&h)?e+2>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?o+=s:(l=(15&h)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?o+=s:(o+=n(l),e+=2))):240==(248&h)?e+3>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?o+=s:(l=(7&h)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?o+=s:(l-=65536,o+=n(55296+(l>>10),56320+(1023&l)),e+=3))):o+=s}return o}function Nk(e,t){let i=t.length,n=0;for(let e=0;e<i;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<i&&(r=(r<<10)+t.charCodeAt(++e)-56613888),n+=r<128?1:r<2048?2:r<65536?3:4}xk(e,n);let r=bk(e,n),s=e.bytes;for(let e=0;e<i;e++){let n=t.charCodeAt(e);n>=55296&&n<=56319&&e+1<i&&(n=(n<<10)+t.charCodeAt(++e)-56613888),n<128?s[r++]=n:(n<2048?s[r++]=n>>6&31|192:(n<65536?s[r++]=n>>12&15|224:(s[r++]=n>>18&7|240,s[r++]=n>>12&63|128),s[r++]=n>>6&63|128),s[r++]=63&n|128)}}function Dk(e,t){let i=bk(e,t.limit),n=e.bytes,r=t.bytes;for(let e=0,s=t.limit;e<s;e++)n[e+i]=r[e]}function Pk(e){return e.bytes[wk(e,1)]}function Lk(e,t){let i=bk(e,1);e.bytes[i]=t}function kk(e){let t=wk(e,8),i=e.bytes;return Tk[0]=i[t++],Tk[1]=i[t++],Tk[2]=i[t++],Tk[3]=i[t++],Tk[4]=i[t++],Tk[5]=i[t++],Tk[6]=i[t++],Tk[7]=i[t++],Sk[0]}function Mk(e,t){let i=bk(e,8),n=e.bytes;Sk[0]=t,n[i++]=Tk[0],n[i++]=Tk[1],n[i++]=Tk[2],n[i++]=Tk[3],n[i++]=Tk[4],n[i++]=Tk[5],n[i++]=Tk[6],n[i++]=Tk[7]}function Uk(e){let t,i=0,n=0;do{t=Pk(e),i<32&&(n|=(127&t)<<i),i+=7}while(128&t);return n}function xk(e,t){for(t>>>=0;t>=128;)Lk(e,127&t|128),t>>>=7;Lk(e,t)}function Vk(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,s=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,o=bk(e,s),a=e.bytes;switch(s){case 10:a[o+9]=r>>>7&1;case 9:a[o+8]=9!==s?128|r:127&r;case 8:a[o+7]=8!==s?n>>>21|128:n>>>21&127;case 7:a[o+6]=7!==s?n>>>14|128:n>>>14&127;case 6:a[o+5]=6!==s?n>>>7|128:n>>>7&127;case 5:a[o+4]=5!==s?128|n:127&n;case 4:a[o+3]=4!==s?i>>>21|128:i>>>21&127;case 3:a[o+2]=3!==s?i>>>14|128:i>>>14&127;case 2:a[o+1]=2!==s?i>>>7|128:i>>>7&127;case 1:a[o]=1!==s?128|i:127&i}}function Fk(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const Bk=new Map([["moderation",1],["supervise",2]]);class jk extends iS{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(gI.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=cT(t=e.map((e=>Bk.get(e)||0))).call(t,((e,t)=>e+t)),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this.qualityRatio}),6e4))}constructor(e){super(),nu(this,"name","AgoraRTCVideoContentInspect"),nu(this,"_connectionState",mI.CONNECTING),nu(this,"_innerConnectionState",void 0),nu(this,"sequence",0),nu(this,"inspectStartTime",void 0),nu(this,"workerManagerConnection",void 0),nu(this,"workerConnection",void 0),nu(this,"workerMessageLengthLimit",void 0),nu(this,"inspectIntervalMinimum",void 0),nu(this,"qualityRatio",void 0),nu(this,"_connectInfo",void 0),nu(this,"_cancelTokenSource",EC.CancelToken.source()),nu(this,"_retryConfig",void 0),nu(this,"wmSequence",0),nu(this,"inspectInterval",void 0),nu(this,"inspectTimer",null),nu(this,"ossFilePrefix",void 0),nu(this,"extraInfo",void 0),nu(this,"_inspectType",void 0),nu(this,"_inspectMode",void 0),nu(this,"_quality",1),nu(this,"qualityTimer",null),nu(this,"_inspectId",void 0),nu(this,"_needWorkUrlOnly",!1),nu(this,"inspectImage",(()=>{if(this.connectionState!==mI.CONNECTED)throw new Mv(xg.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===mI.CONNECTED?this.requestToInspectImage():WC.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()})),this._inspectId=xS(5,"inspect-"),this.workerMessageLengthLimit=kC("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=kC("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=kC("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new JI("worker-manager-"+this._inspectId,JS),this.on(gI.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,WC.debug("[".concat(this._inspectId,"] Inspect operation :").concat(fI[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new JI("worker-"+this._inspectId,JS),this.handleWorkerEvents()}async init(e,t){this.emit(gI.STATE_CHANGE,fI.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new tg(((n,r)=>{this.on(gI.CONNECTION_STATE_CHANGE,((e,t)=>{t===mI.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{r(e)}))}))}async requestAP(e,t,i){const n=kC("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,i,n){let{appId:r,areaCode:s,cname:o,sid:a,token:c,uid:d}=t;nP++;const l="image_moderation_api",h={service_name:l,json_body:JSON.stringify({appId:r,areaCode:s,cname:o,command:"allocateEdge",requestId:nP,seq:nP,sid:a,token:c,ts:Date.now(),uid:d+""})};let u,p,_=e[0];return XS((async()=>{u=Date.now();const e=await MD(_,{data:h,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-u,0!==e.code){const t=new Mv(xg.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw WC.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new Mv(xg.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw WC.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new Mv(xg.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw WC.error(e.toString()),e}const n=kC("VIDEO_INSPECT_WORKER_MANAGER_HOST"),r=kC("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(r||i)})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,responseTime:p}}),((t,i)=>(iv.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1)),((t,i)=>(iv.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==xg.OPERATION_ABORTED&&t.code!==xg.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(gI.STATE_CHANGE,fI.AP_CONNECTED);const{addressList:s}=r;return this.wmSequence++,s}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(gI.STATE_CHANGE,fI.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(Cv.CONNECTED,(async()=>{this.emit(gI.STATE_CHANGE,fI.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.19.1",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)})),this.workerManagerConnection.on(Cv.CLOSED,(()=>{this._innerConnectionState<fI.GET_WORKER_MANAGER_RESPONSE&&WC.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(Cv.FAILED,(()=>{this._innerConnectionState<fI.GET_WORKER_MANAGER_RESPONSE&&WC.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))})),this.workerManagerConnection.on(Cv.RECONNECTING,(()=>{this._innerConnectionState<fI.GET_WORKER_MANAGER_RESPONSE&&WC.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(Cv.ON_MESSAGE,(async e=>{this.emit(gI.STATE_CHANGE,fI.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw WC.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new Mv(xg.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw WC.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new Mv(xg.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{const e=kC("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,n=t.replace(/:\d+\/?$/,":".concat(e));this.emit(gI.STATE_CHANGE,fI.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit(gI.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n)}})),this.workerManagerConnection.on(Cv.WILL_RECONNECT,((e,t,i)=>{i(e)})),this.workerManagerConnection.on(Cv.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(Cv.CONNECTED,(async()=>{this.emit(gI.STATE_CHANGE,fI.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=mI.CONNECTED})),this.workerConnection.on(Cv.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const i=pk(new Uint8Array(e.data));if(kC("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&WC.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(i)),200===i.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(gI.INSPECT_RESULT,void 0,void 0);if(i.data&&i.data.scorePorn&&i.data.scoreSexy&&i.data.scoreNeutral){var t;const e={porn:i.data.scorePorn,sexy:i.data.scoreSexy,neutral:i.data.scoreNeutral},n=cT(t=Object.keys(e)).call(t,((t,i)=>e[t]>e[i]?t:i),"porn"),r=Object.keys(e).find((e=>e===n));this.emit(gI.INSPECT_RESULT,r)}else this.emit(gI.INSPECT_RESULT,void 0,new Mv(xg.UNEXPECTED_RESPONSE,i.code+"","There is an unexpected data on message"))}else this.emit(gI.INSPECT_RESULT,void 0,new Mv(xg.UNEXPECTED_RESPONSE,i.code+"",i.msg))}else WC.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(gI.INSPECT_RESULT,void 0,new Mv(xg.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(Cv.CLOSED,(()=>{this.connectionState=mI.CLOSED})),this.workerConnection.on(Cv.FAILED,(()=>{this.connectionState=mI.CLOSED})),this.workerConnection.on(Cv.RECONNECTING,(()=>{this.connectionState=this.connectionState===mI.CONNECTED?mI.RECONNECTING:mI.CONNECTING})),this.workerConnection.on(Cv.WILL_RECONNECT,((e,t,i)=>{"recover"===e&&i(e),i("tryNext")})),this.workerConnection.on(Cv.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(gI.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){this.sequence++;const e=SS(this,gI.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(gI.INSPECT_RESULT,void 0,new Mv(xg.INVALID_OPERATION,"Only the track being played can be inspected"));const i=await this.generateRequestData(e,t);this.workerConnection.sendMessage(i,!0,!0)}else this.emit(gI.INSPECT_RESULT,void 0,new Mv(xg.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await _b(d,i,n),h=this.sequence+"-"+r+"-"+a+"-"+c+"-"+xS(12,""),u={appId:i,cid:r,cname:n,deviceId:"",elapse:jk.intToLong(Number(c-this.inspectStartTime)),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:h,sdkVersion:"4.19.1",sequence:this.sequence,sid:o,timestamp:jk.intToLong(c),uid:a,vid:s,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete u.callbackData,void 0===this.ossFilePrefix&&delete u.ossFilePrefix;const p=uk(u);if(p.byteLength<this.workerMessageLengthLimit){if(kC("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Fk(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Fk(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},u);delete e.jpg,WC.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return p}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=EC.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=mI.CLOSED,this.emit(gI.STATE_CHANGE,fI.CLOSED)}}function Gk(e){let t=function(){const e=Yk.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(e,t){let i=e.appId;void 0!==i&&(nM(t,10),$k(t,i));let n=e.cid;void 0!==n&&(nM(t,16),nM(t,n));let r=e.cname;void 0!==r&&(nM(t,26),$k(t,r));let s=e.deviceId;void 0!==s&&(nM(t,34),$k(t,s));let o=e.elapse;void 0!==o&&(nM(t,40),sM(t,o));let a=e.fileSize;void 0!==a&&(nM(t,48),sM(t,Kk(a)));let c=e.height;void 0!==c&&(nM(t,56),sM(t,Kk(c)));let d=e.jpg;void 0!==d&&(nM(t,66),nM(t,d.length),Qk(t,d));let l=e.networkType;void 0!==l&&(nM(t,72),sM(t,Kk(l)));let h=e.osType;void 0!==h&&(nM(t,80),sM(t,Kk(h)));let u=e.requestId;void 0!==u&&(nM(t,90),$k(t,u));let p=e.sdkVersion;void 0!==p&&(nM(t,98),$k(t,p));let _=e.sequence;void 0!==_&&(nM(t,104),sM(t,Kk(_)));let E=e.sid;void 0!==E&&(nM(t,114),$k(t,E));let m=e.timestamp;void 0!==m&&(nM(t,120),sM(t,m));let f=e.uid;void 0!==f&&(nM(t,128),nM(t,f));let g=e.vid;void 0!==g&&(nM(t,136),nM(t,g));let S=e.width;void 0!==S&&(nM(t,144),sM(t,Kk(S)));let T=e.service;void 0!==T&&(nM(t,152),nM(t,T));let R=e.callbackData;void 0!==R&&(nM(t,162),nM(t,R.length),Qk(t,R));let C=e.ticket;void 0!==C&&(nM(t,170),$k(t,C))}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function Wk(e){return function(e){let t={};e:for(;!Jk(e);){let i=iM(e);switch(i>>>3){case 0:break e;case 1:t.code=iM(e);break;case 2:t.msg=Zk(e,iM(e));break;case 3:t.requestId=Zk(e,iM(e));break;case 4:t.timestamp=rM(e,!1);break;default:Hk(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function Hk(e,t){switch(t){case 0:for(;128&eM(e););break;case 2:qk(e,iM(e));break;case 5:qk(e,4);break;case 1:qk(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function Kk(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let Yk=[];function qk(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function Jk(e){return e.offset>=e.limit}function zk(e,t){let i=e.bytes,n=e.offset,r=e.limit,s=n+t;if(s>i.length){let t=new Uint8Array(2*s);t.set(i),e.bytes=t}return e.offset=s,s>r&&(e.limit=s),n}function Xk(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function Qk(e,t){let i=zk(e,t.length);e.bytes.set(t,i)}function Zk(e,t){let i=Xk(e,t),n=String.fromCharCode,r=e.bytes,s="�",o="";for(let e=0;e<t;e++){let a,c,d,l,h=r[e+i];0==(128&h)?o+=n(h):192==(224&h)?e+1>=t?o+=s:(a=r[e+i+1],128!=(192&a)?o+=s:(l=(31&h)<<6|63&a,l<128?o+=s:(o+=n(l),e++))):224==(240&h)?e+2>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?o+=s:(l=(15&h)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?o+=s:(o+=n(l),e+=2))):240==(248&h)?e+3>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?o+=s:(l=(7&h)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?o+=s:(l-=65536,o+=n(55296+(l>>10),56320+(1023&l)),e+=3))):o+=s}return o}function $k(e,t){let i=t.length,n=0;for(let e=0;e<i;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<i&&(r=(r<<10)+t.charCodeAt(++e)-56613888),n+=r<128?1:r<2048?2:r<65536?3:4}nM(e,n);let r=zk(e,n),s=e.bytes;for(let e=0;e<i;e++){let n=t.charCodeAt(e);n>=55296&&n<=56319&&e+1<i&&(n=(n<<10)+t.charCodeAt(++e)-56613888),n<128?s[r++]=n:(n<2048?s[r++]=n>>6&31|192:(n<65536?s[r++]=n>>12&15|224:(s[r++]=n>>18&7|240,s[r++]=n>>12&63|128),s[r++]=n>>6&63|128),s[r++]=63&n|128)}}function eM(e){return e.bytes[Xk(e,1)]}function tM(e,t){let i=zk(e,1);e.bytes[i]=t}function iM(e){let t,i=0,n=0;do{t=eM(e),i<32&&(n|=(127&t)<<i),i+=7}while(128&t);return n}function nM(e,t){for(t>>>=0;t>=128;)tM(e,127&t|128),t>>>=7;tM(e,t)}function rM(e,t){let i,n=0,r=0,s=0;return i=eM(e),n=127&i,128&i&&(i=eM(e),n|=(127&i)<<7,128&i&&(i=eM(e),n|=(127&i)<<14,128&i&&(i=eM(e),n|=(127&i)<<21,128&i&&(i=eM(e),r=127&i,128&i&&(i=eM(e),r|=(127&i)<<7,128&i&&(i=eM(e),r|=(127&i)<<14,128&i&&(i=eM(e),r|=(127&i)<<21,128&i&&(i=eM(e),s=127&i,128&i&&(i=eM(e),s|=(127&i)<<7))))))))),{low:n|r<<28,high:r>>>4|s<<24,unsigned:t}}function sM(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,s=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,o=zk(e,s),a=e.bytes;switch(s){case 10:a[o+9]=r>>>7&1;case 9:a[o+8]=9!==s?128|r:127&r;case 8:a[o+7]=8!==s?n>>>21|128:n>>>21&127;case 7:a[o+6]=7!==s?n>>>14|128:n>>>14&127;case 6:a[o+5]=6!==s?n>>>7|128:n>>>7&127;case 5:a[o+4]=5!==s?128|n:127&n;case 4:a[o+3]=4!==s?i>>>21|128:i>>>21&127;case 3:a[o+2]=3!==s?i>>>14|128:i>>>14&127;case 2:a[o+1]=2!==s?i>>>7|128:i>>>7&127;case 1:a[o]=1!==s?128|i:127&i}}const oM={},aM={},cM=4294967296,dM=cM*cM,lM=dM/2,hM=mM(0,!0),uM=mM(0),pM=fM(0,-2147483648,!1),_M=fM(-1,2147483647,!1),EM=fM(-1,-1,!0);function mM(e,t){let i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=aM[e],n)?n:(i=fM(e,0,!0),r&&(aM[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=oM[e],n)?n:(i=fM(e,e<0?-1:0,!1),r&&(oM[e]=i),i)}function fM(e,t,i){return{low:0|e,high:0|t,unsigned:!!i}}function gM(e,t){if(isNaN(e))return t?hM:uM;if(t){if(e<0)return hM;if(e>=dM)return EM}else{if(e<=-lM)return pM;if(e+1>=lM)return _M}return e<0?t?hM:uM:fM(e%cM|0,e/cM|0,t)}function SM(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class TM extends iS{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(II.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this._qualityRatio}),6e4))}constructor(e){var t;super(),nu(this,"name","AgoraRTCImageModeration"),nu(this,"_connectionState",vI.CONNECTING),nu(this,"_sequence",0),nu(this,"_moderationStartTime",void 0),nu(this,"_workerConnection",void 0),nu(this,"_workerMessageLengthLimit",void 0),nu(this,"_qualityRatio",void 0),nu(this,"_connectInfo",void 0),nu(this,"_cancelTokenSource",EC.CancelToken.source()),nu(this,"_retryConfig",void 0),nu(this,"_moderationInterval",void 0),nu(this,"_moderationTimer",null),nu(this,"_moderationMode",1),nu(this,"_quality",1),nu(this,"_qualityTimer",null),nu(this,"_ticket",void 0),nu(this,"_moderationIntervalMinimum",void 0),nu(this,"_uploadFailedNum",0),nu(this,"_uploadNum",0),nu(this,"_uploadTimer",null),nu(this,"_moderationId",void 0),nu(this,"inspectImage",(()=>{if(this.connectionState!==vI.CONNECTED)throw new Mv(xg.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===vI.CONNECTED?this.requestToInspectImage():WC.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()})),this._moderationId=xS(5,"image-moderation-"),this._workerMessageLengthLimit=kC("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=kC("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,this._qualityRatio=kC("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new JI("worker-"+this._moderationId,JS),this.on(II.STATE_CHANGE,((e,t)=>{WC.debug("[".concat(this._moderationId,"] Moderation operation :").concat(yI[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(II.STATE_CHANGE,yI.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new tg(((n,r)=>{this.on(II.CONNECTION_STATE_CHANGE,((e,t)=>{e===vI.CONNECTED&&n()})),this.requestAP(e,i,t).then((e=>{this.connectWorker(e)})).catch((e=>{r(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,WC.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===vI.CONNECTED&&this.inspectImage()}async requestAP(e,t,i){const n=kC("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,i,n){let{appId:r,areaCode:s,cname:o,sid:a,token:c,uid:d}=t;nP++;const l="moderation_plugin",h={service_name:l,json_body:JSON.stringify({appId:r,areaCode:s,cname:o,command:"allocateEdge",requestId:nP,seq:nP,sid:a,appToken:c,ts:Date.now(),uid:d+""})};let u,p,_=e[0];return XS((async()=>{u=Date.now();const e=await MD(_,{data:h,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-u,0!==e.code){const t=new Mv(xg.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw WC.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new Mv(xg.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw WC.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new Mv(xg.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw WC.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new Mv(xg.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw WC.error(e.toString()),e}const n=kC("IMAGE_MODERATION_WORKER_HOST");return{addressList:t.servers.map((e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(i,"/moderation")})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p}}),((t,i)=>(iv.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1)),((t,i)=>(iv.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==xg.OPERATION_ABORTED&&t.code!==xg.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0))),n)}(n,e,t,i);this.emit(II.STATE_CHANGE,yI.AP_CONNECTED);const{addressList:s,ticket:o}=r;return this._ticket=o,s}async connectWorker(e){this.emit(II.STATE_CHANGE,yI.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(Cv.CONNECTED,(async()=>{this.emit(II.STATE_CHANGE,yI.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=vI.CONNECTED})),this._workerConnection.on(Cv.CLOSED,(()=>{this.connectionState=vI.CLOSED})),this._workerConnection.on(Cv.FAILED,(()=>{this.connectionState=vI.CLOSED})),this._workerConnection.on(Cv.RECONNECTING,(()=>{this.connectionState=this.connectionState===vI.CONNECTED?vI.RECONNECTING:vI.CONNECTING})),this._workerConnection.on(Cv.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=Wk(new Uint8Array(e.data));kC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&WC.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,WC.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{iv.reportApiInvoke(this._connectInfo.sid||null,{name:sS.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:oS.TRACER}).onError(new Mv(xg.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),kC("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else WC.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(Cv.WILL_RECONNECT,((e,t,i)=>{"recover"===e&&i(e),i("tryNext")})),this._workerConnection.on(Cv.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){const e=SS(this,II.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(kC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&WC.debug("Only the track being played can be inspected"));this._sequence++;const i=await this.generateRequestData(e,t);this._workerConnection.sendMessage(i,!0,!0)}else kC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&WC.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await _b(d,i,n),h=this._sequence+"-"+r+"-"+a+"-"+c+"-"+xS(12,""),u={appId:i,cid:r,cname:n,deviceId:"",elapse:TM.intToLong(Number(c-this._moderationStartTime)),fileSize:d.buffer.byteLength,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:h,sdkVersion:"4.19.1",sequence:this._sequence,sid:o,timestamp:gM(c),uid:a,vid:s,service:this._moderationMode,ticket:this._ticket},p=Gk(u);if(p.byteLength<this._workerMessageLengthLimit){if(kC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?SM(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):SM(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},u);delete e.jpg,WC.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e))}return p}{const t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=EC.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=vI.CLOSED,this.emit(II.STATE_CHANGE,yI.CLOSED)}}function RM(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function CM(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?RM(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):RM(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class vM extends OI{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}constructor(e,t,i){super(e,t),nu(this,"direction",void 0),nu(this,"store",void 0),nu(this,"peerConnection",void 0),nu(this,"transportEventReceiver",void 0),nu(this,"statsFilter",void 0),nu(this,"localCandidateCount",0),nu(this,"allCandidatesReceived",!1),nu(this,"mutex",new YS("P2PConnection-mutex")),nu(this,"dataChannel",void 0),nu(this,"onLocalCandidate",void 0),this.store=t,this.peerConnection=new RTCPeerConnection(vM.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.direction=null!=i?i:Rv.SEND_ONLY,this.dataChannel=this.peerConnection.createDataChannel("agora-p2p-signal",{ordered:!0}),this.statsFilter=wL(this.peerConnection,kC("STATS_UPDATE_INTERVAL"),void 0,Rg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1}async establish(e){try{if(e){await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();if(await this.peerConnection.setLocalDescription(t),!t.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");return t.sdp}{const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");return await this.peerConnection.setLocalDescription(e),e.sdp}}catch(e){throw new Vg(xg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{await this.peerConnection.setRemoteDescription({type:"answer",sdp:e})}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async addRemoteCandidate(e){try{await this.peerConnection.addIceCandidate(e)}catch(e){throw new Vg(xg.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()))}}async send(e){try{const t=[];e.forEach((e=>{const i=this.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});t.push(i)})),Rg()&&!0===kC("SIMULCAST")&&await this.applySimulcastForFirefox(t,e),await this.applySimulcastEncodings(t,e),await this.applySendEncodings(t,e);const i=await this.peerConnection.createOffer();if(await this.peerConnection.setLocalDescription(i),!i.sdp)throw new Error("Cannot get offer.sdp when trying to send PeerConnection.");const n=t.map((e=>{const t=this.getLocalSSRC(e.mid,i.sdp);if(!t)throw new Error("Cannot get ssrc when trying to send PeerConnection.");return{mid:e.mid,localSSRC:[{ssrcId:t}]}}));return{sdp:i.sdp,trackMessage:n}}catch(e){throw e instanceof Vg?e:new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length (".concat(t.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));t.map((e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e),this.peerConnection.removeTrack(e.sender)}));const i=await this.peerConnection.createOffer();if(await this.peerConnection.setLocalDescription(i),!i.sdp)throw new Error("Cannot get offer.sdp when trying to send PeerConnection.");return i.sdp}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i){try{await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();if(!n.sdp)throw new Error("Cannot get answer sdp when trying to receive track.");await this.peerConnection.setLocalDescription(n),WC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."));const r=this.getRemoteMid(i,t);if(void 0===r)throw new Error("Cannot get transceiver mid when trying to receive track.");const s=this.peerConnection.getTransceivers().find((e=>e.mid===r));if(!s||null===s.mid)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,mid:s.mid,sdp:n.sdp}}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async setDescription(e,t){try{if("remote"===e){await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();if(!i.sdp)throw new Error("Cannot get answer sdp when trying to receive track.");return await this.peerConnection.setLocalDescription(i),WC.debug("[".concat(this.store.clientId,"] [P2PConnection] exchanging SDP, type is ").concat(e)),i.sdp}await this.peerConnection.setRemoteDescription({type:"answer",sdp:t})}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection.setDescription failed; ".concat(e.toString()))}}async stopReceiving(e,t){try{const i=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(i.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");i.map((e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)})),await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();if(await this.peerConnection.setLocalDescription(n),!n.sdp)throw new Error("Cannot get answer sdp when trying to receive track.");return n.sdp}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async restartICE(){try{const e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");return this.store.descriptionStart(),await this.peerConnection.setLocalDescription(e),e.sdp}catch(e){throw new Vg(xg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transportEventReceiver=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===i.length&&(this.isVP8Simulcast(t)?Rg()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find((e=>e.mid===t));i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return{local:CM(CM({},uL),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:CM(CM({},uL),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate)),e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,WC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,WC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),kC("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(_S(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...vM.turnServerConfigToIceServers(e.turnServer.servers)),kC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...vM.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),kC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(t.iceTransportPolicy="relay")})))),kC("ENABLE_ENCODED_TRANSFORM")&&hA().supportWebRTCEncodedTransform&&(t.encodedInsertableStreams=!0),t}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.tcpport&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(hD(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"stun:".concat(e.turnServerURL,":").concat(e.tcpport)}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:e,remote:t}=i.getSelectedCandidatePair();WC.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port})," )"))}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i;if(t||(t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))),!t)return WC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return WC.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!hA().supportSetRtpSenderParameters)return WC.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n={},r={};switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced"}if(e._encoderConfig){var s;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),Lr(s=e._hints).call(s,Dy.LOW_STREAM)&&(i&&(r.maxFramerate=pD(i)),n&&n>=1&&(r.scaleResolutionDownBy=n))}if(kC("DSCP_TYPE")&&kg()){var o;const e=kC("DSCP_TYPE");Lr(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e)}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];Rg()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),WC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!hA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i<e.length;i++){const n=e[i],r=t[i];r instanceof fb&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,n.sender)}}catch(e){WC.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){const n=GP.parse(e);return t.forEach(((e,t)=>{const r=i[t],s=n.mediaDescriptions.find((e=>e.attributes.mid===r));s&&(XP(s,e),tL(s,e,this.store.codec))})),GP.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var i,n,r,s,o;const c=e[a],d=t[a];if(d instanceof fb&&!Lr(i=d._hints).call(i,Dy.LOW_STREAM)&&null!==(n=d._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Rg()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof fb&&this.isVP8Simulcast(n)){const t=e[i],r={},s={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:s.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:s.medium,scaleResolutionDownBy:4}];const o=t.sender.getParameters();await t.sender.setParameters(Object.assign(o,r))}}}isVP8Simulcast(e){var t,i,n,r,s;return!!(e instanceof fb&&kC("SIMULCAST")&&"vp8"===this.store.codec&&!Lr(t=e._hints).call(t,Dy.LOW_STREAM)&&null!==(i=e._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=e._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(kC("SDP_LOGGING"))return WC.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}getLocalSSRC(e,t){var i,n;if(t=null!==(i=t)&&void 0!==i?i:null===(n=this.currentLocalDescription)||void 0===n?void 0:n.sdp){var r;const i=null===(r=GP.parse(t).mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===r?void 0:r.attributes.ssrcs;return null==i?void 0:i[0].ssrcId}}getRemoteMid(e,t){var i,n,r;if(t=null!==(i=t)&&void 0!==i?i:null===(n=this.currentRemoteDescription)||void 0===n?void 0:n.sdp)return null===(r=GP.parse(t).mediaDescriptions.find((t=>t.attributes.ssrcs.some((t=>t.ssrcId===e)))))||void 0===r?void 0:r.attributes.mid}async getRemoteSSRC(e,t){var i,n;if(t=null!==(i=t)&&void 0!==i?i:null===(n=this.currentRemoteDescription)||void 0===n?void 0:n.sdp){var r;const i=null===(r=GP.parse(t).mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===r?void 0:r.attributes.ssrcs;return null==i?void 0:i[0].ssrcId}}}function IM(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return await n.apply(this,s)}finally{i()}},i}var yM;function AM(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function bM(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?AM(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):AM(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}Lv([IM,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],vM.prototype,"establish",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],vM.prototype,"connect",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[RTCIceCandidate]),kv("design:returntype",tg)],vM.prototype,"addRemoteCandidate",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],vM.prototype,"send",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[String,String,Number]),kv("design:returntype",tg)],vM.prototype,"receive",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[String,String]),kv("design:returntype",tg)],vM.prototype,"setDescription",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[Array,String]),kv("design:returntype",tg)],vM.prototype,"stopReceiving",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],vM.prototype,"restartICE",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],vM.prototype,"close",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[String,$y]),kv("design:returntype",tg)],vM.prototype,"updateEncoderConfig",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[String,$y]),kv("design:returntype",tg)],vM.prototype,"updateSendParameters",null),Lv([IM,kv("design:type",Function),kv("design:paramtypes",[$y,String]),kv("design:returntype",tg)],vM.prototype,"replaceTrack",null),function(e){e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY"}(yM||(yM={}));class wM extends iS{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(_I.StateChange,t,this._state)}constructor(e,t){super(),nu(this,"store",void 0),nu(this,"statsUploader",void 0),nu(this,"sendConnection",void 0),nu(this,"recvConnection",void 0),nu(this,"localTrackMap",new Map),nu(this,"remoteUserMap",new Map),nu(this,"localDataChannels",[]),nu(this,"pendingLocalTracks",[]),nu(this,"pendingRemoteTracks",[]),nu(this,"statsCollector",void 0),nu(this,"dtlsFailedCount",0),nu(this,"sendMutex",new YS("P2PChannel2-send-mutex")),nu(this,"recvMutex",new YS("P2PChannel2-recv-mutex")),nu(this,"_state",pI.Disconnected),nu(this,"_restartStates",["disconnected","failed"]),nu(this,"_restartTimer",void 0),nu(this,"handleMuteLocalTrack",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==pI.Connected)return void i(new Vg(xg.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const n=this.filterTobeMutedTracks(e);if(0===n.length)return void t();const o=n.find((e=>"videoLowTrack"===e[0]));o&&o[1].track._originMediaStreamTrack.stop();let a=!1;var r,s;a="video"===e.trackMediaType?!(null===(r=this.localTrackMap.get(uI.LocalAudioTrack))||void 0===r||!r.track._muted):void 0===(null===(s=this.localTrackMap.get(uI.LocalVideoTrack))||void 0===s?void 0:s.id);const c=n.filter((e=>{let[t,i]=e;return(t!==uI.LocalAudioTrack||a)&&void 0!==i.id})).map((e=>{let[,t]=e;return t}));let d;c.length>0&&(d=await this.sendConnection.stopSending(c.map((e=>e.id))),c.forEach((e=>{e.id=void 0,e.ssrcs=void 0})));const l=this.createMuteMessage(n),h="video"===e.trackMediaType?bI.MUTE_LOCAL_VIDEO:bI.MUTE_LOCAL_AUDIO,u=await fS(this,_I.RequestP2PMuteLocal,{action:h,sdp:d,message:l,isMuteAll:a});u&&await this.sendConnection.setDescription("local",u),(d||"audio"===e.trackMediaType)&&await gS(this,_I.RequestMuteLocal,l),t()}catch(e){i(e)}finally{n()}})),nu(this,"handleUnmuteLocalTrack",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==pI.Connected)return void i(new Vg(xg.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const n=this.filterTobeUnmutedTracks(e);if(0===n.length)return void t();const r=this.createUnmuteMessage(n),s="video"===e.trackMediaType?bI.UNMUTE_LOCAL_VIDEO:bI.UNMUTE_LOCAL_AUDIO;await gS(this,_I.RequestP2PMuteLocal,{action:s,message:r}),t()}catch(e){i(e)}finally{n()}})),nu(this,"handleUpdateVideoEncoder",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleSetVideoEncoder");try{const i=this.localTrackMap.get(uI.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==pI.Connected)return void t();const{id:n,track:r}=i;n&&(await this.sendConnection.updateSendParameters(n,r),await this.sendConnection.updateEncoderConfig(n,r),this.emit(_I.UpdateVideoEncoder,r)),t()}catch(e){i(e)}finally{n()}})),nu(this,"handleSetOptimizationMode",(async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleSetOptimizationMode");try{const i=this.localTrackMap.get(uI.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==pI.Connected)return;const{id:n,track:r}=i;n&&await this.sendConnection.updateSendParameters(n,r),t()}catch(e){i(e)}finally{n()}})),nu(this,"handleReplaceTrack",(async(e,t,i,n)=>{let r;WC.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var s;const i=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(!this.sendConnection||!i||void 0===i[1].id||this.state!==pI.Connected)return void t();if(await(null===(s=this.sendConnection)||void 0===s?void 0:s.replaceTrack(e,i[1].id)),i[0]===uI.LocalVideoTrack&&hA().supportDualStreamEncoding){const t=this.localTrackMap.get(uI.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new tg(((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)}))}}t()}catch(e){i(e)}finally{var o;null===(o=r)||void 0===o||o()}})),nu(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),nu(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),nu(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),nu(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new sk,this.bindStatsUploaderEvents()}async startP2PConnection(e,t){throw new Vg(xg.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(e,t,i,n,r,s){throw new Vg(xg.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(e,t){if(this.state=pI.New,this.sendConnection&&(WC.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset P2PConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),this.recvConnection&&(WC.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset P2PConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),this.sendConnection=new vM(e,this.store),this.bindConnectionEvents(this.sendConnection),this.recvConnection=new vM(e,this.store,Rv.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection),t){this.store.peerConnectionStart(),await this.recvConnection.establish(t);const e=await this.sendConnection.establish(t);return this.statsUploader.startUploadTransportStats(!0),this.statsUploader.startUploadExtensionUsageStats(),this.state=pI.Connected,e}return await this.recvConnection.establish(t),this.sendConnection.establish(t)}async p2pConnect(e){if(!this.sendConnection||!this.recvConnection)throw new Vg(xg.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.recvConnection.connect(e),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=pI.Connected}async addRemoteCandidate(e){if(!this.sendConnection||!this.recvConnection)throw new Vg(xg.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e),await this.sendConnection.addRemoteCandidate(e)}async publish(e,t,i){if(!this.sendConnection||this.state!==pI.Connected){this.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===this.pendingLocalTracks.indexOf(e)));return void(this.pendingLocalTracks=this.pendingLocalTracks.concat(t))}this.store.pubId=this.store.pubId+1,sD.markPublishStart(this.store.clientId,this.store.pubId);const n=this.filterTobePublishedTracks(e,t,i);if(0===n.length)return void await this.tryToUnmuteAudio(e);n.forEach((e=>{let{track:t,type:i}=e;const n=Date.now();this.store.publish(t.getTrackId(),i===uI.LocalAudioTrack?"audio":"video",n)})),this.bindLocalTrackEvents(n);const r=this.createGatewayPublishMessage(n);return this.assignLocalTracks(n),n.forEach((e=>{let{track:t,type:i}=e;const n=Date.now();this.store.publish(t.getTrackId(),i===uI.LocalAudioTrack?"audio":"video",void 0,n)})),r}async dopublish(e){if(!this.sendConnection||this.state!==pI.Connected)return;const t=this.localTrackMap.get(e);if(t){const{sdp:i,trackMessage:n}=await this.sendConnection.send([t.track]),{mid:r,localSSRC:s}=n[0];t.id=r,t.ssrcs=s,this.statsCollector.addLocalStats(e),this.statsUploader.startUploadUplinkStats();const o=await fS(this,_I.RequestP2PPublish,{kind:e===uI.LocalAudioTrack?dI.AUDIO:dI.VIDEO,sdp:i,ssrcId:s[0].ssrcId});await this.sendConnection.setDescription("local",o);const a=this.createUnmuteMessage([[e,t]]);await gS(this,_I.RequestUnmuteLocal,a)}}async setDescription(e,t){let i,n;"local"===e?(i=await this.sendMutex.lock("From P2PChannel.restartICE"),n=this.sendConnection):(i=await this.recvMutex.lock("From P2PChannel.restartICE"),n=this.recvConnection);try{if(!n||this.state!==pI.Connected)return;return await n.setDescription(e,t)}finally{i()}}publishLowStream(e){return xP((function*(){throw new Vg(xg.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")}))()}async republish(){this.pendingLocalTracks.length>0&&(WC.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await fS(this,_I.RequestRePublish,this.pendingLocalTracks),this.emit(_I.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublish(e){if(!this.sendConnection||this.state!==pI.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter((t=>!Lr(e).call(e,t))));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}})));const i=t.filter((e=>{let[,{id:t}]=e;return void 0!==t}));if(!this.sendConnection||this.state!==pI.Connected)return void e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}));const n=t.find((e=>"videoLowTrack"===e[0]));let r;n&&n[1].track.close();const s=this.createGatewayUnpublishMessage(t);i.length>0&&(r=await this.sendConnection.stopSending(i.map((e=>{let[,{id:t}]=e;return t})))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let[t,{track:i}]=e;return{type:t,track:i}}))),t.forEach((e=>{let[t]=e;this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadUplinkStats();const o=this.createMuteMessage(t);return await tg.all(o.map((async e=>{await gS(this,_I.RequestMuteLocal,[e])}))),{sdp:r,unpubMsg:s}}async unpublishLowStream(){throw new Vg(xg.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async doUnpublish(e){if(!this.sendConnection||this.state!==pI.Connected)return;const t=[];if(e!==dI.AUDIO){const e=this.localTrackMap.get(uI.LocalVideoTrack);void 0!==(null==e?void 0:e.id)&&t.push([uI.LocalVideoTrack,e]);const i=this.localTrackMap.get(uI.LocalVideoLowTrack);void 0!==(null==i?void 0:i.id)&&t.push([uI.LocalVideoLowTrack,i]),this.statsCollector.removeLocalStats(uI.LocalVideoTrack),this.statsCollector.removeLocalStats(uI.LocalVideoLowTrack)}if(e!==dI.VIDEO){const e=this.localTrackMap.get(uI.LocalAudioTrack);void 0!==(null==e?void 0:e.id)&&t.push([uI.LocalAudioTrack,e]),this.statsCollector.removeLocalStats(uI.LocalAudioTrack)}if(t.length>0){const i=await this.sendConnection.stopSending(t.map((e=>{let[,t]=e;return t.id})));t.forEach((e=>{let[,t]=e;t.id=void 0,t.ssrcs=void 0}));const n=await fS(this,_I.RequestP2PUnPublish,{sdp:i,kind:e});await this.sendConnection.setDescription("local",n);const r=this.createMuteMessage(t);await tg.all(r.map((async e=>{await gS(this,_I.RequestMuteLocal,[e])})))}}async subscribe(e,t,i,n){var r;if(!this.recvConnection||this.state!==pI.Connected)throw new Vg(xg.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if(null!==(r=this.remoteUserMap.get(e))&&void 0!==r&&r.has(t))return;const{track:s,mid:o,sdp:a}=await this.recvConnection.receive(t,i,n);t===dI.AUDIO?(e._audioSSRC=n,e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new Ab(s,e.uid,e._uintid,this.store),WC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=n,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new yb(s,e.uid,e._uintid,this.store),WC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),this.bindRemoteTrackEvents(e,e._videoTrack));const c=this.remoteUserMap.get(e);c?c.set(t,o):this.remoteUserMap.set(e,new Map([[t,o]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadDownlinkStats(),await gS(this,_I.RequestP2PUnmuteRemote,t);const d=this.pendingRemoteTracks.findIndex((i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r}));return-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(_I.MediaReconnectEnd,e.uid)),a}async unsubscribe(e,t,i,n){const r=this.pendingRemoteTracks.filter((t=>{let{user:n,kind:r}=t;return void 0!==i?n.uid===e.uid&&i===r:n.uid===e.uid}));if(r.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.recvConnection&&this.state===pI.Connected||n||r.forEach((t=>{let{kind:i}=t;var n;if(i===dI.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===dI.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.recvConnection||this.state!==pI.Connected)return;const s=this.filterTobeUnSubscribedTracks(e,i);if(0===s.length)return void(i!==dI.VIDEO&&gS(this,_I.RequestP2PMuteRemote,dI.AUDIO));const o=await this.recvConnection.stopReceiving(s.map((e=>{let[,{id:t}]=e;return t})),t);return this.withdrawRemoteTracks(s),0===this.remoteUserMap.size&&this.statsUploader.stopUploadDownlinkStats(),s.forEach((e=>{let[t,{kind:i}]=e;var r,s;if(i===dI.VIDEO&&t._videoSSRC&&(null===(r=this.recvConnection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1)),i===dI.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),n||(null===(s=t._videoTrack)||void 0===s||s._destroy(),t._videoTrack=void 0);else if(i===dI.AUDIO){var o;this.unbindRemoteTrackEvents(t._audioTrack),n||(null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0)}})),s.filter((e=>{let[,{kind:t}]=e;return t!==dI.AUDIO})).forEach((e=>{let[,{kind:t}]=e;gS(this,_I.RequestP2PMuteRemote,t)})),i!==dI.VIDEO&&gS(this,_I.RequestP2PMuteRemote,dI.AUDIO),o}getAllDataChannels(){return this.localDataChannels}async massSubscribe(e){throw new Vg(xg.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(e){throw new Vg(xg.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(e){throw new Vg(xg.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(e){throw new Vg(xg.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")}async muteRemote(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void WC.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void WC.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===dI.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.recvConnection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);i?i.get(t)||WC.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,".")):WC.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."))}getAllTracks(e){const t=this.localTrackMap.get(uI.LocalAudioTrack);if((null==t?void 0:t.track)instanceof ZA){const i=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>{let[t]=e;return t!==uI.LocalAudioTrack})).filter((t=>{let[i]=t;return!(e&&i===uI.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t})).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let[i]=t;return!(e&&i===uI.LocalVideoLowTrack)})).map((e=>{let[,{track:t}]=e;return t}))}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(uI.LocalAudioTrack),s=n?this.localTrackMap.get(uI.LocalVideoLowTrack):this.localTrackMap.get(uI.LocalVideoTrack);iv.publish(this.store.sessionId,{eventElapse:sD.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==s?void 0:s.track.getTrackLabel(),screenshare:-1!==(null==s?void 0:s.track._hints.indexOf(Dy.SCREEN_TRACK)),audio:!!i,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var s;i||(i=[]);const o=i.find((e=>e instanceof zA)),a=n?null===(s=this.localTrackMap.get(uI.LocalVideoTrack))||void 0===s?void 0:s.track:i.find((e=>e instanceof fb));iv.publish(this.store.sessionId,{eventElapse:sD.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==o?void 0:o.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(Dy.SCREEN_TRACK)),audio:!!o,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===dI.VIDEO?i._videoSSRC:i._audioSSRC;r&&iv.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===dI.VIDEO,audio:n===dI.AUDIO,peerid:i.uid,subscribeRequestid:n===dI.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:sD.measureFromSubscribeStart(this.store.clientId,r)})}reset(){WC.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new YS("P2PChannel2-send-mutex"),this.sendMutex=new YS("P2PChannel2-recv-mutex"),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(uI.LocalAudioTrack);if((null==e?void 0:e.track)instanceof ZA){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.state=pI.Disconnected}getStats(e){var t,i;return e?null===(i=this.recvConnection)||void 0===i?void 0:i.getStats():null===(t=this.sendConnection)||void 0===t?void 0:t.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.recvConnection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(uI.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(uI.LocalVideoTrack);if(e)return{width:e.track._videoWidth||0,height:e.track._videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof fb||t&&t.track instanceof zA?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;const i=Array.from(hu(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(uI.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=Zu(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(WC.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=pI.Reconnecting,kC("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let[i,{track:n}]=e;switch(i){case uI.LocalVideoTrack:Lr(t=n._hints).call(t,Dy.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case uI.LocalAudioTrack:n instanceof ZA?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case uI.LocalVideoLowTrack:}})),this.emit(_I.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;Array.from(hu(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(t,e)})),this.emit(_I.MediaReconnectStart,t.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),WC.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof bP?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}async restartICE(e){let t;t=e.direction===Rv.SEND_ONLY?await this.sendMutex.lock("From P2PChannel.restartICE"):await this.recvMutex.lock("From P2PChannel.restartICE");try{const t=await e.restartICE(),i=await fS(this,_I.RequestP2PRestartICE,t);e.setDescription("local",i)}finally{t()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(uI.LocalVideoTrack),i=this.localTrackMap.get(uI.LocalAudioTrack),n=e.videoSend.find((e=>{var i;return e.ssrc===(null==t||null===(i=t.ssrcs)||void 0===i?void 0:i[0].ssrcId)})),r=e.audioSend.find((e=>{var t;return e.ssrc===(null==i||null===(t=i.ssrcs)||void 0===t?void 0:t[0].ssrcId)}));if(!n||!r)return 1;const s=SS(this,_I.NeedSignalRTT),o=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=o&&a?(o+a)/2:o||a,d=(c&&s?(c+s)/2:c||s)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,h=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,u=null==t?void 0:t.track;if(u&&u._encoderConfig&&-1===u._hints.indexOf(Dy.SCREEN_TRACK)){const t=u._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return sv[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][h]}}return h}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((i=>{let[n]=i;const r=n._audioSSRC,s=n._videoSSRC,o=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===s));if(!o&&!a)return void(t+=1);const c=SS(this,_I.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,h=o?o.jitterMs:void 0,u=e.recvPacketLossRate;let p=.7*u*100/50+.3*l/1500;h&&(p=.6*u*100/50+.2*l/1500+.2*h/400),t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new tg(((t,i)=>{this.handleMuteLocalTrack(e,t,i)}))}filterTobePublishedTracks(e,t,i){const n=[],r=hA(),s=this.getAllTracks();e=yS(e=e.filter((e=>-1===s.indexOf(e))));let o=!1,a=!1;for(const s of e){if(s instanceof fb&&(this.localTrackMap.has(uI.LocalVideoTrack)||o?new Vg(xg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:s,type:uI.LocalVideoTrack}),o=!0),t)){const e=this.getLowVideoTrack(s,i);n.push({track:e,type:uI.LocalVideoLowTrack})}if(s instanceof zA){const e=this.localTrackMap.get(uI.LocalAudioTrack);if(e){if(!(e.track instanceof ZA))throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(s._bypassWebAudio)throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(s),this.bindLocalAudioTrackEvents(s,!0)}else if(a){const e=n.find((e=>{let{type:t}=e;return t===uI.LocalAudioTrack}));if(!(e.track instanceof ZA))throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(s._bypassWebAudio)throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(s)}else{if(!r.webAudioMediaStreamDest||s instanceof ZA||s._bypassWebAudio)n.push({track:s,type:uI.LocalAudioTrack});else{const e=new ZA;e.addAudioTrack(s),n.push({track:e,type:uI.LocalAudioTrack})}a=!0}}}return n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=yS(e=e.filter((e=>-1!==i.indexOf(e))));for(const i of e){if(i instanceof zA){const e=this.localTrackMap.get(uI.LocalAudioTrack);if(!e)continue;e.track instanceof ZA?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([uI.LocalAudioTrack,e]),e.track.close())):t.push([uI.LocalAudioTrack,e])}if(i instanceof fb){const e=this.localTrackMap.get(uI.LocalVideoTrack);if(!e)continue;t.push([uI.LocalVideoTrack,e]);const i=this.localTrackMap.get(uI.LocalVideoLowTrack);i&&t.push([uI.LocalVideoLowTrack,i])}}return t}bindLocalTrackEvents(e){e.forEach((e=>{let{track:t,type:i}=e;switch(i){case uI.LocalVideoTrack:t.addListener(Ny.GET_STATS,this.handleGetLocalVideoStats),t.addListener(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(Ny.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(Ny.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(Ny.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case uI.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case uI.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof ZA?e.trackList.forEach((e=>{e.addListener(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Ny.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(Ny.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(Ny.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let[t,{track:i}]=e;return{track:i,type:t}}))),e.forEach((e=>{let{track:t,type:i}=e;switch(i){case uI.LocalVideoTrack:t.off(Ny.GET_STATS,this.handleGetLocalVideoStats),t.off(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(Ny.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(Ny.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(Ny.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case uI.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case uI.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof ZA?e.trackList.forEach((e=>{e.off(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Ny.GET_STATS,this.handleGetLocalAudioStats),e.off(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(Ny.GET_STATS,this.handleGetLocalAudioStats),e.off(Ny.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Ny.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Ny.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(Ny.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Ny.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof yb&&t.addListener(Ny.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof Ab&&t.addListener(Ny.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(Ny.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let[t,i]=e;i.has(dI.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(dI.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)}))}createGatewayPublishMessage(e){return e.map((e=>{var t;let i,n,{track:r,type:s}=e;switch(s){case uI.LocalAudioTrack:i=Qv.Audio,n={dtx:r instanceof XA&&r._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case uI.LocalVideoTrack:i=Lr(t=r._hints).call(t,Dy.SCREEN_TRACK)?Qv.Screen:Qv.High,n=bM(bM({},_D(r)),{},{codec:this.store.codec});break;case uI.LocalVideoLowTrack:i=Qv.Low,n=bM(bM({},_D(r)),{},{codec:this.store.codec})}return{kind:s===uI.LocalAudioTrack?dI.AUDIO:dI.VIDEO,stream_type:i,attributes:n,isMuted:r.muted||!r.enabled}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case uI.LocalVideoTrack:i=Lr(t=r._hints).call(t,Dy.SCREEN_TRACK)?Qv.Screen:Qv.High;break;case uI.LocalAudioTrack:i=Qv.Audio;break;case uI.LocalVideoLowTrack:i=Qv.Low}return{stream_type:i,ssrcs:s,mid:o}}))}assignLocalTracks(e){e.forEach((e=>{let{track:t,type:i}=e;this.localTrackMap.set(i,{track:t})}))}withdrawLocalTracks(e){e.forEach((e=>{let[t]=e;this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var i;if(WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(_I.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),Lr(i=this._restartStates).call(i,t)||e.direction===Rv.SEND_ONLY){if(this._restartTimer)return;const t=()=>{"disconnected"!==e.iceConnectionState&&"checking"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||(WC.debug("[".concat(this.store.clientId,"] [P2PChannel] start use restartICE")),"CONNECTED"===SS(this,_I.QueryClientConnectionState)&&this.restartICE(e))};this._restartTimer=window.setTimeout((()=>{t(),this._restartTimer=void 0}),800)}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),iv.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:oS.TRACER}).onSuccess(),this.emit(_I.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(hu(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var n;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(xy.FIRST_FRAME_DECODED),iv.firstRemoteFrame(this.store.sessionId,JC.FIRST_AUDIO_DECODE,zC.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:sD.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(hu(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));i&&iv.firstRemoteFrame(this.store.sessionId,JC.FIRST_AUDIO_RECEIVED,zC.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:sD.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;const i=Array.from(hu(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));i&&iv.firstRemoteFrame(this.store.sessionId,JC.FIRST_VIDEO_RECEIVED,zC.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:sD.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(_I.ConnectionTypeChange,i),WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(TD(t))," -> ").concat(JSON.stringify(TD(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{WC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(TD(t))," -> ").concat(JSON.stringify(TD(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=e=>{this.emit(_I.LocalCandidate,e)}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(uI.LocalAudioTrack);if(e instanceof zA&&(null==i?void 0:i.track)instanceof ZA)return i.track.isActive||t.push([uI.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n&&(t.push(n),n[0]===uI.LocalVideoTrack)){const e=this.localTrackMap.get(uI.LocalVideoLowTrack);e&&t.push([uI.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(uI.LocalAudioTrack);if(e instanceof zA&&(null==i?void 0:i.track)instanceof ZA)return i.track.isActive&&t.push([uI.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find((t=>{let[,{track:i}]=t;return e===i}));if(n)if(n[0]===uI.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(uI.LocalVideoLowTrack);e&&t.push([uI.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case uI.LocalAudioTrack:i=Qv.Audio;break;case uI.LocalVideoTrack:i=Lr(t=r._hints).call(t,Dy.SCREEN_TRACK)?Qv.Screen:Qv.High;break;case uI.LocalVideoLowTrack:i=Qv.Low}return{stream_type:i,ssrcs:s,mid:o}}))}createUnmuteMessage(e){return e.map((e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case uI.LocalAudioTrack:i=Qv.Audio;break;case uI.LocalVideoTrack:i=Lr(t=r._hints).call(t,Dy.SCREEN_TRACK)?Qv.Screen:Qv.High;break;case uI.LocalVideoLowTrack:i=Qv.Low}return{stream_type:i,ssrcs:s,mid:o}}))}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach((t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])}));return i}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let[i,{kind:n,id:r}]=e;switch(n){case dI.VIDEO:return void(i._videoSSRC&&t.push({stream_type:dI.VIDEO,ssrcId:i._videoSSRC}));case dI.AUDIO:return void(i._audioSSRC&&t.push({stream_type:dI.AUDIO,ssrcId:i._audioSSRC}))}})),t}withdrawRemoteTracks(e){e.forEach((e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(uI.LocalVideoTrack),i=this.localTrackMap.get(uI.LocalVideoLowTrack);t&&await t.track.setBitrateLimit(e.uplink),i&&e.low_stream_uplink&&await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0})}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return"connected"!==e&&"connected"!==t}return!0}async tryToUnmuteAudio(e){for(let t=0;t<e.length;t++)if(e[t]instanceof zA){const i=this.filterTobeUnmutedTracks(e[t]);if(0===i.length)continue;const n=this.createUnmuteMessage(i);return void await gS(this,_I.RequestUnmuteLocal,n)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=e=>this.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter((e=>{let[,{ssrcs:t}]=e;return!!t})),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.recvConnection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(_I.RequestUploadStats,e,t),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await US(zS(this.dtlsFailedCount,JS)),this.emit(_I.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(uI.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof fb))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof fb)).length>1)throw new Vg(xg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof zA)).length>1&&(e.some((e=>e instanceof zA&&e._bypassWebAudio))||!hA().webAudioMediaStreamDest))throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof fb&&this.pendingLocalTracks.some((e=>e instanceof fb)))throw new Vg(xg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof zA&&this.pendingLocalTracks.some((e=>e instanceof zA))&&(!hA().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof zA&&e._bypassWebAudio))))throw new Vg(xg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const i=!kC("DISABLE_DUAL_STREAM_USE_ENCODING")&&hA().supportDualStreamEncoding,n=bM(bM({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():jL(e,n);const s=xS(8,"track-low-"),o=new fb(r,bM(bM({},i&&{scaleResolutionDownBy:SD(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,s);return o.on(My.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,Py.LOW_STREAM)})),o._hints.push(Dy.LOW_STREAM),e.addListener(Ny.NEED_CLOSE,(()=>{o.close()})),o}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock")}reportVideoFirstFrameDecoded(e,t,i,n){var r;const s=Array.from(hu(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(s){n||this.store.subscribe(s.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,o=r.subscribe.find((e=>e.userId===s.uid&&"video"===e.type));iv.firstRemoteVideoDecode(this.store.sessionId,JC.FIRST_VIDEO_DECODE,zC.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:sD.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==o?void 0:o.subscribeEnd)||0,subscriberStart:(null==o?void 0:o.subscribeStart)||0,videoAddNotify:(null==o?void 0:o.streamAdded)||0,state:n?1:0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.recvConnection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const s=await this.recvConnection.getRemoteSSRC(r);return void 0!==s&&s!==i}resetConnection(e){WC.debug("[".concat(this.store.clientId,"] [P2PChannel2] reset connection to ").concat(e)),this.state===pI.Connected?(WC.debug("[".concat(this.store.clientId,"] [P2PChannel2] fallback to websocket but P2PChannel2 state still connected, disconnect first")),this.disconnectForReconnect()):(this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0))}async publishDataChannel(e){throw new Vg(xg.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new Vg(xg.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new Vg(xg.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new Vg(xg.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new Vg(xg.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new Vg(xg.NOT_SUPPORTED)}async preConnect(e,t,i,n,r,s){throw new Vg(xg.NOT_SUPPORTED)}getEstablishParams(){throw new Vg(xg.NOT_SUPPORTED)}async reSubscribe(e){throw new Vg(xg.NOT_SUPPORTED)}async updateVideoStreamParameter(e,t){throw new Vg(xg.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let[t,{track:i}]=e;t===uI.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,Py.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}}function OM(e){return function(t,i,n){const r=t[i];if("function"!=typeof r)throw new Error("Cannot use mutex on object property.");return n.value=async function(){for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];switch(e){case yM.SEND_ONLY:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(i));try{return await r.apply(this,n)}finally{e()}}case yM.RECEIVE_ONLY:{const e=await this.recvMutex.lock("From P2PChannel2.".concat(i));try{return await r.apply(this,n)}finally{e()}}default:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(i)),t=await this.recvMutex.lock("From P2PChannel2.".concat(i));try{return await r.apply(this,n)}finally{e(),t()}}}},n}}function NM(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function DM(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?NM(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):NM(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}Lv([OM(),kv("design:type",Function),kv("design:paramtypes",[Object,String]),kv("design:returntype",tg)],wM.prototype,"startP2P",null),Lv([OM(),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],wM.prototype,"p2pConnect",null),Lv([OM(yM.SEND_ONLY),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],wM.prototype,"dopublish",null),Lv([OM(yM.SEND_ONLY),kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],wM.prototype,"unpublish",null),Lv([OM(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],wM.prototype,"unpublishLowStream",null),Lv([OM(yM.SEND_ONLY),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],wM.prototype,"doUnpublish",null),Lv([OM(yM.RECEIVE_ONLY),kv("design:type",Function),kv("design:paramtypes",[bP,String,String,Number]),kv("design:returntype",tg)],wM.prototype,"subscribe",null),Lv([OM(yM.RECEIVE_ONLY),kv("design:type",Function),kv("design:paramtypes",[bP,String,String,Boolean]),kv("design:returntype",tg)],wM.prototype,"unsubscribe",null),Lv([OM(yM.RECEIVE_ONLY),kv("design:type",Function),kv("design:paramtypes",[bP,String]),kv("design:returntype",tg)],wM.prototype,"muteRemote",null),Lv([OM(yM.RECEIVE_ONLY),kv("design:type",Function),kv("design:paramtypes",[bP,String]),kv("design:returntype",tg)],wM.prototype,"unmuteRemote",null),Lv([OM(yM.RECEIVE_ONLY),kv("design:type",Function),kv("design:paramtypes",[bP,String]),kv("design:returntype",tg)],wM.prototype,"hasRemoteMediaWithLock",null),Lv([OM(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],wM.prototype,"disconnectForReconnect",null),Lv([OM(yM.RECEIVE_ONLY),kv("design:type",Function),kv("design:paramtypes",[bP,String,Number]),kv("design:returntype",tg)],wM.prototype,"remoteMediaSsrcChanged",null);const PM=Date.now(),LM=20,kM=new Map,MM=new Map;async function UM(e){const t=kM.get(e),i=Array.isArray(t)&&t[t.length-1],n=MM.get(e);if(!i)return void(n.isSyncing=!1);const r={uid:i.uid,payload:DS(i.payload)};0===n.firstRecvTs&&(n.firstRecvTs=i.recvTs,n.firstSendTs=i.sendTs);const s=i.sendTs-n.firstSendTs,o=s-(Date.now()-n.firstRecvTs);o>0&&(n.firstRecvTs=Date.now()-s);let a=i.mediaDelay+o;a<=0?(t.pop(),xM(i.context,r),a=0):a=Math.min(a,LM),setTimeout((()=>t.length&&UM(e)),a)}function xM(e,t){e.safeEmit(dS.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function VM(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return xM(i,{uid:e.uid,payload:DS(e.payload)});const n="".concat(i.id,"-").concat(e.uid),r=kM.get(n)||[],s=r.findIndex((t=>e.sendTs>=t.sendTs)),o=DM(DM({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===s?r.push(o):r.splice(s,0,o),kM.set(n,r);let a=!1;var c;MM.has(n)?a=!(null===(c=MM.get(n))||void 0===c||!c.isSyncing):MM.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0}),a||UM(n)}function FM(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function BM(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?FM(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):FM(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}YS.setLogger(WC);class jM extends iS{get connectionState(){return this._gateway.state}get remoteUsers(){return this._users}get localTracks(){return this._p2pChannel.getAllTracks(!0)}get uid(){return this._uid}get channelName(){return this._channelName}get localDataChannels(){return this._p2pChannel.getAllDataChannels()}get mode(){return this._config.mode}get role(){var e;return(null===(e=this._config)||void 0===e?void 0:e.role)||"audience"}get codec(){return this._config.codec}get audioCodec(){return this._config.audioCodec||"opus"}get isStringUID(){return!!this._joinInfo&&!!this._joinInfo.stringUid}get __className__(){return"Client"}constructor(e){let t;if(super(),nu(this,"store",void 0),nu(this,"_uid",void 0),nu(this,"_channelName",void 0),nu(this,"_uintUid",void 0),nu(this,"_users",[]),nu(this,"_config",void 0),nu(this,"_clientId",void 0),nu(this,"_appId",void 0),nu(this,"_sessionId",null),nu(this,"_key",void 0),nu(this,"_joinInfo",void 0),nu(this,"_gateway",void 0),nu(this,"_statsCollector",void 0),nu(this,"_configDistribute",void 0),nu(this,"_leaveMutex",new YS("client-leave")),nu(this,"_publishMutex",new YS("client-publish")),nu(this,"_renewTokenMutex",new YS("client-renewtoken")),nu(this,"_subscribeMutex",new YS("client-subscribe")),nu(this,"_encryptionMode","none"),nu(this,"_encryptionSecret",null),nu(this,"_encryptionSalt",null),nu(this,"_proxyServer",void 0),nu(this,"_turnServer",{servers:[],mode:"auto"}),nu(this,"_cloudProxyServerMode","disabled"),nu(this,"_isDualStreamEnabled",!1),nu(this,"_defaultStreamFallbackType",void 0),nu(this,"_lowStreamParameter",void 0),nu(this,"_streamFallbackTypeCacheMap",new Map),nu(this,"_remoteStreamTypeCacheMap",new Map),nu(this,"_axiosCancelSource",EC.CancelToken.source()),nu(this,"_audioVolumeIndicationInterval",void 0),nu(this,"_networkQualityInterval",void 0),nu(this,"_userOfflineTimeout",void 0),nu(this,"_streamRemovedTimeout",void 0),nu(this,"_injectStreamingClient",void 0),nu(this,"_liveTranscodeStreamingClient",void 0),nu(this,"_liveRawStreamingClient",void 0),nu(this,"_channelMediaRelayClient",void 0),nu(this,"_networkQualitySensitivity","normal"),nu(this,"_p2pChannel",void 0),nu(this,"_useLocalAccessPoint",!1),nu(this,"_setLocalAPVersion",void 0),nu(this,"_joinAndNotLeaveYet",!1),nu(this,"_numberOfJoinCount",0),nu(this,"_remoteDefaultVideoStreamType",void 0),nu(this,"_inspect",void 0),nu(this,"_moderation",void 0),nu(this,"_license",void 0),nu(this,"_pendingPublishedUsers",[]),nu(this,"ntpAlignErrorCount",0),nu(this,"remoteInboundOffset",0),nu(this,"_handleLocalTrackEnable",((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),nu(this,"_handleLocalTrackDisable",((e,t,i)=>{this.unpublish(e).then(t).catch(i)})),nu(this,"_handleUserOnline",(e=>{if(kC("BLOCK_LOCAL_CLIENT")&&av(e.uid,this.channelName))return void WC.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&WC.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const t=this._users.find((t=>t.uid===e.uid));if(t)t._trust_in_room_=!0;else{const t=new bP(e.uid,e.uint_id||e.uid);this._users.push(t),WC.debug("[".concat(this._clientId,"] user online"),e.uid),this.safeEmit(dS.USER_JOINED,t)}})),nu(this,"_handleUserOffline",(e=>{if(kC("BLOCK_LOCAL_CLIENT")&&av(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));t&&(this._handleRemoveStream(e),this._handleRemoveDataChannels(e),IS(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),WC.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(dS.USER_LEAVED,t,e.reason))})),nu(this,"_handleAddAudioOrVideoStream",((e,t,i,n,r,s,o)=>{if(kC("BLOCK_LOCAL_CLIENT")&&av(t,this.channelName))return;const a=this._users.find((e=>e.uid===t));if(!a)return void WC.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));WC.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(a.uid,e,void 0,void 0,void 0,Date.now());const c="audio"===e?a.hasAudio:a.hasVideo;a._uintid||(a._uintid=r||t),"audio"===e?a._trust_audio_stream_added_state_=!0:a._trust_video_stream_added_state_=!0,"audio"===e?(a._audio_added_=!0,void 0!==i&&(a._audioSSRC=i),void 0!==n&&(a._cname=n),s&&(a._audioOrtc=s)):(a._video_added_=!0,void 0!==i&&(a._videoSSRC=i),void 0!==n&&(a._cname=n),void 0!==o&&(a._rtxSsrcId=o),s&&(a._videoOrtc=s)),("audio"===e?a.hasAudio:a.hasVideo)&&!c&&(WC.info("[".concat(this._clientId,"] remote user ").concat(a.uid," published ").concat(e)),this.safeEmit(dS.USER_PUBLISHED,a,e)),"video"===e?iv.onGatewayStream(this._sessionId,JC.ON_ADD_VIDEO_STREAM,zC.ON_ADD_VIDEO_STREAM,{peer:r||t,ssrc:a._videoSSRC}):iv.onGatewayStream(this._sessionId,JC.ON_ADD_AUDIO_STREAM,zC.ON_ADD_AUDIO_STREAM,{peer:r||t,ssrc:a._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(a,e,i).then((t=>{if(t&&(WC.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof lk))return this._p2pChannel.unsubscribe(a,e,!0).then((()=>this._subscribe(a,e,!0).catch((e=>{WC.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(a,e)&&(WC.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after reconnect.")),this._subscribe(a,e,!0).catch((e=>{WC.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),nu(this,"_handleRemoveStream",((e,t,i)=>{if(kC("BLOCK_LOCAL_CLIENT")&&av(e.uid,this.channelName))return;const n=this._users.find((t=>t.uid===e.uid));if(!n)return void WC.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));WC.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let r=()=>{};if(n.hasAudio&&n.hasVideo?r=()=>{WC.info("[".concat(this._clientId,"] remote user ").concat(n.uid," unpublished audio track")),this.safeEmit(dS.USER_UNPUBLISHED,n,"audio"),WC.info("[".concat(this._clientId,"] remote user ").concat(n.uid," unpublished video track")),this.safeEmit(dS.USER_UNPUBLISHED,n,"video")}:n.hasVideo?r=()=>{WC.info("[".concat(this._clientId,"] remote user ").concat(n.uid," unpublished video track")),this.safeEmit(dS.USER_UNPUBLISHED,n,"video")}:n.hasAudio&&(r=()=>{WC.info("[".concat(this._clientId,"] remote user ").concat(n.uid," unpublished audio track")),this.safeEmit(dS.USER_UNPUBLISHED,n,"audio")}),n._trust_audio_stream_added_state_=!0,n._trust_video_stream_added_state_=!0,n._audio_added_=!1,n._video_added_=!1,this._p2pChannel instanceof lk)this._p2pChannel.unsubscribe(n).then((e=>{if(e)return this._gateway.unsubscribe(e,n.uid)}));else if(t&&i)if(e.sdp){const{sdp:r}=e;this._p2pChannel.unsubscribe(n,r).then((e=>{e&&t(e)})).catch(i)}else t&&t();n._audioSSRC=void 0,n._videoSSRC=void 0,n._audioOrtc=void 0,n._videoOrtc=void 0,n._rtxSsrcId=void 0,iv.onGatewayStream(this._sessionId,JC.ON_REMOVE_STREAM,zC.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),r()})),nu(this,"_handleSetStreamLocalEnable",((e,t,i)=>{if(kC("BLOCK_LOCAL_CLIENT")&&av(t,this.channelName))return;const n=this._users.find((e=>e.uid===t));if(!n)return void WC.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));WC.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(i?"enabled":"disabled"," with uid ").concat(t));const r="audio"===e?n.hasAudio:n.hasVideo;if("audio"===e){n._trust_audio_enabled_state_=!0;const e=n._audio_enabled_;if(n._audio_enabled_=i,n._audio_enabled_===e)return;{const e=n._audio_enabled_?"enable-local-audio":"disable-local-audio";WC.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(dS.USER_INFO_UPDATED,t,e)}}else{n._trust_video_enabled_state_=!0;const e=n._video_enabled_;if(n._video_enabled_=i,n._video_enabled_===e)return;{const e=n._video_enabled_?"enable-local-video":"disable-local-video";WC.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(dS.USER_INFO_UPDATED,t,e)}}const s="audio"===e?n.hasAudio:n.hasVideo;return r!==s?!r&&s?(WC.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(dS.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),WC.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(dS.USER_UNPUBLISHED,n,e)):void 0})),nu(this,"_handleMuteStream",((e,t,i,n,r,s)=>{if(kC("BLOCK_LOCAL_CLIENT")&&av(e,this.channelName))return;WC.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const o=this._users.find((t=>t.uid===e));if(!o)return void WC.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const a="audio"===t?o.hasAudio:o.hasVideo;if("audio"===t){o._trust_audio_mute_state_=!0;const t=o._audio_muted_;if(o._audio_muted_=i,o._audio_muted_===t)return;{const t=o._audio_muted_?"mute-audio":"unmute-audio";WC.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(dS.USER_INFO_UPDATED,e,t)}}else{o._trust_video_mute_state_=!0;const t=o._video_muted_;if(o._video_muted_=i,o._video_muted_===t)return;{const t=o._video_muted_?"mute-video":"unmute-video";WC.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(dS.USER_INFO_UPDATED,e,t)}}const c="audio"===t?o.hasAudio:o.hasVideo;if(a!==c){if(!a&&c)return this.store.useP2P||("audio"===t?o._audioSSRC:o._videoSSRC)?(WC.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(dS.USER_PUBLISHED,o,t)):void WC.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").concat(t," unmute message before add stream message, ").concat(t," SSRC doesn't exist yet."));"video"===t&&o._videoTrack&&o._videoTrack._destroy(),"audio"===t&&o._audioTrack,r&&s&&this._p2pChannel instanceof wM&&(n?this._p2pChannel.unsubscribe(o,n,t).then((e=>{r(e)})).catch(s):r()),this._p2pChannel.muteRemote(o,t),WC.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(dS.USER_UNPUBLISHED,o,t)}})),nu(this,"_handleP2PLost",(async e=>{WC.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():WC.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)})),nu(this,"_handleTokenWillExpire",(()=>{WC.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(dS.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)})),nu(this,"_handleBeforeUnload",(e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),WC.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))})),nu(this,"_handleUpdateNetworkQuality",(()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(dS.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(dS.NETWORK_QUALITY,e)})),nu(this,"_handleP2PAddAudioOrVideoStream",((e,t)=>{const i=this._users.find((e=>e.uid===t));if(!i)return void WC.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));WC.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(i.uid,e,void 0,void 0,void 0,Date.now());const n="audio"===e?i.hasAudio:i.hasVideo;"audio"===e?i._trust_audio_stream_added_state_=!0:i._trust_video_stream_added_state_=!0,"audio"===e?i._audio_added_=!0:i._video_added_=!0,("audio"===e?i.hasAudio:i.hasVideo)&&!n&&(WC.info("[".concat(this._clientId,"] remote user ").concat(i.uid," published ").concat(e)),this.safeEmit(dS.USER_PUBLISHED,i,e)),this._p2pChannel.hasPendingRemoteMedia(i,e)&&(WC.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(i.uid," after reconnect.")),this._subscribe(i,e,!0).catch((e=>{WC.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),this._config=e,this._clientId=xS(5,"client-"),this.store=new wC(e.codec,e.audioCodec,e.mode,this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),WC.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(OC," build: ").concat(DC,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{mS(e.clientRoleOptions),t=Object.assign({},e.clientRoleOptions)}catch(e){WC.warning("[".concat(this._clientId,"] ").concat(e.toString()))}this._statsCollector=new cD(this.store),this._statsCollector.onStatsException=(e,t,i)=>{WC.debug("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),this.safeEmit(dS.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const r=this._users.find((t=>t.uid===e));r&&iv.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:r._uintid})},this.store.useDataChannel=hA().supportDataChannel&&kC("SIGNAL_CHANNEL"),this.store.useP2P=kC("P2P"),this._gateway=new PD(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||JS,httpRetryConfig:e.httpRetryConfig||JS,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:t}),this._configDistribute=new mP,this.store.useP2P?(this._p2pChannel=new wM(this.store,this._statsCollector),this._handleP2PEvents()):this._p2pChannel=new lk(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(e,t,i,n,r){let s=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],o=arguments.length>6&&void 0!==arguments[6]&&arguments[6];LC("JOIN_GATEWAY_USE_443PORT_ONLY",s),LC("JOIN_GATEWAY_USE_DUAL_DOMAIN",o);const a=this._gateway.signal.websocket;return a instanceof qI&&(a.use443PortOnly=s,a.tryDoubleDomain=o),async function(e,t,i){rg.get(e)||rg.set(e,[]),sg.get(e)||sg.set(e,t),og.get(e)||og.set(e,0);const n=rg.get(e),r=sg.get(e);if(!n||!r)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(og.get(e)===r){const e=ng();n.push(e),await e.promise}og.set(e,og.get(e)+1);for(var s=arguments.length,o=new Array(s>3?s-3:0),a=3;a<s;a++)o[a-3]=arguments[a];const c=await i(...o);return og.set(e,og.get(e)-1),og.get(e)===r-1&&n.length>0&&(n[0].resolve(),n.shift()),0===og.get(e)&&(rg.set(e,[]),sg.set(e,0),og.set(e,0)),c}("client.join",kC("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,i,n,r)}async join(e,t,i,n,r){const s=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const o=vC(),a=IC()?window.isSecureContext:"Browser Not Support";if(!IC()&&!o||!window.isSecureContext){const e="The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser";WC.warning(e)}const c=VS();"DISCONNECTED"===this.connectionState&&(this.store.avoidJoinStart=Math.round(Date.now()),WC.debug("[".concat(this._clientId,"] set avoidJoinStart to ").concat(this.store.avoidJoinStart)));const d=iv.reportApiInvoke(c,{name:sS.JOIN,options:[e,t,i,n],states:{isHttps:o,isSecureContext:a},tag:oS.TRACER});iv.setAppId(e);try{if(!i&&null!==i)throw new Mv(xg.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&Wg(i,"token",1,2047),Wg(e,"appid",1,2047),Uv(t),n&&xv(n),r&&Wg(r,"optionalInfo",1,2047)}catch(e){throw d.onError(e),e}if(WC.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(s)),this._leaveMutex.isLocked&&(WC.debug("[".concat(this._clientId,"] join: waiting leave operation")),(await this._leaveMutex.lock())(),WC.debug("[".concat(this._clientId,"] join: continue"))),this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const e=new Mv(xg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw d.onError(e),e}this._sessionId||(this._sessionId=c,this.store.sessionId=this._sessionId),this._gateway.state="CONNECTING";const l=BM({clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof n?n:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:r,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType});if(this._useLocalAccessPoint&&(l.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof n&&(l.stringUid=n,this._uintUid?(l.uid=this._uintUid,this._uintUid=void 0):l.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(l.aesmode=this._encryptionMode,l.aespassword=await eS(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new Mv(xg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(l.aessalt=this._encryptionSalt)}this._startSession(this._sessionId,{channel:t,appId:e});const h=this._sessionId;setTimeout((()=>{"CONNECTING"===this.connectionState&&h===this._sessionId&&iv.joinChannelTimeout(this._sessionId,5)}),5e3);try{var u;let n;const r=l.cloudProxyServer;if(Lr(u=["proxy3","proxy4","proxy5"]).call(u,r)){const e=kC("PROXY_SERVER_TYPE3");Array.isArray(e)?l.proxyServer=e[0]:l.proxyServer=e}if(iv.setProxyServer(l.proxyServer),WC.setProxyServer(l.proxyServer),this.store.requestAPStart(),l.stringUid&&!l.uid){const e=await cP(l.stringUid,l,this._axiosCancelSource.token,this._config.httpRetryConfig||JS,this.store);WC.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(l.stringUid," => ").concat(e)),l.uid=e,n=await aP(l,this._axiosCancelSource.token,this._config.httpRetryConfig||JS,!0,this.store)}else n=await aP(l,this._axiosCancelSource.token,this._config.httpRetryConfig||JS,!0,this.store);if(!this._joinAndNotLeaveYet)throw new Mv(xg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(l,this._axiosCancelSource.token),this._configDistribute.on(aI.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)}))}),0),this._key=i||e;const s=n.gatewayInfo;this._joinInfo=BM(BM({},l),{},{cid:s.cid,uid:l.uid?l.uid:s.uid,vid:s.vid,apResponse:s.res,uni_lbs_ip:s.uni_lbs_ip,gatewayAddrs:s.gatewayAddrs});const o=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new Mv(xg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));d.onSuccess(o),this._appId=e,this._channelName=l.cname,this._uid=o,this.store.uid=o,setTimeout((()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(Tg()?"beforeunload":"pagehide",this._handleBeforeUnload)}),0);const a=l.stringUid?"string uid: ".concat(l.stringUid,",uid: ").concat(l.uid):"uid: ".concat(this._uid);return WC.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(a)),setTimeout((()=>{WC.startUpload()}),5e3),this.store.joinEnd(),p=this,Lr(ov).call(ov,p)||ov.push(p),o}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===xg.OPERATION_ABORTED?WC.warning("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),t):WC.error("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),t),t.code!==xg.OPERATION_ABORTED&&this._numberOfJoinCount===s&&(this._gateway.state="DISCONNECTED",this._reset()),d.onError(t),t}var p}_joinGateway(){if(!this._joinInfo||!this._key)throw new Mv(xg.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!kC("JOIN_WITH_FALLBACK_SIGNAL_PROXY"))).then((e=>e)).catch((e=>{if(e.code===xg.INIT_WEBSOCKET_TIMEOUT)return this._gateway.leave(!0,cS.FALLBACK),e;if(e.code===xg.INIT_DATACHANNEL_TIMEOUT)return this._gateway.leave(!0,cS.FALLBACK),e;throw e})).then((e=>{if(e instanceof Mv){if(e.code===xg.INIT_WEBSOCKET_TIMEOUT){if(WC.info("[".concat(this._clientId,"] join timeout, fallback to proxy")),!this._joinInfo||!this._key)throw new Mv(xg.INVALID_OPERATION);this._joinInfo.cloudProxyServer="fallback",this._cloudProxyServerMode="fallback",this.store.cloudProxyServerMode="fallback";const e=kC("PROXY_SERVER_TYPE3");if(Array.isArray(e))if(this._joinInfo.apUrl){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(this._joinInfo.apUrl)[1].split("."),i=t.slice(t.length-2).join(".");e.forEach((e=>{this._joinInfo&&Lr(e).call(e,i)&&(this._joinInfo.proxyServer=e)})),this._joinInfo.proxyServer||(this._joinInfo.proxyServer=e[0])}else this._joinInfo.proxyServer=e[0];else this._joinInfo.proxyServer=e;const t=kC("LOG_UPLOAD_SERVER").match(/.+:(\d{1,5})$/);return t&&t[1]&&"443"!==t[1]&&WC.setProxyServer(this._joinInfo.proxyServer),"443"!==kC("STATS_COLLECTOR_PORT").toString()&&iv.setProxyServer(this._joinInfo.proxyServer),iv.reportApiInvoke(this._sessionId,{name:sS.JOIN_FALLBACK_TO_PROXY,options:[this._joinInfo.proxyServer],tag:oS.TRACER}).onSuccess(),this.safeEmit(dS.JOIN_FALLBACK_TO_PROXY,this._joinInfo.proxyServer),kC("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&this._joinInfo.turnServer.servers.forEach((e=>{"forceturn"in e&&(e.forceturn=!0)})),this._gateway.join(this._joinInfo,this._key)}if(WC.info("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new Mv(xg.INVALID_OPERATION);return iv.reportApiInvoke(this._sessionId,{name:sS.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:oS.TRACER}).onSuccess(),this._joinGateway()}return e})).then((e=>e))}async leave(){WC.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(Tg()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=ov.indexOf(e);-1!==t&&ov.splice(t,1)}(this);const e=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return WC.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void e();await this._gateway.leave("CONNECTED"!==this.connectionState),WC.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),e()}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof $y))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new Mv(xg.INVALID_PARAMS,"param list is empty");const i=e;if("audience"===this._gateway.role)throw new Mv(xg.INVALID_OPERATION,"audience can not publish stream");for(const e of i){if(!(e instanceof $y))throw new Mv(xg.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new Mv(xg.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}WC.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))));const n=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&i.forEach((e=>{const t=this._configDistribute.getBitrateLimit();e instanceof fb&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(i),WC.info("[".concat(this._clientId,"] Publish success, id ").concat(i.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw WC.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{n()}}async _publishDataChannel(e){jg(e.id,"id",0,65535,!0),Fg(e.ordered,"ordered"),Wg(e.metadata,"metadata",0,512),WC.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(e.id));const t=await this._publishMutex.lock();try{if(-1!==this._p2pChannel.getAllDataChannels().findIndex((t=>t.id===e.id)))throw new Mv(xg.INVALID_PARAMS,"Invalid id: ".concat(e.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||void 0===this._uid)throw new Mv(xg.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&kC("FORCE_TURN")&&!kC("TURN_ENABLE_TCP")&&!kC("TURN_ENABLE_UDP"))throw new Mv(xg.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const t=new iD(e);await this._p2pChannel.publishDataChannel([t]);try{const i={streamId:e.id,ordered:e.ordered,maxRetransmits:kC("DATASTREAM_MAX_RETRANSMITS"),metadata:e.metadata,channelId:t._originDataChannelId};await this._gateway.publishDataChannel(this._uid,i,!0)}catch(e){if(e.code!==xg.DISCONNECT_P2P)throw e}return await t._waitTillOpen(),WC.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(t.id)),t}catch(e){throw WC.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new Mv(xg.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof $y))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);WC.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map((e=>"".concat(e.getTrackId()," ")))," "));const i=await this._publishMutex.lock();try{if(this._p2pChannel instanceof wM){const e=await this._p2pChannel.unpublish(t);if(e){const t=await this._gateway.sendExtensionMessage(AI.UNPUBLISH,e);t&&await this._p2pChannel.setDescription("local",t)}}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),WC.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw WC.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e}finally{i&&i()}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),WC.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map((e=>"".concat(e.id," ")))," "));const t=await this._publishMutex.lock();try{const t=await this._p2pChannel.unpublishDataChannel(e);t&&await this._gateway.unpublishDataChannel(t),WC.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw WC.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,i){return"datachannel"===t?this._subscribeDataChannel(e,i):this._subscribe(e,t)}async _subscribeDataChannel(e,t){var i;if(jg(t,"channelId",0,65535,!0),!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e)))throw WC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new Mv(xg.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw WC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new Mv(xg.INVALID_REMOTE_USER,"user is not published");const n=null===(i=e._dataChannels)||void 0===i?void 0:i.find((e=>e.id===t));if(!n)throw WC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new Mv(xg.REMOTE_USER_IS_NOT_PUBLISHED);const r=await this._subscribeMutex.lock();WC.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const i=await this._p2pChannel.subscribeDataChannel(e,[n]);if(i&&Lr(i).call(i,n.id))try{var s;if(!n._originDataChannelId)throw WC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new Mv(xg.REMOTE_USER_IS_NOT_PUBLISHED);const t={id:n.id,datachannelId:n._originDataChannelId,ordered:n.ordered,maxRetransmits:n.maxRetransmits,metadata:null!==(s=n.metadata)&&void 0!==s?s:""};await this._gateway.subscribeDataChannel(e.uid,t,!0)}catch(t){if((null==t?void 0:t.code)!==xg.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[n]),t;await this._p2pChannel.unsubscribeDataChannel(e,[n]),this._p2pChannel.setPendingRemoteDataChannel(e,n.id)}return await n._waitTillOpen(),WC.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),n}finally{r()}}async _p2pSubscribe(e,t,i){if(Bg(t,"mediaType",["audio","video"]),!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e))){const t=new Mv(xg.INVALID_REMOTE_USER,"user is not in the channel");throw WC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new Mv(xg.INVALID_REMOTE_USER,"user is not published");throw WC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!i&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){const i=new Mv(xg.REMOTE_USER_IS_NOT_PUBLISHED);throw WC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}const n=await this._subscribeMutex.lock();WC.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));const r="audio"===t?uI.LocalAudioTrack:this._joinInfo.defaultVideoStream===Ly.LOW_STREAM?uI.LocalVideoLowTrack:uI.LocalVideoTrack;try{await this._p2pChannel.hasRemoteMediaWithLock(e,t)?await this._p2pChannel.unmuteRemote(e,t):(this.store.subscribe(e.uid,t,Date.now()),this._p2pChannel instanceof wM&&await this._gateway.sendExtensionMessage(AI.SUBSCRIBE,{trackType:r})),WC.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{WC.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new Mv(xg.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw WC.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{n()}}async _subscribe(e,t,i){if(this._p2pChannel instanceof wM)return this._p2pSubscribe(e,t);if(Bg(t,"mediaType",["audio","video"]),!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find((t=>t===e))){const t=new Mv(xg.INVALID_REMOTE_USER,"user is not in the channel");throw WC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new Mv(xg.INVALID_REMOTE_USER,"user is not published");throw WC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!(i||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const i=new Mv(xg.REMOTE_USER_IS_NOT_PUBLISHED);throw WC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}let n="audio"===t?e._audioSSRC:e._videoSSRC,r="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,o={stream_type:"audio"===t?dI.AUDIO:dI.VIDEO,ssrcId:n};const a=await this._subscribeMutex.lock();WC.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const a="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==a&&a!==n&&(n=a,r="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,o={stream_type:"audio"===t?dI.AUDIO:dI.VIDEO,ssrcId:n}),sD.markSubscribeStart(this.store.clientId,n),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,n,s,r);try{await this._gateway.subscribe(e.uid,o,!0)}catch(i){if((null==i?void 0:i.code)!==xg.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),i;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t)}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t)}catch(i){throw this._p2pChannel.reportSubscribeEvent(!1,null==i?void 0:i.code,e,t),i}WC.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{WC.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const a="audio"===t?e._audioTrack:e._videoTrack;if(!a)throw new Mv(xg.UNEXPECTED_ERROR,"can not find remote track in user object");return a}catch(t){throw WC.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{a()}}async massSubscribe(e){if(Hg(e,"subscribeList"),!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();WC.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; ")));const r=(e=[...e]).map((e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i}})),s=await this._p2pChannel.globalLock();try{var o;for(let t=e.length-1;t>=0;t--){const n=e[t],{user:s,mediaType:o}=n;if(Bg(o,"mediaType",["audio","video"]),!s){const e=new Mv(xg.INVALID_PARAMS,"user property does not exist in subscribeList item");throw WC.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}if(!this._users.find((e=>e===s))){const i=new Mv(xg.INVALID_REMOTE_USER,"user is not in the channel");WC.error("[".concat(this._clientId,"] can not massSubscribe ").concat(s.uid,", this user is not in the channel")),r[t].error=i,e.splice(t,1);continue}if("audio"===o&&(!s.hasAudio||void 0===s._audioSSRC)||"video"===o&&(!s.hasVideo||void 0===s._videoSSRC)){const i=new Mv(xg.REMOTE_USER_IS_NOT_PUBLISHED);WC.error("[".concat(this._clientId,"] can not subscribe ").concat(s.uid," with mediaType ").concat(o,", remote user is not published")),r[t].error=i,e.splice(t,1);continue}const a=eI.Video|eI.LwoVideo,c=i.get(s);if(c){if("video"===o?c&a:c&eI.Audio){e.splice(t,1),WC.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(s.uid,", mediaType:").concat(o," twice"));continue}i.set(s,c|("video"===o?a:eI.Audio))}else i.set(s,"video"===o?a:eI.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:r,mediaType:s}=n,o=eI.Video|eI.LwoVideo;if(this._p2pChannel.hasRemoteMedia(r,s)){await this._p2pChannel.unmuteRemoteNoLock(r,s);const n=i.get(r);i.set(r,"video"===s?n^o:n^eI.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);const n=cT(o=Array.from(i.entries())).call(o,((e,t)=>{let[i,n]=t;if(0===n)return e;const r={stream_id:i.uid,stream_type:n};return n&eI.Audio&&(r.audio_ssrc=i._audioSSRC),n&eI.Video&&(r.video_ssrc=i._videoSSRC),e.push(r),e}),[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map((e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i,ssrcId:i===dI.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===dI.VIDEO?t._rtxSsrcId:void 0}})));const i=new Map;if(n.length>0){const e=await this._gateway.subscribeAll(n,!0);((null==e?void 0:e.users)||[]).forEach((e=>{let{stream_id:t,video_error_code:n,audio_error_code:r,error_code:s}=e;(n||r||s)&&i.set(t,{video_error_code:n,audio_error_code:r,error_code:s})}))}if(Array.from(i.entries()).length>0){const e=Array.from(i.entries()).map((e=>{let t,[i,n]=e;return n.error_code||n.video_error_code&&n.audio_error_code?t=void 0:n.video_error_code?t=dI.VIDEO:n.audio_error_code&&(t=dI.AUDIO),{user:this.remoteUsers.find((e=>e.uid===i)),mediaType:t}}));await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of r){const t=i.get(e.user.uid);if(t){const i=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(i){const t=kI(i);WC.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new Mv(xg.SUBSCRIBE_FAILED,"code ".concat(i,": ").concat(t.desc))}}e.error||("video"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack)}return this.store.massSubscribe(r.filter((e=>!e.error)).map((e=>({userId:e.user.uid,type:e.mediaType}))),void 0,Date.now()),r.forEach((e=>{var i;iv.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===dI.VIDEO,audio:e.mediaType===dI.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===dI.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t)},!0)})),WC.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)})).join("; "))),r}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{s(),n()}}async unsubscribe(e,t,i){if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,i)}else await this._unsubscribeDataChannel(e,i);if(t&&Bg(t,"mediaType",["audio","video"]),!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find((t=>t===e))){const t=new Mv(xg.INVALID_REMOTE_USER,"user is not in the channel");throw WC.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}WC.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const n=await this._subscribeMutex.lock();try{if(this._p2pChannel instanceof wM)await this._gateway.sendExtensionMessage(AI.UNSUBSCRIBE,{mediaType:t});else{const i=await this._p2pChannel.unsubscribe(e,t);i&&await this._gateway.unsubscribe(i,e.uid),WC.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===xg.DISCONNECT_P2P)return void WC.warning("disconnecting p2p, abort unsubscribe request.");throw WC.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{n()}}async _unsubscribeDataChannel(e,t){if(t&&jg(t,"id",0,65535,!0),!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");if(!this._users.find((t=>t===e))){const t=new Mv(xg.INVALID_REMOTE_USER,"user is not in the channel");throw WC.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}let i;if("number"==typeof t){const n=e._dataChannels.find((e=>e.id===t));n&&(i=[n])}else i=e._dataChannels;if(void 0===i){const i=new Mv(xg.REMOTE_USER_IS_NOT_PUBLISHED);throw WC.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i}WC.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(i.map((e=>e.id))));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,i);t&&await this._gateway.unsubscribeDataChannel(t,e.uid),WC.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===xg.DISCONNECT_P2P)return void WC.warning("disconnecting p2p, abort unsubscribe request.");throw WC.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(Hg(e,"unsubscribeList"),!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");WC.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join())),e=[...e];const t=new Map;for(let i=e.length-1;i>=0;i--){const{user:n,mediaType:r}=e[i];if(!n){const e=new Mv(xg.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw WC.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}if(Bg(r,"mediaType",["video","audio",void 0]),!this._users.find((e=>e===n))){WC.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),e.splice(i,1);continue}const s=eI.Video|eI.LwoVideo;if(t.has(n)){const o=t.get(n);let a;switch(r){case"video":a=o&s;break;case"audio":a=o&eI.Audio;break;default:a=o&(eI.Audio|s)}if(a){WC.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(n.uid,",mediaType:").concat(r," twice.")),e.splice(i,1);continue}r?"audio"===r?t.set(n,o|eI.Audio):"video"===r&&t.set(n,o|s):t.set(n,o|eI.Audio|s)}else r?"audio"===r?t.set(n,eI.Audio):"video"===r&&t.set(n,s):t.set(n,eI.Audio|s)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),WC.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map((e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")})).join()))}catch(e){if(e.code===xg.DISCONNECT_P2P)return void WC.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw WC.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){!function(e){if(!e)throw new Vg(xg.INVALID_PARAMS);Kg(e.width)||Gg(e.width,"streamParameter.width"),Kg(e.height)||Gg(e.height,"streamParameter.height"),Kg(e.framerate)||Gg(e.framerate,"streamParameter.framerate"),Kg(e.bitrate)||jg(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&WC.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),WC.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e,this._isDualStreamEnabled)return this._p2pChannel.updateVideoStreamParameter(e,uI.LocalVideoLowTrack)}async enableDualStream(){if(!hA().supportDualStream)throw iv.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new Mv(xg.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new Mv(xg.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw iv.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,iv.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),WC.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this._p2pChannel.getLocalMedia(uI.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw iv.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,iv.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),WC.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(function(e){Bg(e,"role",["audience","host"])}(e),t&&mS(t),"rtc"===this.mode)throw WC.warning("[".concat(this._clientId,"]rtc mode can not use setClientRole")),new Mv(xg.INVALID_OPERATION,"rtc mode can not use setClientRole");if(t&&t.level&&"host"===e)throw new Mv(xg.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new Mv(xg.INVALID_OPERATION,"can not set client role to audience when publishing stream");await this._gateway.setClientRole(e,t),this._config.role=e,WC.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level))}getRemoteInboundOffset(){var e;const t=null===(e=this._p2pChannel.getStats())||void 0===e?void 0:e.audioSend[0];if(!t||!t.timestamp)return 0;const i=t.timestamp-Date.now();return Math.abs(i)>1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0}getNtpWallTimeInMs(){return"visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(Wg(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new Mv(xg.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,iv.setProxyServer(this._proxyServer),WC.setProxyServer(this._proxyServer),WC.info("[".concat(this._clientId,"] Set proxy server ").concat(t?"by initialize call":""," success."))}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if("DISCONNECTED"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new Mv(xg.INVALID_OPERATION,"You have already set the proxy")}if(_S(e))return this._turnServer={servers:e,mode:"original-manual"},void WC.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>ES(e))),this._turnServer={servers:e,mode:"manual"},WC.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"you should set license before join channel");if(Wg(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new Mv(xg.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,WC.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new Mv(xg.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let i;switch(void 0===e&&(e=3),e){case 1:case 2:throw new Mv(xg.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:i="proxy3";break;case 4:i="proxy4";break;case 5:i="proxy5";break;default:throw new Mv(xg.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,WC.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"Stop proxy server after leave channel");iv.setProxyServer(),WC.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",WC.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]}}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new Mv(xg.INVALID_PARAMS,"accessPoints is required.");Hg(e.accessPoints.serverList,"accessPoints.serverList"),Wg(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{jg(e,t,0,65535,!0)};let i=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),i=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new Mv(xg.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");kC("CLOSE_AFB_FOR_LOCAL_AP")&&(LC("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),LC("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const n=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,r=e.accessPoints.domain,s=e.accessPoints.serverList.map((e=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(r):e)),o=s.map((e=>"".concat(e,":").concat(i)));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,LC("WEBCS_DOMAIN",o),LC("WEBCS_DOMAIN_BACKUP_LIST",o),LC("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(Hg(e.report.hostname,"report.hostname"),LC("EVENT_REPORT_DOMAIN",e.report.hostname[0]),LC("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(LC("EVENT_REPORT_DOMAIN",s[0]),LC("EVENT_REPORT_BACKUP_DOMAIN",s[1]||s[0]));let a=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),a=e.report.port),LC("STATS_COLLECTOR_PORT",a),e.report?LC("ENABLE_EVENT_REPORT",!0):LC("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(Hg(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=s[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),LC("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(Hg(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=s;let h=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),h=e.cds.port),LC("CDS_AP",l.map((e=>"".concat(e,":").concat(h)))),e.cds?LC("ENABLE_CONFIG_DISTRIBUTE",!0):LC("ENABLE_CONFIG_DISTRIBUTE",!1),WC.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(Hg(e,"serverList"),Wg(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new Mv(xg.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const i=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map((e=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e)),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,LC("WEBCS_DOMAIN",e),LC("WEBCS_DOMAIN_BACKUP_LIST",e),LC("GATEWAY_DOMAINS",[t]),LC("EVENT_REPORT_DOMAIN",e[0]),LC("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),LC("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),WC.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(Bg(e,"streamType",[0,1]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw WC.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else WC.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){Bg(t,"streamType",[0,1]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout((()=>{const t=this._users.find((t=>t.uid===e));t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution()}),2e3)}catch(e){throw WC.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}WC.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){Bg(t,"fallbackType",[0,1,2]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw WC.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}WC.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,i){!function(e){Bg(e,"encryptionMode",["aes-128-xts","aes-256-xts","aes-128-ecb","sm4-128-ecb","aes-128-gcm","aes-256-gcm","aes-128-gcm2","aes-256-gcm2","none"])}(e),Wg(t,"secret");const n=["aes-128-gcm2","aes-256-gcm2"];if(Lr(n).call(n,e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new Mv(xg.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new Mv(xg.INVALID_PARAMS,"current encrypt mode does not need salt");new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||WC.warning("The secret is not strong:\n The secret must contain at least 1 lowercase alphabetical character,\n The secret must contain at least 1 uppercase alphabetical character,\n The secret must contain at least 1 numeric character,\n The secret must contain at least one special character,\n The secret must be eight characters or longer.\n "),this._encryptionMode=e,this._encryptionSecret=t,i&&(this._encryptionSalt=PS(i))}async renewToken(e){if(Wg(e,"token",1,2047),!this._key||!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const i=await this._renewTokenMutex.lock();try{if(kC("USE_NEW_TOKEN")){WC.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await pP(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||JS);WC.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else WC.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});WC.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,WC.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?WC.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(dS.VOLUME_INDICATOR,e)}),kC("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e}async startLiveStreaming(e,t){if(!t){if("h264"!==this.codec)throw new Mv(xg.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new Mv(xg.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new Mv(xg.LIVE_STREAMING_TASK_CONFLICT);const i=t?vv.TRANSCODE:vv.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(vv.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new Mv(xg.INVALID_PARAMS,"can not find live streaming url to stop");await tg.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async addInjectStreamUrl(e,t){if(!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"can not addInjectStreamUrl, no joininfo");const i=this._createLiveStreamingClient(vv.INJECT);i.setInjectStreamConfig(t,0),await i.startLiveStreamingTask(e,vv.INJECT)}async removeInjectStreamUrl(){var e;const t=this._createLiveStreamingClient(vv.INJECT),i=Array.from(Pv(e=t.streamingTasks).call(e)).find((e=>e.mode===vv.INJECT));if(!this._joinInfo||!i)throw new Mv(xg.INVALID_OPERATION,"can remove addInjectStreamUrl, no joininfo or inject task");await t.stopLiveStreamingTask(i.url)}async startChannelMediaRelay(e){IP(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){IP(e);const t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e)}async stopChannelMediaRelay(){const e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)}sendStreamMessage(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){const t=new TextEncoder;e.payload=t.encode(e.payload)}if(new Blob([e.payload]).size>1024)throw new Mv(xg.INVALID_PARAMS,"stream message out of range.");return this._gateway.signal.request(fv.DATA_STREAM,{payload:PS(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-PM},!t)}sendMetadata(e){if(!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new Mv(xg.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(fv.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:PS(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(YC),!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"can not send custom report, not joined");await iv.sendCustomReportMessage(this._joinInfo.sid,e)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){return this._statsCollector.getRemoteNetworkQualityStats()}async pickSVCLayer(e,t){Bg(t.spatialLayer,"spatialLayer",[0,1,2,3]),Bg(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw WC.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}setRTM2Flag(e){if(Bg(e,"flag",[0,1]),!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"Can't setRtm2Flag, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"Can't setRtm2Flag in ".concat(this.connectionState," state"));return this._gateway.setRTM2Flag(e)}_reset(){if(WC.debug("[".concat(this._clientId,"] reset client")),this._axiosCancelSource.cancel(),this._axiosCancelSource=EC.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId=null,this.store.sessionId=null,this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._pendingPublishedUsers=[],this._users.forEach((e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach((e=>e._close())),e._dataChannels.length=0)})),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),"fallback"===this._cloudProxyServerMode&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new YS("client-publish"),this._subscribeMutex=new YS("client-subscribe"),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._injectStreamingClient&&(this._injectStreamingClient.terminate(),this._injectStreamingClient.removeAllListeners(),this._injectStreamingClient=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0}catch(e){}if(this._moderation)try{this.setImageModeration(!1)}catch(e){}}_startSession(e,t){const i=e||VS();e?WC.debug("[".concat(this._clientId,"] new Session ").concat(i)):WC.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(i)),this._sessionId=i,this.store.sessionId=i,t?iv.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:t.channel,appid:t.appId,mode:this.mode}):this._joinInfo?iv.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:this._joinInfo.cname,appid:this._joinInfo.appId,mode:this.mode}):this._gateway.joinInfo&&iv.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:this._gateway.joinInfo.cname,appid:this._gateway.joinInfo.appId,mode:this.mode}),this._joinInfo&&(this._joinInfo.sid=i),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=i)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new Mv(xg.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&kC("FORCE_TURN")&&!kC("TURN_ENABLE_TCP")&&!kC("TURN_ENABLE_UDP"))throw new Mv(xg.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");WC.debug("[".concat(this._clientId,"] publish high stream"));try{if(this._p2pChannel instanceof wM){const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(i)try{await this._gateway.sendExtensionMessage(AI.PUBLISH,i)}catch(t){throw this._p2pChannel.unpublish(e),t}}else{const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter),n=(await i.next()).value;if(n){var t;let r;try{r=await this._gateway.publish(this._uid,n,!0)}catch(e){if(e.code!==xg.DISCONNECT_P2P)throw i.throw(e),e}await i.next((null===(t=r)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof fb&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig),!t.muted&&t.enabled||await this._p2pChannel.muteLocalTrack(t)}}catch(t){if(this._p2pChannel.reportPublishEvent(!1,null==t?void 0:t.code,e),(null==t?void 0:t.code)===xg.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new Mv(xg.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new Mv(xg.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));WC.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=e.bitrate));try{const e=await this._p2pChannel.publishLowStream(this._lowStreamParameter),i=(await e.next()).value;if(i){var t;let n;try{n=await this._gateway.publish(this._uid,i,!0)}catch(t){if(t.code!==xg.DISCONNECT_P2P)throw e.throw(t),t}e.next((null===(t=n)||void 0===t?void 0:t.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0)}}catch(e){if(this._p2pChannel.reportPublishEvent(!1,null==e?void 0:e.code,void 0,!0),(null==e?void 0:e.code)===xg.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){if(!this._joinInfo||!this._appId)return new Mv(xg.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw();const t=()=>new CP(this._joinInfo,this._config.websocketRetryConfig||JS,this._config.httpRetryConfig||JS),i=e=>{e.onLiveStreamError=(e,t)=>{iv.reportApiInvoke(this._sessionId,{name:sS.ON_LIVE_STREAM_ERROR,options:[e,t],tag:oS.TRACER}).onSuccess(),this.safeEmit(dS.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{iv.reportApiInvoke(this._sessionId,{name:sS.ON_LIVE_STREAM_WARNING,options:[e,t],tag:oS.TRACER}).onSuccess(),this.safeEmit(dS.LIVE_STREAMING_WARNING,e,t)},e.on(Hv.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new Mv(xg.INVALID_OPERATION,"can not find join info to get worker manager"));hP(e,this._joinInfo,this._axiosCancelSource.token,JS).then(t).catch(i)}))};switch(e){case vv.RAW:return this._liveRawStreamingClient||(this._liveRawStreamingClient=t(),i(this._liveRawStreamingClient)),this._liveRawStreamingClient;case vv.TRANSCODE:return this._liveTranscodeStreamingClient||(this._liveTranscodeStreamingClient=t(),i(this._liveTranscodeStreamingClient)),this._liveTranscodeStreamingClient;case vv.INJECT:return this._injectStreamingClient||(this._injectStreamingClient=t(),this._injectStreamingClient.on(Hv.REQUEST_WORKER_MANAGER_LIST,((e,t,i)=>{if(!this._joinInfo)return i(new Mv(xg.INVALID_OPERATION,"can not find join info to get worker manager"));hP(e,this._joinInfo,this._axiosCancelSource.token,JS).then(t).catch(i)})),this._injectStreamingClient.onInjectStatusChange=(e,t,i)=>{this.safeEmit(dS.INJECT_STREAM_STATUS,e,t,i)}),this._injectStreamingClient}}_createChannelMediaRelayClient(){if(!this._joinInfo)return new Mv(xg.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw();if(!this._channelMediaRelayClient){const{sendResolutionWidth:e,sendResolutionHeight:t}=this.getLocalVideoStats(),i={width:e,height:t};this._channelMediaRelayClient=new AP(this._joinInfo,this._clientId,this._config.websocketRetryConfig||JS,this._config.httpRetryConfig||JS,i),this._channelMediaRelayClient.on("state",(e=>{e===zv.RELAY_STATE_FAILURE&&this._channelMediaRelayClient&&this._channelMediaRelayClient.dispose(),this.safeEmit(dS.CHANNEL_MEDIA_RELAY_STATE,e)})),this._channelMediaRelayClient.on("event",(e=>{this.safeEmit(dS.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._statsCollector.onStatsChanged=(e,t)=>{var i;"resolution"===e&&(null===(i=this._channelMediaRelayClient)||void 0===i||i.setVideoProfile(t))}}return this._channelMediaRelayClient}_handleUpdateDataChannel(e,t){const{added:i,deleted:n}=e,r=[];Array.isArray(i)&&i.length>0&&i.forEach((e=>{const{uid:i,stream_id:n,ordered:s,max_retrans_times:o,metadata:a}=e,c=this._users.find((e=>e._uintid===i));if(c){if(WC.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),Lr(r).call(r,c)||r.push(c),c._uintid||(c._uintid=i),-1===c._dataChannels.findIndex((t=>t.id===e.stream_id))){const e={id:n,ordered:!!s,maxRetransmits:o,metadata:a},i=new tD(e);c._dataChannels.push(i),WC.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(dS.USER_PUBLISHED,c,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(WC.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(c.uid," after reconnect.")),this._subscribeDataChannel(c,e.stream_id).catch((e=>{WC.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))}else WC.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"))})),t&&(this.safeEmit(dS.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]),Array.isArray(n)&&n.length>0&&n.forEach((e=>{const{uid:t,stream_id:i}=e,n=this._users.find((e=>e._uintid===t));if(!n)return void WC.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const r=n._dataChannels.find((t=>t.id===e.stream_id));r&&(WC.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),this._p2pChannel.unsubscribeDataChannel(n,[r]).then((e=>{if(e)return n._dataChannels=n._dataChannels.filter((e=>e!==r)),this._gateway.unsubscribeDataChannel(e,n.uid)})),WC.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel ,id:").concat(r.id)),this.safeEmit(dS.USER_UNPUBLISHED,n,"datachannel",r._config))}))}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){WC.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const i=()=>{WC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(dS.USER_UNPUBLISHED,t,"datachannel",e._config)}))};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid)})),i()}}else WC.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(Zv.DISCONNECT_P2P,(async()=>{await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(Zv.CONNECTION_STATE_CHANGE,((e,t,i)=>{var n;if(i===cS.FALLBACK)return;const r=()=>{this.safeEmit(dS.CONNECTION_STATE_CHANGE,e,t,i)};if(iv.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:sS.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:oS.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),WC.info("[".concat(this._clientId,"] connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void r();if("RECONNECTING"===e)this._users.forEach((e=>{e._trust_in_room_=!1,e._trust_audio_enabled_state_=!1,e._trust_video_enabled_state_=!1,e._trust_audio_mute_state_=!1,e._trust_video_mute_state_=!1,e._trust_audio_stream_added_state_=!1,e._trust_video_stream_added_state_=!1,e._audioSSRC=void 0,e._videoSSRC=void 0,e._videoOrtc=void 0,e._audioOrtc=void 0,e._cname=void 0,e._rtxSsrcId=void 0})),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if("CONNECTED"===e){var s;this._streamFallbackTypeCacheMap.forEach(((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch((e=>{WC.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{WC.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)}))})),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(s=this._joinInfo)||void 0===s?void 0:s.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then((()=>{WC.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{WC.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))})),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout((()=>{"CONNECTED"===this.connectionState&&(this._userOfflineTimeout=void 0,this._users.filter((e=>!e._trust_in_room_)).forEach((e=>{WC.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(e.uid)),this._handleUserOffline({uid:e.uid})})))}),3e3),this._streamRemovedTimeout=window.setTimeout((()=>{"CONNECTED"===this.connectionState&&(this._streamRemovedTimeout=void 0,this._users.forEach((e=>{e._trust_audio_mute_state_||(WC.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,dI.AUDIO,!1)),e._trust_video_mute_state_||(WC.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,dI.VIDEO,!1)),e._trust_audio_enabled_state_||(WC.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(WC.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(WC.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(WC.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(WC.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}))})))}),1e3))}r()})),this._gateway.on(Zv.REQUEST_NEW_GATEWAY_LIST,((e,t)=>{if(!this._joinInfo)return t(new Mv(xg.UNEXPECTED_ERROR,"can not recover, no join info"));oP(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||JS,this.store).then((t=>{this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip);const i=[];t.gatewayInfo.gatewayAddrs.forEach((e=>{let{address:t}=e;const[n,r]=t.split(":");this._joinInfo&&this._joinInfo.proxyServer?i.push({proxy:this._joinInfo.proxyServer,host:n,port:r}):i.push({host:n,port:r})})),e(i)})).catch(t)})),this._gateway.on(Zv.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(dS.NETWORK_QUALITY,e)})),this._gateway.on(Zv.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(dS.STREAM_TYPE_CHANGED,e,t),iv.reportApiInvoke(this._sessionId,{name:sS.STREAM_TYPE_CHANGE,options:[e,t],tag:oS.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))})),this._gateway.on(Zv.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(Zv.NEED_RENEW_SESSION,(()=>{this._startSession()})),this._gateway.on(Zv.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,i)=>{try{t(await this._p2pChannel.startP2PConnection(e))}catch(e){i(e)}})),this._gateway.on(Zv.JOIN_RESPONSE,((e,t)=>{if(this.store.useP2P)return;const{dtlsParameters:i,iceParameters:n,candidates:r,rtpCapabilities:s,setup:o,cname:a}=JP(e.ortc,t);this._p2pChannel.connect(n,i,r,s,o,a)})),this._gateway.on(Zv.REQUEST_DC_CONNECTION_PARAMS,(e=>{e(this._p2pChannel.getEstablishParams())})),this._gateway.on(Zv.RESET_SIGNAL,(e=>{this._p2pChannel.resetConnection(e),this._handleGatewaySignalEvents()})),this._gateway.on(Zv.DATACHANNEL_FAILBACK,(()=>{this._joinGateway()})),this._gateway.on(Zv.DATACHANNEL_PRECONNECT,(async(e,t,i,n)=>{var r,s,o,a,c,d;await this._p2pChannel.startP2PConnection({turnServer:null===(r=this._joinInfo)||void 0===r?void 0:r.turnServer},!0);const l=function(e,t){let i;return t&&t.ip&&"number"==typeof t.port?(i=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip,port:t.port.toString(),type:"host",extension:{}}],WC.debug("Using remote candidate from AP ".concat(t.ip,":").concat(t.port)),t.ip6&&(i.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip6,port:t.port.toString(),type:"host",extension:{}}),WC.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))):i=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],i}(e,t);return this._p2pChannel.preConnect({iceUfrag:"".concat(null===(s=this._joinInfo)||void 0===s?void 0:s.apResponse.cid,"_").concat(null===(o=this._joinInfo)||void 0===o?void 0:o.apResponse.cert),icePwd:"".concat(null===(a=this._joinInfo)||void 0===a?void 0:a.apResponse.cid,"_").concat(null===(c=this._joinInfo)||void 0===c?void 0:c.apResponse.cert)},{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(d=kC("FINGERPRINT"))&&void 0!==d?d:e.fingerprint}]},l,{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},"active","o/i14u9pJrxRKAsu").then(i).catch(n)}))}_handleGatewaySignalEvents(){this._gateway.signal.on(Sv.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(Sv.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(Sv.ON_ADD_AUDIO_STREAM,(e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc))),this._gateway.signal.on(Sv.ON_ADD_VIDEO_STREAM,(e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc,e.rtxSsrcId))),this._gateway.signal.on(Sv.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(Sv.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{this._handleUpdateDataChannel({added:e.datastreams,deleted:[]},!0)})),this._gateway.signal.on(Sv.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(Sv.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(Sv.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,dI.AUDIO,!0))),this._gateway.signal.on(Sv.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,dI.AUDIO,!1))),this._gateway.signal.on(Sv.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,dI.VIDEO,!0))),this._gateway.signal.on(Sv.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,dI.VIDEO,!1))),this._gateway.signal.on(Sv.RECEIVE_METADATA,(e=>{const t=DS(e.metadata);this.safeEmit(dS.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(Sv.ON_DATA_STREAM,(async e=>{if(!e)return;let t=0;if(e.ordered||e.syncWithAudio){const i=this._p2pChannel.getStats(),n=this.remoteUsers.find((t=>t.uid===e.uid)),r=null==i?void 0:i.audioRecv.find((e=>e.ssrc===(null==n?void 0:n._audioSSRC)));t=null==r?void 0:r.jitterBufferMs}null==t&&(t=0),VM(e,t,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})})),this._gateway.signal.on(Sv.ON_CRYPT_ERROR,(()=>{NS((()=>{WC.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(dS.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(Sv.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(Sv.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{WC.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,cS.TOKEN_EXPIRE),this.safeEmit(dS.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(Sv.ON_STREAM_FALLBACK_UPDATE,(e=>{WC.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(dS.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(Sv.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),WC.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(Sv.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(Sv.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(mv.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case fv.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var i,n;const r=e.some((e=>{let{stream_type:t}=e;return t===Qv.Audio})),s=e.some((e=>{let{stream_type:t}=e;return t!==Qv.Audio})),o=e.some((e=>{let{stream_type:t}=e;return t===Qv.Screen||t===Qv.ScreenLow}));"offer"===t.state&&iv.publish(this._joinInfo.sid,{eventElapse:sD.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:xg.TIMEOUT,audio:r,video:s,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:o,audioName:r?null===(i=e.find((e=>{let{stream_type:t}=e;return t===Qv.Audio})))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0,videoName:s?null===(n=e.find((e=>{let{stream_type:t}=e;return t!==Qv.Audio})))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0})}break}case fv.SUBSCRIBE:t&&iv.subscribe(this._joinInfo.sid,{succ:!1,ec:xg.TIMEOUT,audio:t.stream_type===dI.AUDIO,video:t.stream_type===dI.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:sD.measureFromSubscribeStart(this.store.clientId,t.ssrcId)})}})),this._gateway.signal.on(Sv.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(Sv.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;kC("BLOCK_LOCAL_CLIENT")&&(e.users=e.users.filter((e=>!av(e.string_id||e.stream_id,this.channelName))));const t=[],i=[];for(const n of e.users){let e=this._users.find((e=>e._uintid===n.stream_id));e?e._trust_in_room_=!0:(e=new bP(n.string_id||n.stream_id,n.stream_id),this._users.push(e),0===this.getListeners(dS.PUBLISHED_USER_LIST).length&&(WC.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.safeEmit(dS.USER_JOINED,e)));const r=eI.Audio&n.stream_type,s=(eI.Video|eI.LwoVideo)&n.stream_type,o=0!=(65280&n.stream_type),a=r&&e.hasAudio,c=s&&e.hasVideo;s&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=n.video_ssrc,e._rtxSsrcId=n.video_rtx),r&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=n.audio_ssrc),r&&!a&&0===this.getListeners(dS.PUBLISHED_USER_LIST).length&&(WC.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.safeEmit(dS.USER_PUBLISHED,e,"audio")),s&&!c&&0===this.getListeners(dS.PUBLISHED_USER_LIST).length&&(WC.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.safeEmit(dS.USER_PUBLISHED,e,"video")),(r&&!a||s&&!c||o)&&t.push(e),s&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&i.push({user:e,mediaType:"video"}),r&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&i.push({user:e,mediaType:"audio"})}i.length>0&&(WC.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(i.map((e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType))).join("; ")," ")),this.massSubscribe(i).catch((e=>{WC.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())}))),this.getListeners(dS.PUBLISHED_USER_LIST).length>0?kC("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=t:(WC.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map((e=>e.uid)).join(", "))),this.safeEmit(dS.PUBLISHED_USER_LIST,t)):WC.info("[".concat(this._clientId,"] client not emit user-list event case there is no user-list listener, users: ").concat(t.map((e=>e.uid)).join(", ")))}))}_handleP2PEvents(){this._gateway.signal.on(Sv.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(AI.PUBLISH,(async(e,t)=>{e.forEach((e=>e.kind===dI.VIDEO?(this._handleP2PAddAudioOrVideoStream("video",t),e.isMuted?this._handleMuteStream(t,dI.VIDEO,!0):this._handleMuteStream(t,dI.VIDEO,!1)):(this._handleP2PAddAudioOrVideoStream("audio",t),e.isMuted?this._handleMuteStream(t,dI.AUDIO,!0):this._handleMuteStream(t,dI.AUDIO,!1))))})),this._gateway.signal.on(mv.P2P_START,(async(e,t)=>{var i;this._p2pChannel instanceof wM&&t(await this._p2pChannel.startP2P({turnServer:null===(i=this._joinInfo)||void 0===i?void 0:i.turnServer},e))})),this._gateway.signal.on(mv.P2P_CONNECTION,(async e=>{this._p2pChannel instanceof wM&&await this._p2pChannel.p2pConnect(e)})),this._gateway.signal.on(mv.P2P_REMOTE_CANDIDATE_UPDATE,(e=>{this._p2pChannel instanceof wM&&this._p2pChannel.addRemoteCandidate(JSON.parse(e))})),this._gateway.signal.on(AI.SUBSCRIBE,(async(e,t,i)=>{if(this._p2pChannel instanceof wM){const{trackType:n}=JSON.parse(e);try{await this._p2pChannel.dopublish(n),t()}catch(e){i(e)}}})),this._gateway.signal.on(AI.UNSUBSCRIBE,(async(e,t,i)=>{if(this._p2pChannel instanceof wM){const{mediaType:n}=JSON.parse(e);try{await this._p2pChannel.doUnpublish(n),t()}catch(e){i(e)}}})),this._gateway.signal.on(AI.EXCHANGE_SDP,(async(e,t,i)=>{if(this._p2pChannel instanceof wM){const{type:n,sdp:r}=JSON.parse(e);try{t(await this._p2pChannel.setDescription(n,r))}catch(e){i(e)}}})),this._gateway.signal.on(AI.UNPUBLISH,(async(e,t,i)=>{if(this._p2pChannel instanceof wM){const{unpubMsg:n,uid:r}=e;if(1===n.length){const s=n[0].stream_type===Qv.Audio?dI.AUDIO:dI.VIDEO;this._handleMuteStream(r,s,!0);const{sdp:o}=e;if(this._p2pChannel instanceof wM&&o){const e=this._users.find((e=>e.uid===r));if(!e)return WC.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void t();this._p2pChannel.unsubscribe(e,o,s).then((e=>{e&&t(e)})).catch(i)}else t()}else this._handleRemoveStream(e,t,i)}})),this._gateway.signal.on(AI.CONTROL,(async(e,t,i)=>{const{action:n,sdp:r,isMuteAll:s,uid:o}=e;switch(n){case bI.MUTE_LOCAL_VIDEO:this._handleMuteStream(o,dI.VIDEO,!0,r,t,i);break;case bI.MUTE_LOCAL_AUDIO:t(),this._handleMuteStream(o,dI.AUDIO,!0);break;case bI.UNMUTE_LOCAL_VIDEO:t(),this._handleP2PAddAudioOrVideoStream("video",o),this._handleMuteStream(o,dI.VIDEO,!1);break;case bI.UNMUTE_LOCAL_AUDIO:t(),this._handleP2PAddAudioOrVideoStream("audio",o),this._handleMuteStream(o,dI.AUDIO,!1)}s&&this._handleRemoveStream(e,t,i)})),this._gateway.signal.on(AI.DO_SUBSCRIBE,(async(e,t,i)=>{if(this._p2pChannel instanceof wM){const{kind:n,sdp:r,ssrcId:s,uid:o}=e,a=this._users.find((e=>e.uid===o));if(!a)return WC.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)")),void t();try{t(await this._p2pChannel.subscribe(a,n,r,s))}catch(e){i(e)}}})),this._gateway.signal.on(AI.DO_UNSUBSCRIBE,(async(e,t,i)=>{if(this._p2pChannel instanceof wM){const{uid:n,kind:r,sdp:s}=e,o=this._users.find((e=>e.uid===n));if(!o)return WC.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)")),void t();try{t(await this._p2pChannel.unsubscribe(o,s,r))}catch(e){i(e)}}})),this._gateway.signal.on(AI.RESTART_ICE,(async(e,t,i)=>{if(this._p2pChannel instanceof wM)try{t(await this._p2pChannel.setDescription("remote",e))}catch(e){i(e)}})),this._p2pChannel.on(_I.RequestP2PRestartICE,(async(e,t,i)=>{try{t(await this._gateway.sendExtensionMessage(AI.RESTART_ICE,e))}catch(e){i(e)}})),this._p2pChannel.on(_I.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(AI.CANDIDATE,JSON.stringify(e))})),this._p2pChannel.on(_I.RequestP2PMuteLocal,(async(e,t,i)=>{try{t(await this._gateway.sendExtensionMessage(AI.CONTROL,e))}catch(e){i(e)}})),this._p2pChannel.on(_I.RequestP2PPublish,(async(e,t,i)=>{try{t(await this._gateway.sendExtensionMessage(AI.DO_SUBSCRIBE,e))}catch(e){i(e)}})),this._p2pChannel.on(_I.RequestP2PUnPublish,(async(e,t,i)=>{try{t(await this._gateway.sendExtensionMessage(AI.DO_UNSUBSCRIBE,e))}catch(e){i(e)}})),this._p2pChannel.on(_I.RequestP2PUnmuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===xg.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(_I.RequestP2PMuteRemote,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===xg.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(_I.StateChange,((e,t)=>{t===pI.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(_I.RequestMuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===xg.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(_I.RequestUnmuteLocal,(async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===xg.DISCONNECT_P2P?t():i(e)}else t()})),this._p2pChannel.on(_I.RequestRePublish,((e,t,i)=>{this.publish(e,!1).then(t).catch(i)})),this._p2pChannel.on(_I.RequestRePublishDataChannel,((e,t,i)=>{tg.all(e.map((async e=>{await this._p2pChannel.publishDataChannel([e]);const t={streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId};try{await this._gateway.publishDataChannel(this._uid,t,!0)}catch(e){if(e.code!==xg.DISCONNECT_P2P)throw e}}))).then(t).catch(i)})),this._p2pChannel.on(_I.RequestReSubscribe,(async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===dI.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){i(e)}})),this._p2pChannel.on(_I.RequestUploadStats,((e,t)=>{this._gateway.uploadStats(e,t)})),this._p2pChannel.on(_I.MediaReconnectStart,(e=>{this.safeEmit(dS.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(_I.MediaReconnectEnd,(e=>{this.safeEmit(dS.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(_I.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(_I.RequestRestartICE,(async e=>{if(this._p2pChannel instanceof wM)return;const t=await this._p2pChannel.restartICE(e),i=await t.next();if(i.done)return;const n=i.value;let r;try{r=await this._gateway.restartICE({iceParameters:n})}catch(e){return void t.throw(e)}const{iceParameters:s}=function(e){const t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(r);await t.next({remoteIceParameters:s})})),this._p2pChannel.on(_I.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(_I.RequestReconnectPC,(async()=>{var e;const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),{gatewayEstablishParams:r,gatewayAddress:s}=await this._gateway.reconnectPC({iceParameters:t,dtlsParameters:i,rtpCapabilities:n}),{dtlsParameters:o,iceParameters:a,candidates:c,rtpCapabilities:d,setup:l,cname:h}=JP(r,s);await this._p2pChannel.connect(a,o,c,d,l,h),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(_I.RequestUnpublishForReconnectPC,(async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()})),this._p2pChannel.on(_I.P2PLost,(()=>{this.safeEmit(dS.P2P_LOST,this.store.uid)})),this._p2pChannel.on(_I.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(_I.ConnectionTypeChange,(e=>{this.safeEmit(dS.IS_USING_CLOUD_PROXY,e)})),this._p2pChannel.on(_I.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(_I.QueryClientConnectionState,(e=>{e(this.connectionState)}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if("CONNECTED"!==this.connectionState||!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"[".concat(this._clientId,"] Client did not join channel"));if(this._inspect)throw new Mv(xg.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));if(!e)throw new Mv(xg.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig is necessary"));if(!e.inspectType||!Array.isArray(e.inspectType))throw new Mv(xg.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.inspectType is necessary and is an instance of Array."));{const t=[...new Set(e.inspectType)];t.forEach((e=>{var t;if(!Lr(t=["supervise","moderation"]).call(t,e))throw new Mv(xg.INVALID_PARAMS,"[".concat(this._clientId,"] ").concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new Mv(xg.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.extraInfo length cannot exceed 1024 bytes"));try{const t=new jk(e);this._inspect=t,this.handleVideoInspectEvents(this._inspect),await t.init({appId:this._joinInfo.appId,areaCode:"",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},JS)}catch(e){throw Array.isArray(e)?e[0]:e}}async disableContentInspect(){if(!this._inspect)throw new Mv(xg.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}async setImageModeration(e,t){if(Fg(e,"enabled"),e){if(!t)throw new Mv(xg.INVALID_PARAMS,"[".concat(this._clientId,"] config is necessary"));if(jg(t.interval,"interval",1e3,1/0),"CONNECTED"!==this.connectionState||!this._joinInfo)throw new Mv(xg.INVALID_OPERATION,"[".concat(this._clientId,'] can not enable image moderation, not joined"'));try{if(this._moderation)return void this._moderation.updateConfig(t);const e=new TM(t);this._moderation=e,this.handleImageModerationEvents(this._moderation),await e.init({appId:this._joinInfo.appId,areaCode:"",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},JS)}catch(e){throw Array.isArray(e)?e[0]:e}}else{if(!this._moderation)throw new Mv(xg.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}}handleImageModerationEvents(e){e.on(II.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(dS.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===vI.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new Mv(xg.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(II.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}handleVideoInspectEvents(e){e.on(gI.CONNECTION_STATE_CHANGE,((t,i)=>{if(this.safeEmit(dS.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===mI.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(dS.CONTENT_INSPECT_ERROR,new Mv(xg.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on(gI.INSPECT_RESULT,((e,t)=>{var i;if((null==t?void 0:t.code)===xg.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return WC.debug("Stop inspect content because that has left channel"),null==this||null===(i=this._inspect)||void 0===i||i.close(),void(this._inspect=void 0);this.safeEmit(dS.CONTENT_INSPECT_RESULT,e,t)})),e.on(gI.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}getJoinChannelServiceRecords(){return WC.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){Fg(e,"enabled"),LC("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0}}}Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],jM.prototype,"leave",null),Lv([tv({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof $y))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),kv("design:type",Function),kv("design:paramtypes",[Object,Boolean]),kv("design:returntype",tg)],jM.prototype,"publish",null),Lv([tv({argsMap:(e,t)=>(t||(t=[]),t instanceof iD?[t.getChannelId()]:(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))))}),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],jM.prototype,"unpublish",null),Lv([tv({argsMap:(e,t,i,n)=>[t.uid,i,n]}),kv("design:type",Function),kv("design:paramtypes",[bP,String,Number]),kv("design:returntype",tg)],jM.prototype,"subscribe",null),Lv([tv({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]}))}),kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],jM.prototype,"massSubscribe",null),Lv([tv({argsMap:(e,t,i,n)=>[t.uid,i,n]}),kv("design:type",Function),kv("design:paramtypes",[bP,String,Number]),kv("design:returntype",tg)],jM.prototype,"unsubscribe",null),Lv([tv({argsMap:(e,t)=>t.map((e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}}))}),kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",tg)],jM.prototype,"massUnsubscribe",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],jM.prototype,"setLowStreamParameter",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],jM.prototype,"enableDualStream",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],jM.prototype,"disableDualStream",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[String,Object]),kv("design:returntype",tg)],jM.prototype,"setClientRole",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[String,Boolean]),kv("design:returntype",void 0)],jM.prototype,"setProxyServer",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Object,Boolean]),kv("design:returntype",void 0)],jM.prototype,"setTurnServer",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",void 0)],jM.prototype,"setLicense",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",void 0)],jM.prototype,"startProxyServer",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],jM.prototype,"stopProxyServer",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",void 0)],jM.prototype,"setLocalAccessPointsV2",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Array,String]),kv("design:returntype",void 0)],jM.prototype,"setLocalAccessPoints",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",tg)],jM.prototype,"setRemoteDefaultVideoStreamType",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Object,Number]),kv("design:returntype",tg)],jM.prototype,"setRemoteVideoStreamType",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Object,Number]),kv("design:returntype",tg)],jM.prototype,"setStreamFallbackOption",null),Lv([tv({argsMap:(e,t)=>[t]}),kv("design:type",Function),kv("design:paramtypes",[String,String,Uint8Array]),kv("design:returntype",void 0)],jM.prototype,"setEncryptionConfig",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],jM.prototype,"renewToken",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],jM.prototype,"enableAudioVolumeIndicator",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[String,Boolean]),kv("design:returntype",tg)],jM.prototype,"startLiveStreaming",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],jM.prototype,"setLiveTranscoding",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[String]),kv("design:returntype",tg)],jM.prototype,"stopLiveStreaming",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[String,Object]),kv("design:returntype",tg)],jM.prototype,"addInjectStreamUrl",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],jM.prototype,"removeInjectStreamUrl",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[vP]),kv("design:returntype",tg)],jM.prototype,"startChannelMediaRelay",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[vP]),kv("design:returntype",tg)],jM.prototype,"updateChannelMediaRelay",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],jM.prototype,"stopChannelMediaRelay",null),Lv([tv({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],jM.prototype,"sendCustomReportMessage",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Object,Object]),kv("design:returntype",tg)],jM.prototype,"pickSVCLayer",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Number]),kv("design:returntype",tg)],jM.prototype,"setRTM2Flag",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Object]),kv("design:returntype",tg)],jM.prototype,"enableContentInspect",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",tg)],jM.prototype,"disableContentInspect",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Boolean,Object]),kv("design:returntype",tg)],jM.prototype,"setImageModeration",null),Lv([tv({reportResult:!0}),kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",Array)],jM.prototype,"getJoinChannelServiceRecords",null),Lv([tv(),kv("design:type",Function),kv("design:paramtypes",[Boolean]),kv("design:returntype",tg)],jM.prototype,"setPublishAudioFilterEnabled",null);const GM=pg().name;class WM{constructor(e,t){nu(this,"id",0),nu(this,"element",void 0),nu(this,"peerPair",void 0),nu(this,"context",void 0),nu(this,"audioPlayerElement",void 0),nu(this,"audioTrack",void 0),WM.count+=1,this.id=WM.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const i="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),"complete"===e.iceGatheringState?e.localDescription:new tg((t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription)}}))},t=async(e,t)=>await e.setRemoteDescription(t);try{const i=await e(this.peerPair[0],"offer");await t(this.peerPair[1],i);const n=await e(this.peerPair[1],"answer");await t(this.peerPair[0],n)}catch(e){throw new Mv(xg.LOCAL_AEC_ERROR,e.toString()).print()}}async getTracksFromMediaElement(e){if(this.audioTrack)return this.audioTrack;let t;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination(),this.context.createMediaElementSource(e).connect(t)}catch(e){throw new Mv(xg.LOCAL_AEC_ERROR,e.toString()).print()}if(!t)throw new Mv(xg.LOCAL_AEC_ERROR,"no dest node when local aec").print();const i=t.stream.getAudioTracks()[0];return this.audioTrack=i,i}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp()}close(){WC.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach((e=>{e.close()})),this.peerPair=void 0,this.audioPlayerElement=void 0}}nu(WM,"count",0);const HM=window.AudioContext||window.webkitAudioContext;class KM{constructor(){nu(this,"units",[]),nu(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return WC.debug("the system does not need to process local aec"),-1;this.context||(this.context=new HM);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new WM(e,this.context),this.units.push(t)),t.startEchoCancellation(),WC.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return pg().name!==cg.SAFARI}}Lv([tv({report:iv}),kv("design:type",Function),kv("design:paramtypes",[HTMLAudioElement]),kv("design:returntype",Number)],KM.prototype,"processExternalMediaAEC",null);const YM=new KM;function qM(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function JM(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?qM(Object(i),!0).forEach((function(t){nu(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):qM(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const zM=window||document;function XM(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!zM)return;const i=QM._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(QM.onSecurityPolicyViolation||QM.getListeners(RI.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;kC("CSP_DETECTED_HOSTNAME_LIST").some((e=>Lr(t).call(t,e)))&&(QM.onSecurityPolicyViolation&&"function"==typeof QM.onSecurityPolicyViolation&&QM.onSecurityPolicyViolation(e),QM.getListeners(RI.SECURITY_POLICY_VIOLATION).length>0&&QM.safeEmit(RI.SECURITY_POLICY_VIOLATION,e))};i&&zM.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||QM.getListeners(RI.SECURITY_POLICY_VIOLATION).length>0)&&zM.addEventListener("securitypolicyviolation",n),QM._cspEventHandlerPointer=n}LC("PROCESS_ID","process-".concat(xS(8,""),"-").concat(xS(4,""),"-").concat(xS(4,""),"-").concat(xS(4,""),"-").concat(xS(12,""))),function(){const e=pg();lA.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),lA.getStreamFromExtension=e.name===cg.CHROME&&Number(e.version)>34,lA.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const e=new RTCPeerConnection;let t=!1;try{e.addTransceiver("audio"),t=!0}catch(e){}return e.close(),t}(),lA.supportMinBitrate=e.name===cg.CHROME||e.name===cg.EDGE,lA.supportSetRtpSenderParameters=function(){const e=pg();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!kg()||!(!Tg()&&!mg())||e.name===cg.FIREFOX&&Number(e.version)>=64)}(),e.name===cg.SAFARI&&(Number(e.version)>=14?lA.supportDualStream=!0:lA.supportDualStream=!1),lA.webAudioMediaStreamDest=function(){const e=pg();return!(e.name===cg.SAFARI&&Number(e.version)<12)}(),lA.supportReplaceTrack=!!window.RTCRtpSender&&"function"==typeof RTCRtpSender.prototype.replaceTrack,lA.supportWebGL="undefined"!=typeof WebGLRenderingContext,lA.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,kg()||(lA.webAudioWithAEC=!0),lA.supportShareAudio=function(){const e=pg();return(e.os===ag.WIN_10||e.os===ag.WIN_81||e.os===ag.WIN_7||e.os===ag.LINUX||e.os===ag.MAC_OS)&&e.name===cg.CHROME&&Number(e.version)>=74}(),lA.supportDataChannel=!!(vg(76)||function(e){const t=pg();return!(t.name!==cg.FIREFOX||!t.osVersion)&&Number(t.version)>=e}(68)||function(e){const t=pg();return!(t.name!==cg.SAFARI||!t.osVersion)&&Number(t.version)>=e}(14)),lA.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!Rg()&&!!e&&e.prototype.setConfiguration instanceof Function}(),lA.supportWebRTCEncodedTransform=function(){const e=pg();return"Chrome"===e.name&&Number(e.version)>=86}(),lA.supportWebRTCInsertableStream=function(){const e=pg();return(e.name===cg.CHROME||e.name===cg.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),AS((()=>{lA.supportDualStreamEncoding=function(){const e=pg();return!!kC("DISABLE_WEBAUDIO")||"Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&kC("CHROME_DUAL_STREAM_USE_ENCODING"))}(),WC.info("browser compatibility",JSON.stringify(lA),JSON.stringify(e))}))}(),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void WC.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();WC.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(PC,e)){const{value:n,expires:r}=t[e];if(r&&r<=i)return;MC[e]=n,PC[e]=n}}))}catch(t){WC.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(MC.AREAS)&&MC.AREAS.length>0&&HD(MC.AREAS,!0);const QM=function(e){const t=new iS,i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===RI.SECURITY_POLICY_VIOLATION&&XM(t,!0)}(e,i),t.on.bind(t)(e,i)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return JM(JM({},i),n)}({__TRACK_LIST__:wy,VERSION:OC,BUILD:DC,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:(e,t,i)=>{WC.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),LC(e,t,i)},getParameter:kC,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;t.addTransceiver("video",{direction:"recvonly"}),t.addTransceiver("audio",{direction:"recvonly"});const i=(await t.createOffer()).sdp;if(!i)return e;t.close(),t=null,e=function(e){const t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push("VP8"),e.match(/ VP9/i)&&t.video.push("VP9"),e.match(/ AV1/i)&&t.video.push("AV1"),e.match(/ H264/i)&&t.video.push("H264"),e.match(/ H265/i)&&t.video.push("H265"),e.match(/ opus/i)&&t.audio.push("OPUS"),e.match(/ PCMU/i)&&t.audio.push("PCMU"),e.match(/ PCMA/i)&&t.audio.push("PCMA"),e.match(/ G722/i)&&t.audio.push("G722"),t}(i)}catch(e){throw new Mv(xg.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){const e=iv.reportApiInvoke(null,{name:sS.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:oS.TRACER});let t=!1;try{const e=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(e&&i&&n)}catch(e){return WC.error("check system requirement failed: ",e),!1}let i=!1;const n=pg();n.name===cg.CHROME&&Number(n.version)>=58&&(!gg()||fg())&&(i=!0),n.name===cg.FIREFOX&&Number(n.version)>=56&&(i=!0),n.name===cg.OPERA&&Number(n.version)>=45&&(i=!0),n.name===cg.SAFARI&&Number(n.version)>=11&&(i=!0),(Pg()||pg().name===cg.QQ)&&(i=!0),WC.debug("checkSystemRequirements, api:",t,"browser",i);const r=t&&i;return e.onSuccess(r),r},getDevices:function(e){return AA.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return AA.getRecordingDevices(e)},getCameras:function(e){return AA.getCamerasDevices(e)},getElectronScreenSources:fA,getPlaybackDevices:function(e){return AA.getSpeakers(e)},createClient:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=iv.reportApiInvoke(null,{name:sS.CREATE_CLIENT,options:[e],tag:oS.TRACER});try{!function(e){Bg(e.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),Bg(e.mode,"config.mode",["rtc","live"]),void 0!==e.audioCodec&&Bg(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&Wg(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&ES(e.turnServer),void 0!==e.httpRetryConfig&&pS(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&pS(e.websocketRetryConfig)}(e)}catch(e){throw t.onError(e),e}return void 0===e.audioCodec&&(e.audioCodec="opus"),t.onSuccess(),new jM(BM(BM({forceWaitGatewayResponse:!0},e),{},{role:"rtc"===e.mode?"host":e.role||"audience"}))},createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.CREATE_CAM_VIDEO_TRACK,options:[Tb({},e)]}),i=$A(e),n=xS(8,"track-cam-");let r=null;WC.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{r=(await CA({video:i},n)).getVideoTracks()[0]||null}catch(e){throw t.onError(e),e}if(!r){const e=new Vg(xg.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw(WC)}e.optimizationMode&&Rb(n,r,e,vy(e.encoderConfig));const s=new gb(r,e,i,e.scalabiltyMode?yy(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return t.onSuccess(s.getTrackId()),WC.info("create camera video success, trackId:",n),s},createCustomVideoTrack:function(e){const t=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.CREATE_CUSTOM_VIDEO_TRACK,options:[e]}),i=new fb(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?yy(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,xS(8,"track-cus-"),[Dy.CUSTOM_TRACK]);return t.onSuccess(i.getTrackId()),WC.info("create custom video track success with config",e,"trackId",i.getTrackId()),i},createScreenVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const i=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.CREATE_SCREEN_VIDEO_TRACK,options:[Tb({},e),t]});e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const n=function(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&Sg()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:n,surfaceSwitching:r,systemAudio:s}=e;(vg(107)||Ig(107)||yg(93))&&(i&&(Bg(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),n?(Bg(n,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=n):t.selfBrowserSurface="include",r&&(Bg(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(vg(105)||Ig(105)||yg(91))&&s&&(Bg(s,"systemAudio",["exclude","include"]),t.systemAudio=s),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const o=e.encoderConfig?Iy(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:o?o.width:void 0,maxHeight:o?o.height:void 0},o&&(o.frameRate&&("number"==typeof o.frameRate?(t.mandatory.maxFrameRate=o.frameRate,t.mandatory.minFrameRate=o.frameRate):(t.mandatory.maxFrameRate=o.frameRate.max||o.frameRate.ideal||o.frameRate.exact||void 0,t.mandatory.minFrameRate=o.frameRate.min||o.frameRate.ideal||o.frameRate.exact||void 0),t.frameRate=o.frameRate),o.width&&(t.width=o.width),o.height&&(t.height=o.height)),t}(e),r=xS(8,"track-scr-v-");let s=null,o=null;const a=hA();if(!a.supportShareAudio&&"enable"===t){const e=new Vg(xg.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return i.onError(e),e.throw(WC)}WC.info("start create screen video track with config",e,"withAudio",t,"trackId",r);try{const e=await CA({screen:n,screenAudio:"auto"===t?a.supportShareAudio:"enable"===t},r);s=e.getVideoTracks()[0]||null,o=e.getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!s){const e=new Vg(xg.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(WC)}if(!o&&"enable"===t){s&&s.stop();const e=new Vg(xg.SHARE_AUDIO_NOT_ALLOWED);return i.onError(e),e.throw(WC)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(Rb(r,s,e,e.encoderConfig&&Iy(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const c=new fb(s,e.encoderConfig?Iy(e.encoderConfig):{},e.scalabiltyMode?yy(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r,[Dy.SCREEN_TRACK]);if(!o)return i.onSuccess(c.getTrackId()),WC.info("create screen video track success","video:",c.getTrackId()),c;const d=new zA(o,void 0,xS(8,"track-scr-a-"),!1,!0);return i.onSuccess([c.getTrackId(),d.getTrackId()]),WC.info("create screen video track success","video:",c.getTrackId(),"audio:",d.getTrackId()),[c,d]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.CREATE_MIC_AND_CAM_TRACKS,options:[e,t]}),n=$A(t),r=eb(e),s=xS(8,"track-mic-"),o=xS(8,"track-cam-");let a=null,c=null;WC.info("start create camera video track(".concat(o,") and microphone audio track(").concat(s,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await CA({audio:r,video:n},"".concat(s,"-").concat(o));a=e.getAudioTracks()[0],c=e.getVideoTracks()[0]}catch(e){throw i.onError(e),e}if(!a||!c){const e=new Vg(xg.UNEXPECTED_ERROR,"can not find tracks in media stream");return i.onError(e),e.throw(WC)}t.optimizationMode&&Rb(o,c,t,vy(t.encoderConfig));const d=new XA(a,e,r,s),l=new gb(c,t,n,t.scalabiltyMode?yy(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,o);return i.onSuccess([d.getTrackId(),l.getTrackId()]),WC.info("create camera video track(".concat(o,") and microphone audio track(").concat(s,") success")),[d,l]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=eb(e),n=xS(8,"track-mic-");let r=null;WC.info("start create microphone audio track with config",JSON.stringify(e),"trackId",n);try{r=(await CA({audio:i},n)).getAudioTracks()[0]||null}catch(e){throw t.onError(e),e}if(!r){const e=new Vg(xg.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw(WC)}const s=new XA(r,e,i,n);return t.onSuccess(s.getTrackId()),WC.info("create microphone audio track success, trackId:",n),s},createCustomAudioTrack:function(e){const t=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new zA(e.mediaStreamTrack,e.encoderConfig?by(e.encoderConfig):{},xS(8,"track-cus-"),!1,!0);return WC.info("create custom audio track success with config",e,"trackId",i.getTrackId()),t.onSuccess(i.getTrackId()),i},createBufferSourceAudioTrack:async function(e){var t;const{cacheOnlineFile:i,encoderConfig:n}=e;let{source:r}=e;const s={source:r instanceof AudioBuffer?"AudioBuffer":r instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":r,cacheOnlineFile:i,encoderConfig:n},o=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.CREATE_BUFFER_AUDIO_TRACK,options:[s]});if(kC("DISABLE_WEBAUDIO"))throw new Vg(xg.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");const a=xS(8,"track-buf-");WC.info("start create buffer source audio track with config",JSON.stringify(s),"trackId",a);const c=r;if(!(r instanceof AudioBuffer))try{r=await nb(r,i)}catch(e){return o.onError(e),e.throw(WC)}const d=new tb(r),l=new QA(c,d,n?by(n):{},a);return WC.info("create buffer source audio track success, trackId:",a),o.onSuccess(l.getTrackId()),l},setAppType:function(e){if(WC.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw WC.debug("Invalid appType"),new Mv(xg.INVALID_PARAMS,"invalid app type",e);LC("APP_TYPE",Math.floor(e))},setLogLevel:function(e){WC.setLogLevel(e)},enableLogUpload:function(){kC("USE_NEW_LOG")?LC("UPLOAD_LOG",!0):WC.enableLogUpload()},disableLogUpload:function(){kC("USE_NEW_LOG")?LC("UPLOAD_LOG",!1):WC.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new vP},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof zA||e instanceof Ab)){const e=new Mv(xg.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof zA?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let s=r,o=r;const a=Date.now();return new tg((r=>{const c=setInterval((()=>{const d=e.getVolumeLevel();s=d>s?d:s,o=d<o?d:o;const l=s-o>1e-4,h=Date.now()-a;if(l||h>t){clearInterval(c);const t=l,o={duration:h,deviceLabel:n,maxVolumeLevel:s,result:t};WC.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(o))),i.onSuccess(o),r(t)}}),200)}))},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=iv.reportApiInvoke(null,{tag:oS.TRACER,name:sS.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof fb||e instanceof yb)){const e=new Mv(xg.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof fb?e.getTrackLabel():"remote_track",r=e.getMediaStreamTrack(!0),s=document.createElement("video");s.style.width="1px",s.style.height="1px",s.setAttribute("muted",""),s.muted=!0,s.setAttribute("playsinline",""),s.controls=!1,(Tg()||mg())&&(s.style.opacity="0.01",s.style.position="fixed",s.style.left="0",s.style.top="0",document.body.appendChild(s)),s.srcObject=new MediaStream([r]),s.play();const o=document.createElement("canvas");o.width=160,o.height=120;let a=0,c=0;try{const e=Date.now();a=await function(e,t,i,n){let r,s=0,o=null;return new tg(((a,c)=>{function d(){s>n&&r&&(r(),a(s));const t=i.getContext("2d");if(!t){const e=new Mv(xg.UNEXPECTED_ERROR,"can not get canvas 2d context.");return WC.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,i.width,i.height),l=Math.floor(d.data.length/3);if(o){for(let e=0;e<l;e+=3)if(d.data[e]!==o[e])return s+=1,void(o=d.data);o=d.data}else o=d.data}setTimeout((()=>{r&&(r(),a(s))}),t),r=dA((()=>{d()}),30)}))}(s,t,o,4),c=Date.now()-e}catch(e){throw i.onError(e),e}GM===cg.SAFARI&&(s.pause(),s.remove()),s.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:n,result:d};return WC.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),i.onSuccess(l),d},setArea:HD,audioElementPlayCenter:kA,processExternalMediaAEC:function(e){YM.processExternalMediaAEC(e)},registerExtensions:function(e){e.forEach((e=>{const t=e;t.__registered__=!0,t.logger.hookLog=WC.extLog,t.reporter.hookApiInvoke=iv.extApiInvoke,t.parameters&&Object.keys(t.parameters).forEach((e=>{t.parameters[e]=kC(e)}))}))},ChannelMediaRelayError:Xv,ChannelMediaRelayEvent:Jv,ChannelMediaRelayState:zv,RemoteStreamFallbackType:ky,RemoteStreamType:Ly,ConnectionDisconnectedReason:cS,AudienceLatencyLevelType:aS,AREAS:iI});return Object.defineProperties(QM,{onAudioAutoplayFailed:{get:()=>wA.onAudioAutoplayFailed,set:e=>{wA.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>wA.onAutoplayFailed,set:e=>{wA.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>QM._onSecurityPolicyViolation,set(e){QM._onSecurityPolicyViolation=e,XM(e)}},__CLIENT_LIST__:{get:()=>kC("SHOW_GLOBAL_CLIENT_LIST")?ov:[]}}),AA.on(Jy.CAMERA_DEVICE_CHANGED,(e=>{WC.info("camera device changed",JSON.stringify(e)),QM.onCameraChanged&&QM.onCameraChanged(e),QM.safeEmit(RI.CAMERA_CHANGED,e)})),AA.on(Jy.RECORDING_DEVICE_CHANGED,(e=>{WC.info("microphone device changed",JSON.stringify(e)),QM.onMicrophoneChanged&&QM.onMicrophoneChanged(e),QM.safeEmit(RI.MICROPHONE_CHANGED,e)})),AA.on(Jy.PLAYOUT_DEVICE_CHANGED,(e=>{WC.debug("playout device changed",JSON.stringify(e)),QM.onPlaybackDeviceChanged&&QM.onPlaybackDeviceChanged(e),QM.safeEmit(RI.PLAYBACK_DEVICE_CHANGED,e)})),kA.onAutoplayFailed=()=>{WC.info("detect audio element autoplay failed"),wA.onAudioAutoplayFailed&&wA.onAudioAutoplayFailed()},nA.on("autoplay-failed",(()=>{WC.info("detect webaudio autoplay failed"),wA.onAudioAutoplayFailed&&wA.onAudioAutoplayFailed(),QM.safeEmit(RI.AUTOPLAY_FAILED)})),RS.on(uS.NETWORK_STATE_CHANGE,((e,t)=>{WC.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))})),window&&(window.__ARTC__=QM),QM}();var r=n.exports,s=t({__proto__:null,default:e.getDefaultExportFromCjs(r)},[r]);exports.AgoraRTC_NProduction=s;