@cloudflare/realtimekit 1.5.0-staging.3 → 1.5.0-staging.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/EncryptionManager.cjs.js +1 -1
- package/dist/EncryptionManager.d.ts +1 -0
- package/dist/EncryptionManager.es.js +86 -86
- package/dist/browser.js +13 -13
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +10 -10
- package/dist/index.d.ts +1 -0
- package/dist/index.es.js +3282 -3247
- package/dist/index.es5.js +2787 -2709
- package/dist/index.rn.js +10 -10
- package/dist/ts3.4/dist/EncryptionManager.d.ts +1 -0
- package/dist/ts3.4/dist/index.d.ts +1 -0
- package/package.json +1 -1
package/dist/index.rn.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var ST=Object.defineProperty;var vT=(s,t,e)=>t in s?ST(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var h=(s,t,e)=>(vT(s,typeof t!="symbol"?t+"":t,e),e),Ol=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)};var n=(s,t,e)=>(Ol(s,t,"read from private field"),e?e.call(s):t.get(s)),g=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},m=(s,t,e,r)=>(Ol(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e);var L=(s,t,e)=>(Ol(s,t,"access private method"),e);const nr=require("uuid"),mg=require("bowser"),S=require("@protobuf-ts/runtime"),yT=require("worker-timers"),ET=require("sdp-transform");function fg(s){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const e in s)if(e!=="default"){const r=Object.getOwnPropertyDescriptor(s,e);Object.defineProperty(t,e,r.get?r:{enumerable:!0,get:()=>s[e]})}}return t.default=s,Object.freeze(t)}const Uc=fg(yT),rs=fg(ET);function PT(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}Array.prototype.at||Object.assign(Array.prototype,{at:PT});function bT(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}String.prototype.at||Object.assign(String.prototype,{at:bT});const _T=s=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&s.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,i,a,o,c,d,l;s.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(r=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:r.url,baseURL:(a=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:a.baseURL,method:(c=(o=t==null?void 0:t.reason)==null?void 0:o.config)==null?void 0:c.method,status:(d=t==null?void 0:t.reason)==null?void 0:d.status,statusText:(l=t==null?void 0:t.reason)==null?void 0:l.statusText}},!0)}),window.addEventListener("offline",()=>{s.info("window::offline")}),window.addEventListener("online",()=>{s.info("window::online")}))},co="chrome",Tg="opera",Sg="firefox",vg="iexplorer",yg="safari",Eg="nwjs",Pg="electron",bg="react-native",Bu="unknown",Xc={Chrome:co,Chromium:co,Opera:Tg,Firefox:Sg,"Internet Explorer":vg,Safari:yg};function CT(){const{userAgent:s}=navigator,t={name:Bu,version:void 0};if(s.match(/Chrome/)&&!s.match(/Edge/))if(s.match(/Edg(A?)/)){const e=s.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(e,10)>72&&(t.name=co,t.version=e)}else t.name=co,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function wT(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:Pg,version:t}}return null}function RT(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Eg,version:t}}}function kT(){const s=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let t;if(s||navigator.product==="ReactNative")return s&&s.length>2&&(s[1],t=s[2]),t||(t="unknown"),{name:bg,version:t}}function MT(s){let t;const e=[kT,wT,RT];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in Xc?{name:Xc[r],version:s.getBrowserVersion()}:(t=CT(),t||{name:Bu,version:void 0})}class IT{constructor(){h(this,"_bowser");h(this,"_name");h(this,"_version");h(this,"getDeviceInfo",()=>({isMobile:this.isMobile(),browserName:this._bowser.getBrowserName(),osName:this._bowser.getOSName(),browserVersion:this._bowser.getBrowserVersion(),osVersionName:this._bowser.getOSVersion(),engineName:this._bowser.getEngineName()}))}init(t){let e,r;if(this._bowser=mg.getParser(navigator.userAgent),typeof t=="undefined"){const i=MT(this._bowser);e=i.name,r=i.version}else t.name in Xc?(e=Xc[t.name],r=t.version):(e=Bu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===co}isOpera(){return this._name===Tg}isFirefox(){return this._name===Sg}isIExplorer(){return this._name===vg}isSafari(){return this._name===yg}isNWJS(){return this._name===Eg}isElectron(){return this._name===Pg}isReactNative(){return this._name===bg||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(t){if(this._version)return this._bowser.satisfies(t)}isVersionGreaterThan(t){return this._checkCondition({[this._name]:`>${t}`})}isVersionLessThan(t){return this._checkCondition({[this._name]:`<${t}`})}isVersionEqualTo(t){return this._checkCondition({[this._name]:`~${t}`})}}class AT extends IT{doesVideoMuteByStreamRemove(){return this.isChromiumBased()||this.isWebKitBased()}supportsP2P(){return!this.usesUnifiedPlan()}isChromiumBased(){return this.isChrome()||this.isElectron()||this.isNWJS()||this.isOpera()}isWebKitBased(){return this._bowser.isEngine("webkit")&&typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getUserMedia!="undefined"&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(RTCRtpTransceiver.prototype).indexOf("currentDirection")>-1}isSupported(){return typeof RTCPeerConnection!="undefined"}isUserInteractionRequiredForUnmute(){return this.isFirefox()&&this.isVersionLessThan("68")}supportsVideoMuteOnConnInterrupted(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsBandwidthStatistics(){return!this.isFirefox()&&!this.isWebKitBased()}supportsCodecPreferences(){return this.usesUnifiedPlan()&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(window.RTCRtpTransceiver.prototype).indexOf("setCodecPreferences")>-1&&Object.keys(RTCRtpSender.prototype).indexOf("getCapabilities")>-1&&!this.isWebKitBased()}supportsDeviceChangeEvent(){return navigator.mediaDevices&&typeof navigator.mediaDevices.ondevicechange!="undefined"&&typeof navigator.mediaDevices.addEventListener!="undefined"}supportsLocalCandidateRttStatistics(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsPerformanceObserver(){return typeof window.PerformanceObserver!="undefined"&&PerformanceObserver.supportedEntryTypes.indexOf("longtask")>-1}supportsReceiverStats(){return typeof window.RTCRtpReceiver!="undefined"&&Object.keys(RTCRtpReceiver.prototype).indexOf("getSynchronizationSources")>-1}supportsRTTStatistics(){return!this.isFirefox()}usesPlanB(){return!this.usesUnifiedPlan()}usesSdpMungingForSimulcast(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}usesUnifiedPlan(){return!!(this.isFirefox()||this.isWebKitBased())}usesNewGumFlow(){return!!(this.isChromiumBased()||this.isFirefox()||this.isWebKitBased())}usesAdapter(){return this.usesNewGumFlow()}usesRidsForSimulcast(){return!1}supportsGetDisplayMedia(){return typeof navigator.getDisplayMedia!="undefined"||typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getDisplayMedia!="undefined"}supportsInsertableStreams(){if(!(typeof window.RTCRtpSender!="undefined"&&(window.RTCRtpSender.prototype.createEncodedStreams||window.RTCRtpSender.prototype.createEncodedVideoStreams)))return!1;const t=new ReadableStream;try{return window.postMessage(t,"*",[t]),!0}catch(e){return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const t=navigator.userAgent;if(t.match(/Chrome/))return Number.parseInt(t.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const ge=new AT;var st={},DT={get exports(){return st},set exports(s){st=s}},hn=typeof Reflect=="object"?Reflect:null,bh=hn&&typeof hn.apply=="function"?hn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},$c;hn&&typeof hn.ownKeys=="function"?$c=hn.ownKeys:Object.getOwnPropertySymbols?$c=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:$c=function(t){return Object.getOwnPropertyNames(t)};function OT(s){console&&console.warn&&console.warn(s)}var _g=Number.isNaN||function(t){return t!==t};function re(){re.init.call(this)}DT.exports=re;st.once=xT;re.EventEmitter=re;re.prototype._events=void 0;re.prototype._eventsCount=0;re.prototype._maxListeners=void 0;var _h=10;function cl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(re,"defaultMaxListeners",{enumerable:!0,get:function(){return _h},set:function(s){if(typeof s!="number"||s<0||_g(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");_h=s}});re.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};re.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||_g(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Cg(s){return s._maxListeners===void 0?re.defaultMaxListeners:s._maxListeners}re.prototype.getMaxListeners=function(){return Cg(this)};re.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",a=this._events;if(a!==void 0)i=i&&a.error===void 0;else if(!i)return!1;if(i){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var c=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw c.context=o,c}var d=a[t];if(d===void 0)return!1;if(typeof d=="function")bh(d,this,e);else for(var l=d.length,u=Ig(d,l),r=0;r<l;++r)bh(u[r],this,e);return!0};function wg(s,t,e,r){var i,a,o;if(cl(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=Cg(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,OT(c)}return s}re.prototype.addListener=function(t,e){return wg(this,t,e,!1)};re.prototype.on=re.prototype.addListener;re.prototype.prependListener=function(t,e){return wg(this,t,e,!0)};function NT(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Rg(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=NT.bind(r);return i.listener=e,r.wrapFn=i,i}re.prototype.once=function(t,e){return cl(e),this.on(t,Rg(this,t,e)),this};re.prototype.prependOnceListener=function(t,e){return cl(e),this.prependListener(t,Rg(this,t,e)),this};re.prototype.removeListener=function(t,e){var r,i,a,o,c;if(cl(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(a=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){c=r[o].listener,a=o;break}if(a<0)return this;a===0?r.shift():LT(r,a),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};re.prototype.off=re.prototype.removeListener;re.prototype.removeAllListeners=function(t){var e,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var a=Object.keys(r),o;for(i=0;i<a.length;++i)o=a[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function kg(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?VT(i):Ig(i,i.length)}re.prototype.listeners=function(t){return kg(this,t,!0)};re.prototype.rawListeners=function(t){return kg(this,t,!1)};re.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Mg.call(s,t)};re.prototype.listenerCount=Mg;function Mg(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}re.prototype.eventNames=function(){return this._eventsCount>0?$c(this._events):[]};function Ig(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function LT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function VT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function xT(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}Ag(s,t,a,{once:!0}),t!=="error"&&UT(s,i,{once:!0})})}function UT(s,t,e){typeof s.on=="function"&&Ag(s,"error",t,e)}function Ag(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}var G;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(G||(G={}));var D;(function(s){s.PRECALL_TEST_BEGIN="precall_begin",s.PRECALL_TEST_COMPLETE="precall_end",s.CALL_JOIN_BEGIN="call_join",s.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",s.NET_QUALITY_TEST_END="net_quality_test_end",s.WEBSOCKET_CONNECTED="websocket_connected",s.TRANSPORT_CONNECTED="transport_connected",s.AUDIO_ON="audio_on",s.AUDIO_OFF="audio_off",s.VIDEO_ON="video_on",s.VIDEO_OFF="video_off",s.PARTICIPANT_ROLE="participant_role",s.PING_STAT="ping_stat",s.DISCONNECT="disconnect",s.RECONNECT_ATTEMPT="reconnect_attempt",s.SCREENSHARE_START_REQUESTED="screenshare_start_requested",s.SCREENSHARE_STARTED="screenshare_started",s.SCREENSHARE_STOPPED="screenshare_stopped",s.TAB_CHANGE="tab_change",s.BROWSER_BACKGROUNDED="browser_backgrounded",s.BROWSER_FOREGROUNDED="browser_foregrounded",s.DOMINANT_SPEAKER="dominant_speaker",s.AUDIO_DEVICES_UPDATES="audio_devices_updates",s.VIDEO_DEVICES_UPDATES="video_devices_updates",s.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",s.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",s.SELECTED_CAMERA_UPDATE="selected_camera_update",s.SELECTED_SPEAKER_UPDATE="selected_speaker_update",s.EXPECTED_VIDEO_RESOLUTION="expected_video_resolution",s.EXPECTED_SCREENSHARE_RESOLUTION="expected_screenshare_resolution",s.MEDIA_PERMISSION="media_permission",s.LEGACY_SWITCH="legacy_switch",s.AUDIO_PLAY_FAILED="audio_play_failed",s.VIDEO_PLAY_FAILED="video_play_failed",s.AUDIO_TRACK_MUTED="audio_track_muted",s.VIDEO_TRACK_MUTED="video_track_muted",s.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",s.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",s.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",s.IVS_PLAYER_ERROR="ivs_player_error",s.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",s.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",s.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",s.LIVESTREAM_LATENCY="livestream_latency",s.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",s.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",s.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",s.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(D||(D={}));const $T=new Map([[D.PRECALL_TEST_BEGIN,G.MINOR_EVENT],[D.PRECALL_TEST_COMPLETE,G.MINOR_EVENT],[D.CALL_JOIN_BEGIN,G.MAJOR_EVENT],[D.NET_QUALITY_TEST_BEGIN,G.MINOR_EVENT],[D.NET_QUALITY_TEST_END,G.MINOR_EVENT],[D.WEBSOCKET_CONNECTED,G.MINOR_EVENT],[D.TRANSPORT_CONNECTED,G.MAJOR_EVENT],[D.AUDIO_ON,G.MINOR_EVENT],[D.AUDIO_OFF,G.MINOR_EVENT],[D.VIDEO_ON,G.MINOR_EVENT],[D.VIDEO_OFF,G.MINOR_EVENT],[D.PARTICIPANT_ROLE,G.MINOR_EVENT],[D.PING_STAT,G.MAJOR_EVENT],[D.DISCONNECT,G.MAJOR_EVENT],[D.RECONNECT_ATTEMPT,G.MAJOR_EVENT],[D.SCREENSHARE_START_REQUESTED,G.MINOR_EVENT],[D.SCREENSHARE_STARTED,G.MINOR_EVENT],[D.SCREENSHARE_STOPPED,G.MINOR_EVENT],[D.TAB_CHANGE,G.MINOR_EVENT],[D.BROWSER_BACKGROUNDED,G.MINOR_EVENT],[D.BROWSER_FOREGROUNDED,G.MINOR_EVENT],[D.DOMINANT_SPEAKER,G.MINOR_EVENT],[D.AUDIO_DEVICES_UPDATES,G.MINOR_EVENT],[D.VIDEO_DEVICES_UPDATES,G.MINOR_EVENT],[D.SPEAKER_DEVICES_UPDATES,G.MINOR_EVENT],[D.SELECTED_MICROHPONE_UPDATE,G.MINOR_EVENT],[D.SELECTED_CAMERA_UPDATE,G.MINOR_EVENT],[D.SELECTED_SPEAKER_UPDATE,G.MINOR_EVENT],[D.MEDIA_PERMISSION,G.MINOR_EVENT],[D.LEGACY_SWITCH,G.MINOR_EVENT],[D.AUDIO_PLAY_FAILED,G.MINOR_EVENT],[D.VIDEO_PLAY_FAILED,G.MINOR_EVENT],[D.AUDIO_TRACK_MUTED,G.MINOR_EVENT],[D.VIDEO_TRACK_MUTED,G.MINOR_EVENT],[D.IVS_PLAYER_REBUFFERING,G.MAJOR_EVENT],[D.IVS_PLAYER_AUDIO_BLOCKED,G.MAJOR_EVENT],[D.IVS_PLAYER_PLAYBACK_BLOCKED,G.MAJOR_EVENT],[D.IVS_PLAYER_ERROR,G.MAJOR_EVENT],[D.IVS_PLAYER_RECOVERABLE_ERROR,G.MAJOR_EVENT],[D.IVS_PLAYER_WORKER_ERROR,G.MAJOR_EVENT],[D.IVS_PLAYER_NETWORK_UNAVAILABLE,G.MAJOR_EVENT],[D.LIVESTREAM_LATENCY,G.MAJOR_EVENT],[D.IVS_PLAYER_ANALYTICS_EVENT,G.MINOR_EVENT],[D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,G.MINOR_EVENT],[D.IVS_PLAYER_QUALITY_CHANGED,G.MINOR_EVENT],[D.IVS_PLAYER_INITIALIZED,G.MINOR_EVENT],[D.EXPECTED_VIDEO_RESOLUTION,G.MINOR_EVENT],[D.EXPECTED_SCREENSHARE_RESOLUTION,G.MINOR_EVENT]]);class BT{constructor(){h(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class HT extends st{constructor({logger:e,peerId:r,apiHostnames:i,authToken:a}){super();h(this,"logger");h(this,"peerId");h(this,"eventStore");h(this,"apiEndpoint");h(this,"authToken");this.logger=e,this.peerId=r,this.authToken=a,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new BT}async sendEventsChunkToServer(e){const r={payload:e,peerId:this.peerId},i=new AbortController,a=setTimeout(()=>i.abort(),3e3);try{return await fetch(this.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.authToken}`},body:JSON.stringify(r),signal:i.signal}),!0}catch(o){return this.logger.error("callStats::sendEventsChunkToServer::catch",{peerId:this.peerId,endpoint:this.apiEndpoint,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0}),!1}finally{clearTimeout(a)}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),$T.get(e.event)===G.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();if((r=e==null?void 0:e.entries)!=null&&r.length){const i=await this.sendEventsChunkToServer(e);return i||e.entries.forEach(a=>{this.eventStore.add(a)}),i}return!1}}var Ch;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(Ch||(Ch={}));const Dg={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var $t;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})($t||($t={}));var wh;(function(s){s[s.INIT=0]="INIT",s[s.ACCEPTED=1]="ACCEPTED",s[s.DENIED=2]="DENIED",s[s.SYS_DENIED=3]="SYS_DENIED",s[s.FAILED=4]="FAILED",s[s.NOTFOUND=5]="NOTFOUND",s[s.NOT_APPLICABLE=6]="NOT_APPLICABLE"})(wh||(wh={}));function Hr(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Zc({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function ed({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Og=240,Ng=720,Lg=8,Vg=3,dl=10,ll=.02,ul=.03;function sr({stat:s,weight:t,rangeMin:e,rangeMax:r,rangeRankingDirection:i}){return s==null?t:e===r?i==="UP"?s<=e?t:0:s>=r?t:0:i==="UP"?(1-Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e))*t:i==="DOWN"?Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e)*t:t}function xg({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:i}){const a=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*i);return Math.round((a+Number.EPSILON)*100)/100}function Ug({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function $g({packetsLost:s,packetsSent:t,jitter:e}){const i=sr({stat:Ug({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:dl,rangeRankingDirection:"UP"}),o=sr({stat:e,weight:.3,rangeMin:ll,rangeMax:ul,rangeRankingDirection:"UP"});return i+o}function FT({frameWidth:s,isScreenShare:t}){return s<(t?Ng:Og)}function qT({framesPerSecond:s,isScreenShare:t}){return s<(t?Vg:Lg)}function jT({framesEncoded:s}){return s===0}function Bg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:a,framesEncoded:o}){const c=sr({stat:Ug({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:dl,rangeRankingDirection:"UP"}),d=sr({stat:i,weight:1,rangeMin:ll,rangeMax:ul,rangeRankingDirection:"UP"}),l=FT({frameWidth:s,isScreenShare:a}),u=qT({framesPerSecond:t,isScreenShare:a}),p=jT({framesEncoded:o,isScreenShare:a});return xg({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}function Hg({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function Fg({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const a=sr({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=sr({stat:Hg({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:dl,rangeRankingDirection:"UP"}),l=sr({stat:r,weight:.3,rangeMin:ll,rangeMax:ul,rangeRankingDirection:"UP"});return a+c+l}function GT({framesDecoded:s}){return s===0}function WT({framesPerSecond:s,isScreenShare:t}){return s<(t?Vg:Lg)}function JT({frameWidth:s,isScreenShare:t}){return s<(t?Ng:Og)}function qg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:a,framesDecoded:o}){const c=sr({stat:Hg({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:dl,rangeRankingDirection:"UP"}),d=sr({stat:i,weight:1,rangeMin:ll,rangeMax:ul,rangeRankingDirection:"UP"}),l=JT({frameWidth:s,isScreenShare:a}),u=WT({framesPerSecond:t,isScreenShare:a}),p=GT({framesDecoded:o,isScreenShare:a});return xg({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}class ar{constructor(t){h(this,"pc1");h(this,"pc2");h(this,"constrainVideoBitrateKbps");h(this,"constrainOfferToRemoveVideoFec",!1);h(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=ar.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(t){const e="candidate:",r=t.indexOf(e)+e.length,i=t.substr(r).split(" ");return{type:i[7],protocol:i[2],address:i[4]}}static isNotHostCandidate(t){return t.type!=="host"}static isHost(t){return t.type==="host"}static isRelay(t){return t.type==="relay"}static isReflexive(t){return t.type==="srflx"}static noFilter(t){return!0}onIceCandidate(t,e){if(e.candidate){const r=ar.parseCandidate(e.candidate.candidate);this.iceCandidateFilter(r)&&t.addIceCandidate(e.candidate)}}setIceCandidateFilter(t){this.iceCandidateFilter=t}constrainVideoBitrate(t){this.constrainVideoBitrateKbps=t}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(t){this.constrainOfferToRemoveVideoFec&&(t.sdp=t.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
|
|
1
|
+
"use strict";var vT=Object.defineProperty;var yT=(s,t,e)=>t in s?vT(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var h=(s,t,e)=>(yT(s,typeof t!="symbol"?t+"":t,e),e),Ol=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)};var n=(s,t,e)=>(Ol(s,t,"read from private field"),e?e.call(s):t.get(s)),g=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},m=(s,t,e,r)=>(Ol(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e);var L=(s,t,e)=>(Ol(s,t,"access private method"),e);const nr=require("uuid"),fg=require("bowser"),S=require("@protobuf-ts/runtime"),ET=require("worker-timers"),PT=require("sdp-transform");function Tg(s){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const e in s)if(e!=="default"){const r=Object.getOwnPropertyDescriptor(s,e);Object.defineProperty(t,e,r.get?r:{enumerable:!0,get:()=>s[e]})}}return t.default=s,Object.freeze(t)}const Uc=Tg(ET),rs=Tg(PT);function bT(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}Array.prototype.at||Object.assign(Array.prototype,{at:bT});function _T(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}String.prototype.at||Object.assign(String.prototype,{at:_T});const wT=s=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&s.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,i,a,o,c,d,l;s.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(r=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:r.url,baseURL:(a=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:a.baseURL,method:(c=(o=t==null?void 0:t.reason)==null?void 0:o.config)==null?void 0:c.method,status:(d=t==null?void 0:t.reason)==null?void 0:d.status,statusText:(l=t==null?void 0:t.reason)==null?void 0:l.statusText}},!0)}),window.addEventListener("offline",()=>{s.info("window::offline")}),window.addEventListener("online",()=>{s.info("window::online")}))},co="chrome",Sg="opera",vg="firefox",yg="iexplorer",Eg="safari",Pg="nwjs",bg="electron",_g="react-native",Hu="unknown",Xc={Chrome:co,Chromium:co,Opera:Sg,Firefox:vg,"Internet Explorer":yg,Safari:Eg};function CT(){const{userAgent:s}=navigator,t={name:Hu,version:void 0};if(s.match(/Chrome/)&&!s.match(/Edge/))if(s.match(/Edg(A?)/)){const e=s.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(e,10)>72&&(t.name=co,t.version=e)}else t.name=co,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function RT(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:bg,version:t}}return null}function kT(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Pg,version:t}}}function MT(){const s=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let t;if(s||navigator.product==="ReactNative")return s&&s.length>2&&(s[1],t=s[2]),t||(t="unknown"),{name:_g,version:t}}function IT(s){let t;const e=[MT,RT,kT];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in Xc?{name:Xc[r],version:s.getBrowserVersion()}:(t=CT(),t||{name:Hu,version:void 0})}class AT{constructor(){h(this,"_bowser");h(this,"_name");h(this,"_version");h(this,"getDeviceInfo",()=>({isMobile:this.isMobile(),browserName:this._bowser.getBrowserName(),osName:this._bowser.getOSName(),browserVersion:this._bowser.getBrowserVersion(),osVersionName:this._bowser.getOSVersion(),engineName:this._bowser.getEngineName()}))}init(t){let e,r;if(this._bowser=fg.getParser(navigator.userAgent),typeof t=="undefined"){const i=IT(this._bowser);e=i.name,r=i.version}else t.name in Xc?(e=Xc[t.name],r=t.version):(e=Hu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===co}isOpera(){return this._name===Sg}isFirefox(){return this._name===vg}isIExplorer(){return this._name===yg}isSafari(){return this._name===Eg}isNWJS(){return this._name===Pg}isElectron(){return this._name===bg}isReactNative(){return this._name===_g||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(t){if(this._version)return this._bowser.satisfies(t)}isVersionGreaterThan(t){return this._checkCondition({[this._name]:`>${t}`})}isVersionLessThan(t){return this._checkCondition({[this._name]:`<${t}`})}isVersionEqualTo(t){return this._checkCondition({[this._name]:`~${t}`})}}class DT extends AT{doesVideoMuteByStreamRemove(){return this.isChromiumBased()||this.isWebKitBased()}supportsP2P(){return!this.usesUnifiedPlan()}isChromiumBased(){return this.isChrome()||this.isElectron()||this.isNWJS()||this.isOpera()}isWebKitBased(){return this._bowser.isEngine("webkit")&&typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getUserMedia!="undefined"&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(RTCRtpTransceiver.prototype).indexOf("currentDirection")>-1}isSupported(){return typeof RTCPeerConnection!="undefined"}isUserInteractionRequiredForUnmute(){return this.isFirefox()&&this.isVersionLessThan("68")}supportsVideoMuteOnConnInterrupted(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsBandwidthStatistics(){return!this.isFirefox()&&!this.isWebKitBased()}supportsCodecPreferences(){return this.usesUnifiedPlan()&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(window.RTCRtpTransceiver.prototype).indexOf("setCodecPreferences")>-1&&Object.keys(RTCRtpSender.prototype).indexOf("getCapabilities")>-1&&!this.isWebKitBased()}supportsDeviceChangeEvent(){return navigator.mediaDevices&&typeof navigator.mediaDevices.ondevicechange!="undefined"&&typeof navigator.mediaDevices.addEventListener!="undefined"}supportsLocalCandidateRttStatistics(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsPerformanceObserver(){return typeof window.PerformanceObserver!="undefined"&&PerformanceObserver.supportedEntryTypes.indexOf("longtask")>-1}supportsReceiverStats(){return typeof window.RTCRtpReceiver!="undefined"&&Object.keys(RTCRtpReceiver.prototype).indexOf("getSynchronizationSources")>-1}supportsRTTStatistics(){return!this.isFirefox()}usesPlanB(){return!this.usesUnifiedPlan()}usesSdpMungingForSimulcast(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}usesUnifiedPlan(){return!!(this.isFirefox()||this.isWebKitBased())}usesNewGumFlow(){return!!(this.isChromiumBased()||this.isFirefox()||this.isWebKitBased())}usesAdapter(){return this.usesNewGumFlow()}usesRidsForSimulcast(){return!1}supportsGetDisplayMedia(){return typeof navigator.getDisplayMedia!="undefined"||typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getDisplayMedia!="undefined"}supportsInsertableStreams(){if(!(typeof window.RTCRtpSender!="undefined"&&(window.RTCRtpSender.prototype.createEncodedStreams||window.RTCRtpSender.prototype.createEncodedVideoStreams)))return!1;const t=new ReadableStream;try{return window.postMessage(t,"*",[t]),!0}catch(e){return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const t=navigator.userAgent;if(t.match(/Chrome/))return Number.parseInt(t.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const ge=new DT;var st={},OT={get exports(){return st},set exports(s){st=s}},hn=typeof Reflect=="object"?Reflect:null,_h=hn&&typeof hn.apply=="function"?hn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},$c;hn&&typeof hn.ownKeys=="function"?$c=hn.ownKeys:Object.getOwnPropertySymbols?$c=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:$c=function(t){return Object.getOwnPropertyNames(t)};function NT(s){console&&console.warn&&console.warn(s)}var wg=Number.isNaN||function(t){return t!==t};function re(){re.init.call(this)}OT.exports=re;st.once=UT;re.EventEmitter=re;re.prototype._events=void 0;re.prototype._eventsCount=0;re.prototype._maxListeners=void 0;var wh=10;function cl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(re,"defaultMaxListeners",{enumerable:!0,get:function(){return wh},set:function(s){if(typeof s!="number"||s<0||wg(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");wh=s}});re.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};re.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||wg(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Cg(s){return s._maxListeners===void 0?re.defaultMaxListeners:s._maxListeners}re.prototype.getMaxListeners=function(){return Cg(this)};re.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",a=this._events;if(a!==void 0)i=i&&a.error===void 0;else if(!i)return!1;if(i){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var c=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw c.context=o,c}var d=a[t];if(d===void 0)return!1;if(typeof d=="function")_h(d,this,e);else for(var l=d.length,u=Ag(d,l),r=0;r<l;++r)_h(u[r],this,e);return!0};function Rg(s,t,e,r){var i,a,o;if(cl(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=Cg(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,NT(c)}return s}re.prototype.addListener=function(t,e){return Rg(this,t,e,!1)};re.prototype.on=re.prototype.addListener;re.prototype.prependListener=function(t,e){return Rg(this,t,e,!0)};function LT(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function kg(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=LT.bind(r);return i.listener=e,r.wrapFn=i,i}re.prototype.once=function(t,e){return cl(e),this.on(t,kg(this,t,e)),this};re.prototype.prependOnceListener=function(t,e){return cl(e),this.prependListener(t,kg(this,t,e)),this};re.prototype.removeListener=function(t,e){var r,i,a,o,c;if(cl(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(a=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){c=r[o].listener,a=o;break}if(a<0)return this;a===0?r.shift():VT(r,a),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};re.prototype.off=re.prototype.removeListener;re.prototype.removeAllListeners=function(t){var e,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var a=Object.keys(r),o;for(i=0;i<a.length;++i)o=a[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function Mg(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?xT(i):Ag(i,i.length)}re.prototype.listeners=function(t){return Mg(this,t,!0)};re.prototype.rawListeners=function(t){return Mg(this,t,!1)};re.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Ig.call(s,t)};re.prototype.listenerCount=Ig;function Ig(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}re.prototype.eventNames=function(){return this._eventsCount>0?$c(this._events):[]};function Ag(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function VT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function xT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function UT(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}Dg(s,t,a,{once:!0}),t!=="error"&&$T(s,i,{once:!0})})}function $T(s,t,e){typeof s.on=="function"&&Dg(s,"error",t,e)}function Dg(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}var G;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(G||(G={}));var D;(function(s){s.PRECALL_TEST_BEGIN="precall_begin",s.PRECALL_TEST_COMPLETE="precall_end",s.CALL_JOIN_BEGIN="call_join",s.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",s.NET_QUALITY_TEST_END="net_quality_test_end",s.WEBSOCKET_CONNECTED="websocket_connected",s.TRANSPORT_CONNECTED="transport_connected",s.AUDIO_ON="audio_on",s.AUDIO_OFF="audio_off",s.VIDEO_ON="video_on",s.VIDEO_OFF="video_off",s.PARTICIPANT_ROLE="participant_role",s.PING_STAT="ping_stat",s.DISCONNECT="disconnect",s.RECONNECT_ATTEMPT="reconnect_attempt",s.SCREENSHARE_START_REQUESTED="screenshare_start_requested",s.SCREENSHARE_STARTED="screenshare_started",s.SCREENSHARE_STOPPED="screenshare_stopped",s.TAB_CHANGE="tab_change",s.BROWSER_BACKGROUNDED="browser_backgrounded",s.BROWSER_FOREGROUNDED="browser_foregrounded",s.DOMINANT_SPEAKER="dominant_speaker",s.AUDIO_DEVICES_UPDATES="audio_devices_updates",s.VIDEO_DEVICES_UPDATES="video_devices_updates",s.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",s.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",s.SELECTED_CAMERA_UPDATE="selected_camera_update",s.SELECTED_SPEAKER_UPDATE="selected_speaker_update",s.EXPECTED_VIDEO_RESOLUTION="expected_video_resolution",s.EXPECTED_SCREENSHARE_RESOLUTION="expected_screenshare_resolution",s.MEDIA_PERMISSION="media_permission",s.LEGACY_SWITCH="legacy_switch",s.AUDIO_PLAY_FAILED="audio_play_failed",s.VIDEO_PLAY_FAILED="video_play_failed",s.AUDIO_TRACK_MUTED="audio_track_muted",s.VIDEO_TRACK_MUTED="video_track_muted",s.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",s.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",s.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",s.IVS_PLAYER_ERROR="ivs_player_error",s.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",s.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",s.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",s.LIVESTREAM_LATENCY="livestream_latency",s.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",s.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",s.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",s.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(D||(D={}));const BT=new Map([[D.PRECALL_TEST_BEGIN,G.MINOR_EVENT],[D.PRECALL_TEST_COMPLETE,G.MINOR_EVENT],[D.CALL_JOIN_BEGIN,G.MAJOR_EVENT],[D.NET_QUALITY_TEST_BEGIN,G.MINOR_EVENT],[D.NET_QUALITY_TEST_END,G.MINOR_EVENT],[D.WEBSOCKET_CONNECTED,G.MINOR_EVENT],[D.TRANSPORT_CONNECTED,G.MAJOR_EVENT],[D.AUDIO_ON,G.MINOR_EVENT],[D.AUDIO_OFF,G.MINOR_EVENT],[D.VIDEO_ON,G.MINOR_EVENT],[D.VIDEO_OFF,G.MINOR_EVENT],[D.PARTICIPANT_ROLE,G.MINOR_EVENT],[D.PING_STAT,G.MAJOR_EVENT],[D.DISCONNECT,G.MAJOR_EVENT],[D.RECONNECT_ATTEMPT,G.MAJOR_EVENT],[D.SCREENSHARE_START_REQUESTED,G.MINOR_EVENT],[D.SCREENSHARE_STARTED,G.MINOR_EVENT],[D.SCREENSHARE_STOPPED,G.MINOR_EVENT],[D.TAB_CHANGE,G.MINOR_EVENT],[D.BROWSER_BACKGROUNDED,G.MINOR_EVENT],[D.BROWSER_FOREGROUNDED,G.MINOR_EVENT],[D.DOMINANT_SPEAKER,G.MINOR_EVENT],[D.AUDIO_DEVICES_UPDATES,G.MINOR_EVENT],[D.VIDEO_DEVICES_UPDATES,G.MINOR_EVENT],[D.SPEAKER_DEVICES_UPDATES,G.MINOR_EVENT],[D.SELECTED_MICROHPONE_UPDATE,G.MINOR_EVENT],[D.SELECTED_CAMERA_UPDATE,G.MINOR_EVENT],[D.SELECTED_SPEAKER_UPDATE,G.MINOR_EVENT],[D.MEDIA_PERMISSION,G.MINOR_EVENT],[D.LEGACY_SWITCH,G.MINOR_EVENT],[D.AUDIO_PLAY_FAILED,G.MINOR_EVENT],[D.VIDEO_PLAY_FAILED,G.MINOR_EVENT],[D.AUDIO_TRACK_MUTED,G.MINOR_EVENT],[D.VIDEO_TRACK_MUTED,G.MINOR_EVENT],[D.IVS_PLAYER_REBUFFERING,G.MAJOR_EVENT],[D.IVS_PLAYER_AUDIO_BLOCKED,G.MAJOR_EVENT],[D.IVS_PLAYER_PLAYBACK_BLOCKED,G.MAJOR_EVENT],[D.IVS_PLAYER_ERROR,G.MAJOR_EVENT],[D.IVS_PLAYER_RECOVERABLE_ERROR,G.MAJOR_EVENT],[D.IVS_PLAYER_WORKER_ERROR,G.MAJOR_EVENT],[D.IVS_PLAYER_NETWORK_UNAVAILABLE,G.MAJOR_EVENT],[D.LIVESTREAM_LATENCY,G.MAJOR_EVENT],[D.IVS_PLAYER_ANALYTICS_EVENT,G.MINOR_EVENT],[D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,G.MINOR_EVENT],[D.IVS_PLAYER_QUALITY_CHANGED,G.MINOR_EVENT],[D.IVS_PLAYER_INITIALIZED,G.MINOR_EVENT],[D.EXPECTED_VIDEO_RESOLUTION,G.MINOR_EVENT],[D.EXPECTED_SCREENSHARE_RESOLUTION,G.MINOR_EVENT]]);class HT{constructor(){h(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class FT extends st{constructor({logger:e,peerId:r,apiHostnames:i,authToken:a}){super();h(this,"logger");h(this,"peerId");h(this,"eventStore");h(this,"apiEndpoint");h(this,"authToken");this.logger=e,this.peerId=r,this.authToken=a,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new HT}async sendEventsChunkToServer(e){const r={payload:e,peerId:this.peerId},i=new AbortController,a=setTimeout(()=>i.abort(),3e3);try{return await fetch(this.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.authToken}`},body:JSON.stringify(r),signal:i.signal}),!0}catch(o){return this.logger.error("callStats::sendEventsChunkToServer::catch",{peerId:this.peerId,endpoint:this.apiEndpoint,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0}),!1}finally{clearTimeout(a)}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),BT.get(e.event)===G.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();if((r=e==null?void 0:e.entries)!=null&&r.length){const i=await this.sendEventsChunkToServer(e);return i||e.entries.forEach(a=>{this.eventStore.add(a)}),i}return!1}}var Ch;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(Ch||(Ch={}));const Og={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var $t;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})($t||($t={}));var Rh;(function(s){s[s.INIT=0]="INIT",s[s.ACCEPTED=1]="ACCEPTED",s[s.DENIED=2]="DENIED",s[s.SYS_DENIED=3]="SYS_DENIED",s[s.FAILED=4]="FAILED",s[s.NOTFOUND=5]="NOTFOUND",s[s.NOT_APPLICABLE=6]="NOT_APPLICABLE"})(Rh||(Rh={}));function Fr(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Zc({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function ed({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Ng=240,Lg=720,Vg=8,xg=3,dl=10,ll=.02,ul=.03;function sr({stat:s,weight:t,rangeMin:e,rangeMax:r,rangeRankingDirection:i}){return s==null?t:e===r?i==="UP"?s<=e?t:0:s>=r?t:0:i==="UP"?(1-Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e))*t:i==="DOWN"?Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e)*t:t}function Ug({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:i}){const a=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*i);return Math.round((a+Number.EPSILON)*100)/100}function $g({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Bg({packetsLost:s,packetsSent:t,jitter:e}){const i=sr({stat:$g({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:dl,rangeRankingDirection:"UP"}),o=sr({stat:e,weight:.3,rangeMin:ll,rangeMax:ul,rangeRankingDirection:"UP"});return i+o}function qT({frameWidth:s,isScreenShare:t}){return s<(t?Lg:Ng)}function jT({framesPerSecond:s,isScreenShare:t}){return s<(t?xg:Vg)}function GT({framesEncoded:s}){return s===0}function Hg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:a,framesEncoded:o}){const c=sr({stat:$g({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:dl,rangeRankingDirection:"UP"}),d=sr({stat:i,weight:1,rangeMin:ll,rangeMax:ul,rangeRankingDirection:"UP"}),l=qT({frameWidth:s,isScreenShare:a}),u=jT({framesPerSecond:t,isScreenShare:a}),p=GT({framesEncoded:o,isScreenShare:a});return Ug({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}function Fg({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function qg({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const a=sr({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=sr({stat:Fg({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:dl,rangeRankingDirection:"UP"}),l=sr({stat:r,weight:.3,rangeMin:ll,rangeMax:ul,rangeRankingDirection:"UP"});return a+c+l}function WT({framesDecoded:s}){return s===0}function JT({framesPerSecond:s,isScreenShare:t}){return s<(t?xg:Vg)}function KT({frameWidth:s,isScreenShare:t}){return s<(t?Lg:Ng)}function jg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:a,framesDecoded:o}){const c=sr({stat:Fg({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:dl,rangeRankingDirection:"UP"}),d=sr({stat:i,weight:1,rangeMin:ll,rangeMax:ul,rangeRankingDirection:"UP"}),l=KT({frameWidth:s,isScreenShare:a}),u=JT({framesPerSecond:t,isScreenShare:a}),p=WT({framesDecoded:o,isScreenShare:a});return Ug({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}class ar{constructor(t){h(this,"pc1");h(this,"pc2");h(this,"constrainVideoBitrateKbps");h(this,"constrainOfferToRemoveVideoFec",!1);h(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=ar.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(t){const e="candidate:",r=t.indexOf(e)+e.length,i=t.substr(r).split(" ");return{type:i[7],protocol:i[2],address:i[4]}}static isNotHostCandidate(t){return t.type!=="host"}static isHost(t){return t.type==="host"}static isRelay(t){return t.type==="relay"}static isReflexive(t){return t.type==="srflx"}static noFilter(t){return!0}onIceCandidate(t,e){if(e.candidate){const r=ar.parseCandidate(e.candidate.candidate);this.iceCandidateFilter(r)&&t.addIceCandidate(e.candidate)}}setIceCandidateFilter(t){this.iceCandidateFilter=t}constrainVideoBitrate(t){this.constrainVideoBitrateKbps=t}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(t){this.constrainOfferToRemoveVideoFec&&(t.sdp=t.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
|
|
2
2
|
`),t.sdp=t.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:98 rtx\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=fmtp:98 apt=116\r\n/g,"")),this.pc1.setLocalDescription(t),this.pc2.setRemoteDescription(t),this.pc2.createAnswer().then(this.gotAnswer.bind(this),this.reportFatal.bind(this))}gotAnswer(t){this.constrainVideoBitrateKbps&&(t.sdp=t.sdp.replace(/a=mid:video\r\n/g,`a=mid:video\r
|
|
3
3
|
b=AS:${this.constrainVideoBitrateKbps}\r
|
|
4
|
-
`)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,i;if(t.forEach(a=>{a.type==="candidate-pair"&&a.nominated===!0&&a.bytesSent>0&&(r=a)}),e.forEach(a=>{a.type==="candidate-pair"&&a.nominated===!0&&a.bytesReceived>0&&(i=a)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const a=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:a,backendRTT:a}}catch(a){return}}close(){this.pc1.close(),this.pc2.close()}}class jg extends st{constructor(e){super();h(this,"call");h(this,"timeOut");this.call=new ar(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const KT=8,zT=1/1e3;class YT extends jg{constructor(e){super(e);h(this,"senderChannel");h(this,"recieveChannel");h(this,"startTime");h(this,"lastBitrateMeasureTime");h(this,"sentPayloadBytes",0);h(this,"recievedPayloadBytes",0);h(this,"lastReceivedPayloadBytes",0);h(this,"stopSending",!1);h(this,"testProgress",0);h(this,"samplePacket","");h(this,"finalBitrateSum",0);h(this,"bitRateSampels",0);h(this,"maxNumberOfPacketsToSend",0);h(this,"bytesToKeepBuffered",0);h(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(ar.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<1024*256;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(a){}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,i=r.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const o=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*KT/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const a=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(a*zT)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:i})=>super.testComplete({RTT:r,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Hu extends jg{constructor(e,r=ar.noFilter){super(e);h(this,"ch1");h(this,"ch2");this.call.setIceCandidateFilter(r);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class QT extends Hu{constructor(t){super(t,ar.isHost)}}class XT extends Hu{constructor(t){super(t,ar.isRelay)}}class ZT extends Hu{constructor(t){super(t,ar.isReflexive)}}class eS{constructor(){h(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,a,o;if(!this.ipInformation){try{const c=`https://${e.location}`,l=await(await fetch(c)).json();if(((i=l.loc)==null?void 0:i.length)>5)return this.ipInformation=l,(a=this.ipInformation)!=null&&a.ip&&(this.ipInformation.ip=Hr(this.ipInformation.ip)),l;throw Error("Insufficient data")}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using location service",{error:c})}try{const c=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await c.json(),(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=Hr(this.ipInformation.ip))}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:c})}}return this.ipInformation}resetCache(){this.ipInformation=null}}const Gg=new eS,Rh=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function kh(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class Wg{constructor(){h(this,"transport");h(this,"candidatePair");h(this,"outboundVideoRtp",new Map);h(this,"inboundVideoRtp",new Map);h(this,"outboundAudioRtp",new Map);h(this,"inboundAudioRtp",new Map);h(this,"remoteInboundRtp",new Map);h(this,"producerStreamMap",new Map);h(this,"consumerStreamMap",new Map);h(this,"staleProducerStreamMap",!1);h(this,"staleConsumerStreamMap",!1)}}class Jg extends st{constructor(){super();h(this,"observer");h(this,"outboundProducerMap",new Map);h(this,"inboundConsumerMap",new Map);h(this,"consumerPeerIdMap",new Map);h(this,"pausedConsumerMap",new Map);h(this,"pausedProducerMap",new Map);h(this,"overallProducingTransportsStatsMap",{});h(this,"overallConsumingTransportsStatsMap",{});h(this,"overallConsumersStatsMap",{});h(this,"overallProducersStatsMap",{});h(this,"videoProducerToStatsMap",new Map);h(this,"audioProducerToStatsMap",new Map);h(this,"videoConsumerToStatsMap",new Map);h(this,"audioConsumerToStatsMap",new Map);h(this,"consumerIdsWithFreezedVideo",new Set);h(this,"consumerIdsWithFreezedAudio",new Set);h(this,"producerIdsWithFreezedVideo",new Set);h(this,"producerIdsWithFreezedAudio",new Set);h(this,"freezedProducingTransportIds",new Set);h(this,"freezedConsumingTransportIds",new Set);h(this,"screenShareProducers",new Set);h(this,"screenShareConsumers",new Set);h(this,"ipDetails");h(this,"callStatsInstance");this.observer=new st}async registerProducer(e){await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,i){var o,c;const a=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,i){var o,c;const a=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,i){var o;const a=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,i){var o;const a=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,i){var u;const a=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=a,l=o||c||d;r.totalPacketsSent===i.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=i.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,i){var c,d;const o=!!Array.from(((d=(c=this==null?void 0:this.callStatsInstance)==null?void 0:c.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((l,u)=>l||u.audio||u.video||u.screen,!1);r.totalPacketsReceived===i.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=i.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const i=await e.getStats(),a=r?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"outbound-rtp":{this.outboundProducerMap.set(o.id,e.id);break}}return a}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),a=r?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"inbound-rtp":{this.inboundConsumerMap.set(o.id,e.id);break}}return a}deregisterProducer(e){this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(i=>{const a=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return a&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,a=void 0,o=void 0){var b,_,M,A,x,N,$,K,Z,Ue,es,zr,ts;const c=e,d=new Wg,l=r.length?new Set(r):void 0,u=[],p=[],f=[],T=new Map,E=new Map;for(const k of c.values()){if(l){if(l.size===0)break;if(l.has(k.type))i&&l.delete(k.type);else continue}switch(k.type){case"local-candidate":{u.push(this.getIceCandidateStats(k));break}case"remote-candidate":{p.push(this.getIceCandidateStats(k));break}case"candidate-pair":{const{nominated:v}=k,{selected:P}=k,U=k,me={nominated:v!=null?v:P,currentRoundTripTime:U.currentRoundTripTime,totalRoundTripTime:U.totalRoundTripTime,bytesReceived:U.bytesReceived,bytesSent:U.bytesSent,availableOutgoingBitrate:U.availableOutgoingBitrate,availableIncomingBitrate:U.availableIncomingBitrate,lastPacketReceivedTimestamp:U.lastPacketReceivedTimestamp,lastPacketSentTimestamp:U.lastPacketSentTimestamp,localCandidateId:U.localCandidateId,remoteCandidateId:U.remoteCandidateId,bytesDiscardedOnSend:U.bytesDiscardedOnSend,packetsSent:U.packetsSent,packetsReceived:U.packetsReceived,packetsDiscardedOnSend:U.packetsDiscardedOnSend};f.push(me),(k.nominated===!0||k.selected===!0)&&(d.candidatePair=me);break}case"transport":{const v=k;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:v.bytesReceived,bytesSent:v.bytesSent,packetsSent:v.packetsSent,packetsReceived:v.packetsReceived,dtlsCipher:v.dtlsCipher,dtlsState:v.dtlsState,iceRole:v.iceRole};if(d.transport=P,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,P)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,P)}}break}case"remote-inbound-rtp":{const v=k,P={jitter:v.jitter,fractionLost:v.fractionLost,roundTripTime:v.roundTripTime,roundTripTimeMeasurements:v.roundTripTimeMeasurements,totalRoundTripTime:v.totalRoundTripTime,packetsLost:v.packetsLost};d.remoteInboundRtp.set(v.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(k.id))break;const v=k,P=a||this.outboundProducerMap.get(k.id),U=this.pausedProducerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const me=this.overallProducersStatsMap[P];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.outboundProducerMap.has(k.id)){d.staleProducerStreamMap=!0;break}const we=this.callStatsInstance.producers.get(P);if(((b=we==null?void 0:we.track)==null?void 0:b.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const O={bytesSent:v.bytesSent,packetsSent:v.packetsSent,nackCount:v.nackCount,ssrc:v.ssrc,mid:v.mid,active:v.active,codecId:v.codecId,headerBytesSent:v.headerBytesSent||0,totalPacketSendDelay:v.totalPacketSendDelay||0};if(v.mediaType==="video"||v.kind==="video"){const w=v,De={frameHeight:w.frameHeight,frameWidth:w.frameWidth,framesEncoded:w.framesEncoded,framesDropped:w.framesDropped,framesPerSecond:w.framesPerSecond,framesSent:w.framesSent,keyFramesEncoded:w.keyFramesEncoded,firCount:w.firCount,encoderImplementation:w.encoderImplementation,hugeFramesSent:w.hugeFramesSent,pliCount:w.pliCount,qpSum:w.qpSum,qualityLimitationDurations:w.qualityLimitationDurations,qualityLimitationReason:w.qualityLimitationReason,qualityLimitationResolutionChanges:w.qualityLimitationResolutionChanges,totalEncodeTime:w.targetBitrate,totalPacketSendDelay:w.totalPacketSendDelay,retransmittedBytesSent:w.retransmittedBytesSent,retransmittedPacketsSent:w.retransmittedPacketsSent,scalabilityMode:w.scalabilityMode,powerEfficientEncoder:w.powerEfficientEncoder,...O};d.outboundVideoRtp.set(k.id,De),d.producerStreamMap.get(P).outboundVideoRtpId.push(k.id),this.processOutboundProducerVideoStats(P,me,De)}else if(v.mediaType==="audio"||v.kind==="audio"){const w=v,De={retransmittedBytesSent:w.retransmittedBytesSent,retransmittedPacketsSent:w.retransmittedPacketsSent,...O};d.outboundAudioRtp.set(k.id,De),d.producerStreamMap.get(P).outboundAudioRtpId.push(k.id),this.processOutboundProducerAudioStats(P,me,De)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(k.id))break;const v=k,P=a||this.inboundConsumerMap.get(k.id),U=this.pausedConsumerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(v.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const me=this.overallConsumersStatsMap[P];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.inboundConsumerMap.has(k.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const we={bytesReceived:v.bytesReceived,packetsReceived:v.packetsReceived,packetsLost:v.packetsLost>=0?v.packetsLost:0,jitter:v.jitter,nackCount:v.nackCount,jitterBufferDelay:v.jitterBufferDelay,jitterBufferEmittedCount:v.jitterBufferEmittedCount,lastPacketReceivedTimestamp:v.lastPacketReceivedTimestamp,ssrc:v.ssrc,mid:v.mid,codecId:v.codecId,headerBytesReceived:v.headerBytesReceived||0,packetsDiscarded:v.packetsDiscarded||0,jitterBufferMinimumDelay:v.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:v.jitterBufferTargetDelay||0};if(v.mediaType==="video"||v.kind==="video"){const O=v,w={frameHeight:O.frameHeight,frameWidth:O.frameWidth,framesDecoded:O.framesDecoded,framesDropped:O.framesDropped,framesPerSecond:O.framesPerSecond,framesReceived:O.framesReceived,keyFramesDecoded:O.keyFramesDecoded,firCount:O.firCount,decoderImplementation:O.decoderImplementation,pliCount:O.pliCount,totalProcessingDelay:O.totalProcessingDelay,qpSum:O.qpSum||0,totalAssemblyTime:O.totalAssemblyTime||0,totalDecodeTime:O.totalDecodeTime||0,totalFreezesDuration:O.totalFreezesDuration||0,totalInterFrameDelay:O.totalInterFrameDelay||0,totalPausesDuration:O.totalPausesDuration||0,totalSquaredInterFrameDelay:O.totalSquaredInterFrameDelay||0,freezeCount:O.freezeCount||0,pauseCount:O.pauseCount||0,powerEfficientDecoder:O.powerEfficientDecoder,...we};w.score=qg({frameWidth:w.frameWidth||0,framesDecoded:(w.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:w.framesPerSecond||0,packetsLost:(w.packetsLost||0)-(((M=this.videoConsumerToStatsMap.get(P))==null?void 0:M.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((A=this.videoConsumerToStatsMap.get(P))==null?void 0:A.packetsReceived)||0),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(w.score*10).toFixed(),frameWidth:w.frameWidth||0,frameHeight:w.frameHeight||0,framesPerSecond:w.framesPerSecond||0,packetsLostPercentage:ed({packetsLost:(w.packetsLost||0)-(((x=this.videoConsumerToStatsMap.get(P))==null?void 0:x.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0)}),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((w.bytesReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,w),d.inboundVideoRtp.set(k.id,w),d.consumerStreamMap.get(P).inboundVideoRtpId.push(k.id),this.processInboundConsumerVideoStats(P,me,w)}else if(v.mediaType==="audio"||v.kind==="audio"){const O=v,w={audioLevel:O.audioLevel,concealedSamples:O.concealedSamples,concealmentEvents:O.concealmentEvents,totalAudioEnergy:O.totalAudioEnergy,totalSamplesDuration:O.totalSamplesDuration,totalSamplesReceived:O.totalSamplesReceived,fecPacketsDiscarded:O.fecPacketsDiscarded||0,fecPacketsReceived:O.fecPacketsReceived||0,insertedSamplesForDeceleration:O.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:O.removedSamplesForAcceleration||0,silentConcealedSamples:O.silentConcealedSamples||0,playoutId:O.playoutId,...we};w.score=Fg({concealmentEvents:(w.concealmentEvents||0)-(((K=this.audioConsumerToStatsMap.get(P))==null?void 0:K.concealmentEvents)||0),packetsLost:(w.packetsLost||0)-(((Z=this.audioConsumerToStatsMap.get(P))==null?void 0:Z.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((Ue=this.audioConsumerToStatsMap.get(P))==null?void 0:Ue.packetsReceived)||0),jitter:w.jitter||0}),E.set(P,{score:+(w.score*10).toFixed(),packetsLostPercentage:ed({packetsLost:(w.packetsLost||0)-(((es=this.audioConsumerToStatsMap.get(P))==null?void 0:es.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((zr=this.audioConsumerToStatsMap.get(P))==null?void 0:zr.packetsReceived)||0)}),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((w.bytesReceived||0)-(((ts=this.audioConsumerToStatsMap.get(P))==null?void 0:ts.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,w),d.inboundAudioRtp.set(k.id,w),d.consumerStreamMap.get(P).inboundAudioRtpId.push(k.id),this.processInboundConsumerAudioStats(P,me,w)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}}}if(d.producerStreamMap.forEach((k,v)=>{var P,U,me,we,O,w,De,Ds,wa,Ra,ka,Ma,Ia,Aa,Da,Oa,Na,La,Va,xa,Ua,$a,Ba;if(k.outboundVideoRtpId.length>0){const ae=[];k.outboundVideoRtpId.forEach(Dl=>{ae.push(d.outboundVideoRtp.get(Dl))});const Y=this.getWorkingSimulcastVideoStats(ae);Y.score=Bg({frameWidth:Y.frameWidth||0,framesPerSecond:Y.framesPerSecond||0,jitter:((P=Y.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsSent:(Y.packetsSent||0)-(((U=this.videoProducerToStatsMap.get(v))==null?void 0:U.packetsSent)||0),packetsLost:(((me=Y.remoteData)==null?void 0:me.packetsLost)||0)-(((O=(we=this.videoProducerToStatsMap.get(v))==null?void 0:we.remoteData)==null?void 0:O.packetsLost)||0),framesEncoded:(Y.framesEncoded||0)-(((w=this.videoProducerToStatsMap.get(v))==null?void 0:w.framesEncoded)||0)}),T.set(v,{score:+(Y.score*10).toFixed(),frameWidth:Y.frameWidth||0,frameHeight:Y.frameHeight||0,framesPerSecond:Y.framesPerSecond||0,jitter:((De=Y.remoteData)==null?void 0:De.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsLostPercentage:Zc({packetsSent:(Y.packetsSent||0)-(((Ds=this.videoProducerToStatsMap.get(v))==null?void 0:Ds.packetsSent)||0),packetsLost:(((wa=Y.remoteData)==null?void 0:wa.packetsLost)||0)-(((ka=(Ra=this.videoProducerToStatsMap.get(v))==null?void 0:Ra.remoteData)==null?void 0:ka.packetsLost)||0)}),bitrate:((Y.bytesSent||0)-(((Ma=this.videoProducerToStatsMap.get(v))==null?void 0:Ma.bytesSent)||0))*8/7,cpuLimitations:Y.qualityLimitationReason==="cpu",bandwidthLimitations:Y.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(v,Y)}else if(k.outboundAudioRtpId.length>0){const ae=d.outboundAudioRtp.get(k.outboundAudioRtpId[0]);ae.score=$g({packetsSent:(ae.packetsSent||0)-(((Ia=this.audioProducerToStatsMap.get(v))==null?void 0:Ia.packetsSent)||0),packetsLost:(((Aa=ae.remoteData)==null?void 0:Aa.packetsLost)||0)-(((Oa=(Da=this.audioProducerToStatsMap.get(v))==null?void 0:Da.remoteData)==null?void 0:Oa.packetsLost)||0),jitter:((Na=ae.remoteData)==null?void 0:Na.jitter)||0}),T.set(v,{score:+(ae.score*10).toFixed(),bitrate:((ae.bytesSent||0)-(((La=this.audioProducerToStatsMap.get(v))==null?void 0:La.bytesSent)||0))*8/7,packetsLostPercentage:Zc({packetsSent:(ae.packetsSent||0)-(((Va=this.audioProducerToStatsMap.get(v))==null?void 0:Va.packetsSent)||0),packetsLost:(((xa=ae.remoteData)==null?void 0:xa.packetsLost)||0)-((($a=(Ua=this.audioProducerToStatsMap.get(v))==null?void 0:Ua.remoteData)==null?void 0:$a.packetsLost)||0)}),jitter:((Ba=ae.remoteData)==null?void 0:Ba.jitter)||0,isScreenShare:this.screenShareProducers.has(v)}),this.audioProducerToStatsMap.set(v,ae)}}),f.forEach(k=>{const v=u.find(U=>U.id===k.localCandidateId?(k.localCandidateId=U.id,U):null),P=p.find(U=>U.id===k.remoteCandidateId?(k.remoteCandidateId=U.id,U):null);v&&(k.localCandidateType=v.type,k.localCandidateAddress=Hr(v.address),k.localCandidatePort=v.port,k.localCandidateProtocol=v.protocol,k.localCandidateUrl=v.url,k.localCandidateNetworkType=v.networkType,k.localCandidateRelatedAddress=Hr(v.relatedAddress),k.localCandidateRelatedPort=v.relatedPort),P&&(k.remoteCandidateType=P.type,k.remoteCandidateAddress=Hr(P.address),k.remoteCandidatePort=P.port,k.remoteCandidateProtocol=P.protocol,k.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let k=0,v=0;d.remoteInboundRtp.forEach((P,U)=>{P.roundTripTime&&P.roundTripTime>k&&(k=P.roundTripTime,v=P.totalRoundTripTime)}),d.transport.roundTripTime=k,d.transport.totalRoundTripTime=v}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(k){}if(T.size>0)try{this.observer.emit("producer_score",T)}catch(k){}return d}async getProducersReport(e){const r=e.map(i=>this.generateProducerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(i=>this.generateConsumerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,i){const a=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=a,d=this.parseRTCReport(c,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,o);if(!d)return;const l={stats:d.transport,transportId:e.id,consuming:r,producing:i},u=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),p=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:u,consumerReport:p}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,a)=>{var o,c;r.push({producerId:a,videoStats:i.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:i.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((c=(o=this.callStatsInstance.producers)==null?void 0:o.get(a))==null?void 0:c.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,a)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(a);r.push({consumerId:a,peerId:o,producerId:c,appData:d,videoStats:i.inboundVideoRtpId.map(l=>e.inboundVideoRtp.get(l)),audioStats:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))})})}catch(i){console.error("getConsumersReport: ",i,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):r()}catch(i){r(i)}})}async getConnectivity(e){try{const r={iceServers:e||Rh},i=new Promise((u,p)=>{try{const f=new QT(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),a=new Promise((u,p)=>{try{const f=new XT(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),o=new Promise((u,p)=>{try{const f=new ZT(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),[c,d,l]=await Promise.all([i,a,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((a,o)=>{try{const c={iceServers:e||Rh},d=new YT(c);d.addListener("done",a),d.addListener("failed",o),d.start(1e4)}catch(c){o(c)}});return{throughput:i.throughput,fractionalLoss:0,RTT:i.RTT,jitter:0,backendRTT:i.backendRTT}}catch(r){return}}async getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Gg.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){return}}async getNetworkQuality(e){const[r,i]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}async getNetworkInfo(e,r=!1){var c,d;if(r){const l=await this.getIPDetails();return{ipDetails:l,effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,location:l!=null&&l.loc?kh(l==null?void 0:l.loc):void 0}}const[i,a,o]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:o,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:o!=null&&o.loc?kh(o==null?void 0:o.loc):void 0,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,throughput:a==null?void 0:a.throughput,fractionalLoss:a==null?void 0:a.fractionalLoss,RTT:a==null?void 0:a.RTT,jitter:a==null?void 0:a.jitter,backendRTT:a==null?void 0:a.backendRTT}}}class tS extends Jg{}class Kg extends Jg{constructor(){super(...arguments);h(this,"producerMap",new Map);h(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),a=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...a.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(a,o,e.id):void 0;for(const d of i.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return c}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],i=!1,a=void 0,o=void 0){var b,_,M,A,x,N,$,K,Z,Ue,es,zr,ts;const c=e,d=new Wg,l=r.length?new Set(r):void 0,u=[],p=[],f=[],T=new Map,E=new Map;for(const k of c.values()){if(l){if(l.size===0)break;if(l.has(k.type))i&&l.delete(k.type);else continue}switch(k.type){case"local-candidate":{u.push(this.getIceCandidateStats(k));break}case"remote-candidate":{p.push(this.getIceCandidateStats(k));break}case"candidate-pair":{const{nominated:v}=k,{selected:P}=k,U=k,me={nominated:v!=null?v:P,currentRoundTripTime:U.currentRoundTripTime,totalRoundTripTime:U.totalRoundTripTime,bytesReceived:U.bytesReceived,bytesSent:U.bytesSent,availableOutgoingBitrate:U.availableOutgoingBitrate,availableIncomingBitrate:U.availableIncomingBitrate,lastPacketReceivedTimestamp:U.lastPacketReceivedTimestamp,lastPacketSentTimestamp:U.lastPacketSentTimestamp,localCandidateId:U.localCandidateId,remoteCandidateId:U.remoteCandidateId,bytesDiscardedOnSend:U.bytesDiscardedOnSend,packetsSent:U.packetsSent,packetsReceived:U.packetsReceived,packetsDiscardedOnSend:U.packetsDiscardedOnSend};f.push(me),(k.nominated===!0||k.selected===!0)&&(d.candidatePair=me);break}case"transport":{const v=k;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:v.bytesReceived,bytesSent:v.bytesSent,packetsSent:v.packetsSent,packetsReceived:v.packetsReceived,dtlsCipher:v.dtlsCipher,dtlsState:v.dtlsState,iceRole:v.iceRole};if(d.transport=P,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,P)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,P)}}break}case"remote-inbound-rtp":{const v=k,P={jitter:v.jitter,fractionLost:v.fractionLost,roundTripTime:v.roundTripTime,roundTripTimeMeasurements:v.roundTripTimeMeasurements,totalRoundTripTime:v.totalRoundTripTime,packetsLost:v.packetsLost};d.remoteInboundRtp.set(v.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(k.id))break;const v=k,P=a||this.outboundProducerMap.get(k.id),U=this.pausedProducerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const me=this.overallProducersStatsMap[P];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.outboundProducerMap.has(k.id)){d.staleProducerStreamMap=!0;break}const we=this.callStatsInstance.producers.get(P);if(((b=we==null?void 0:we.track)==null?void 0:b.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const O={bytesSent:v.bytesSent,packetsSent:v.packetsSent,nackCount:v.nackCount,ssrc:v.ssrc,mid:v.mid,active:v.active,codecId:v.codecId,headerBytesSent:v.headerBytesSent||0,totalPacketSendDelay:v.totalPacketSendDelay||0};if(v.mediaType==="video"||v.kind==="video"){const w=v,De={frameHeight:w.frameHeight,frameWidth:w.frameWidth,framesEncoded:w.framesEncoded,framesDropped:w.framesDropped?w.framesDropped:w.droppedFrames,framesPerSecond:w.framesPerSecond?w.framesPerSecond:w.framerateMean,framesSent:w.framesSent,keyFramesEncoded:w.keyFramesEncoded,firCount:w.firCount,encoderImplementation:w.encoderImplementation,hugeFramesSent:w.hugeFramesSent,pliCount:w.pliCount,qpSum:w.qpSum,qualityLimitationReason:w.qualityLimitationReason,qualityLimitationDurations:w.qualityLimitationDurations,qualityLimitationResolutionChanges:w.qualityLimitationResolutionChanges,totalEncodeTime:w.totalEncodeTime,totalPacketSendDelay:w.totalEncodeTime,retransmittedBytesSent:w.retransmittedBytesSent,retransmittedPacketsSent:w.retransmittedPacketsSent,scalabilityMode:w.scalabilityMode,powerEfficientEncoder:w.powerEfficientEncoder,...O};d.outboundVideoRtp.set(k.id,De),d.producerStreamMap.get(P).outboundVideoRtpId.push(k.id),this.processOutboundProducerVideoStats(P,me,De)}else if(v.mediaType==="audio"||v.kind==="audio"){const w=v,De={retransmittedBytesSent:w.retransmittedBytesSent,retransmittedPacketsSent:w.retransmittedPacketsSent,...O};d.outboundAudioRtp.set(k.id,De),d.producerStreamMap.get(P).outboundAudioRtpId.push(k.id),this.processOutboundProducerAudioStats(P,me,De)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(k.id))break;const v=k,P=a||this.inboundConsumerMap.get(k.id),U=this.pausedConsumerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(v.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const me=this.overallConsumersStatsMap[P];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.inboundConsumerMap.has(k.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const we={bytesReceived:v.bytesReceived,packetsReceived:v.packetsReceived,packetsLost:v.packetsLost>=0?v.packetsLost:0,jitter:v.jitter,nackCount:v.nackCount,jitterBufferDelay:v.jitterBufferDelay,jitterBufferEmittedCount:v.jitterBufferEmittedCount,lastPacketReceivedTimestamp:v.lastPacketReceivedTimestamp,ssrc:v.ssrc,mid:v.mid,codecId:v.codecId,headerBytesReceived:v.headerBytesReceived||0,packetsDiscarded:v.packetsDiscarded||0,jitterBufferMinimumDelay:v.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:v.jitterBufferTargetDelay||0};if(v.mediaType==="video"||v.kind==="video"){const O=v,w={frameHeight:O.frameHeight,frameWidth:O.frameWidth,framesDecoded:O.framesDecoded,framesDropped:O.framesDropped?O.framesDropped:O.droppedFrames,framesPerSecond:O.framesPerSecond?O.framesPerSecond:O.framerateMean,framesReceived:O.framesReceived,keyFramesDecoded:O.keyFramesDecoded,firCount:O.firCount,decoderImplementation:O.decoderImplementation,pliCount:O.pliCount,totalProcessingDelay:O.totalProcessingDelay,qpSum:O.qpSum||0,totalAssemblyTime:O.totalAssemblyTime||0,totalDecodeTime:O.totalDecodeTime||0,totalFreezesDuration:O.totalFreezesDuration||0,totalInterFrameDelay:O.totalInterFrameDelay||0,totalPausesDuration:O.totalPausesDuration||0,totalSquaredInterFrameDelay:O.totalSquaredInterFrameDelay||0,freezeCount:O.freezeCount||0,pauseCount:O.pauseCount||0,powerEfficientDecoder:O.powerEfficientDecoder,...we};w.score=qg({frameWidth:w.frameWidth||0,framesDecoded:(w.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:w.framesPerSecond||0,packetsLost:(w.packetsLost||0)-(((M=this.videoConsumerToStatsMap.get(P))==null?void 0:M.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((A=this.videoConsumerToStatsMap.get(P))==null?void 0:A.packetsReceived)||0),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(w.score*10).toFixed(),frameWidth:w.frameWidth||0,frameHeight:w.frameHeight||0,framesPerSecond:w.framesPerSecond||0,packetsLostPercentage:ed({packetsLost:(w.packetsLost||0)-(((x=this.videoConsumerToStatsMap.get(P))==null?void 0:x.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0)}),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((w.bytesReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,w),d.inboundVideoRtp.set(k.id,w),d.consumerStreamMap.get(P).inboundVideoRtpId.push(k.id),this.processInboundConsumerVideoStats(P,me,w)}else if(v.mediaType==="audio"||v.kind==="audio"){const O=v,w={audioLevel:O.audioLevel,concealedSamples:O.concealedSamples,concealmentEvents:O.concealmentEvents,totalAudioEnergy:O.totalAudioEnergy,totalSamplesDuration:O.totalSamplesDuration,totalSamplesReceived:O.totalSamplesReceived,fecPacketsDiscarded:O.fecPacketsDiscarded||0,fecPacketsReceived:O.fecPacketsReceived||0,insertedSamplesForDeceleration:O.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:O.removedSamplesForAcceleration||0,silentConcealedSamples:O.silentConcealedSamples||0,playoutId:O.playoutId,...we};w.score=Fg({concealmentEvents:(w.concealmentEvents||0)-(((K=this.audioConsumerToStatsMap.get(P))==null?void 0:K.concealmentEvents)||0),packetsLost:(w.packetsLost||0)-(((Z=this.audioConsumerToStatsMap.get(P))==null?void 0:Z.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((Ue=this.audioConsumerToStatsMap.get(P))==null?void 0:Ue.packetsReceived)||0),jitter:w.jitter||0}),E.set(P,{score:+(w.score*10).toFixed(),packetsLostPercentage:ed({packetsLost:(w.packetsLost||0)-(((es=this.audioConsumerToStatsMap.get(P))==null?void 0:es.packetsLost)||0),packetsReceived:(w.packetsReceived||0)-(((zr=this.audioConsumerToStatsMap.get(P))==null?void 0:zr.packetsReceived)||0)}),jitter:w.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((w.bytesReceived||0)-(((ts=this.audioConsumerToStatsMap.get(P))==null?void 0:ts.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,w),d.inboundAudioRtp.set(k.id,w),d.consumerStreamMap.get(P).inboundAudioRtpId.push(k.id),this.processInboundConsumerAudioStats(P,me,w)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}}}if(d.producerStreamMap.forEach((k,v)=>{var P,U,me,we,O,w,De,Ds,wa,Ra,ka,Ma,Ia,Aa,Da,Oa,Na,La,Va,xa,Ua,$a,Ba;if(k.outboundVideoRtpId.length>0){const ae=[];k.outboundVideoRtpId.forEach(Dl=>{ae.push(d.outboundVideoRtp.get(Dl))});const Y=this.getWorkingSimulcastVideoStats(ae);Y.score=Bg({frameWidth:Y.frameWidth||0,framesPerSecond:Y.framesPerSecond||0,jitter:((P=Y.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsSent:(Y.packetsSent||0)-(((U=this.videoProducerToStatsMap.get(v))==null?void 0:U.packetsSent)||0),packetsLost:(((me=Y.remoteData)==null?void 0:me.packetsLost)||0)-(((O=(we=this.videoProducerToStatsMap.get(v))==null?void 0:we.remoteData)==null?void 0:O.packetsLost)||0),framesEncoded:(Y.framesEncoded||0)-(((w=this.videoProducerToStatsMap.get(v))==null?void 0:w.framesEncoded)||0)}),T.set(v,{score:+(Y.score*10).toFixed(),frameWidth:Y.frameWidth||0,frameHeight:Y.frameHeight||0,framesPerSecond:Y.framesPerSecond||0,jitter:((De=Y.remoteData)==null?void 0:De.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsLostPercentage:Zc({packetsSent:(Y.packetsSent||0)-(((Ds=this.videoProducerToStatsMap.get(v))==null?void 0:Ds.packetsSent)||0),packetsLost:(((wa=Y.remoteData)==null?void 0:wa.packetsLost)||0)-(((ka=(Ra=this.videoProducerToStatsMap.get(v))==null?void 0:Ra.remoteData)==null?void 0:ka.packetsLost)||0)}),bitrate:((Y.bytesSent||0)-(((Ma=this.videoProducerToStatsMap.get(v))==null?void 0:Ma.bytesSent)||0))*8/7,cpuLimitations:Y.qualityLimitationReason==="cpu",bandwidthLimitations:Y.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(v,Y)}else if(k.outboundAudioRtpId.length>0){const ae=d.outboundAudioRtp.get(k.outboundAudioRtpId[0]);ae.score=$g({packetsSent:(ae.packetsSent||0)-(((Ia=this.audioProducerToStatsMap.get(v))==null?void 0:Ia.packetsSent)||0),packetsLost:(((Aa=ae.remoteData)==null?void 0:Aa.packetsLost)||0)-(((Oa=(Da=this.audioProducerToStatsMap.get(v))==null?void 0:Da.remoteData)==null?void 0:Oa.packetsLost)||0),jitter:((Na=ae.remoteData)==null?void 0:Na.jitter)||0}),T.set(v,{score:+(ae.score*10).toFixed(),bitrate:((ae.bytesSent||0)-(((La=this.audioProducerToStatsMap.get(v))==null?void 0:La.bytesSent)||0))*8/7,packetsLostPercentage:Zc({packetsSent:(ae.packetsSent||0)-(((Va=this.audioProducerToStatsMap.get(v))==null?void 0:Va.packetsSent)||0),packetsLost:(((xa=ae.remoteData)==null?void 0:xa.packetsLost)||0)-((($a=(Ua=this.audioProducerToStatsMap.get(v))==null?void 0:Ua.remoteData)==null?void 0:$a.packetsLost)||0)}),jitter:((Ba=ae.remoteData)==null?void 0:Ba.jitter)||0,isScreenShare:this.screenShareProducers.has(v)}),this.audioProducerToStatsMap.set(v,ae)}}),f.forEach(k=>{const v=u.find(U=>U.id===k.localCandidateId?(k.localCandidateId=U.id,U):null),P=p.find(U=>U.id===k.remoteCandidateId?(k.remoteCandidateId=U.id,U):null);v&&(k.localCandidateType=v.type,k.localCandidateAddress=Hr(v.address),k.localCandidatePort=v.port,k.localCandidateProtocol=v.protocol,k.localCandidateUrl=v.url,k.localCandidateNetworkType=v.networkType,k.localCandidateRelatedAddress=Hr(v.relatedAddress),k.localCandidateRelatedPort=v.relatedPort),P&&(k.remoteCandidateType=P.type,k.remoteCandidateAddress=Hr(P.address),k.remoteCandidatePort=P.port,k.remoteCandidateProtocol=P.protocol,k.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let k=0,v=0;d.remoteInboundRtp.forEach((P,U)=>{P.roundTripTime&&P.roundTripTime>k&&(k=P.roundTripTime,v=P.totalRoundTripTime)}),d.transport.roundTripTime=k,d.transport.totalRoundTripTime=v}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(k){}if(T.size>0)try{this.observer.emit("producer_score",T)}catch(k){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,a)=>{const o=this.producerMap.get(a),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(u=>{const p=e.outboundVideoRtp.get(u);return p.frameHeight||(p.frameHeight=c.height,p.frameWidth=c.width,p.framesPerSecond=c.frameRate),p}),l={producerId:a,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(u=>e.outboundAudioRtp.get(u))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let a;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(u=>{const f=this.consumerMap.get(i).track.getSettings(),T=e.inboundVideoRtp.get(u);return T.frameHeight||(T.frameHeight=f.height,T.frameWidth=f.width,T.framesPerSecond=f.frameRate),T});a={consumerId:i,peerId:o,producerId:c,appData:d,videoStats:l,audioStats:r==null?void 0:r.inboundAudioRtpId.map(u=>e.inboundAudioRtp.get(u))}}catch(o){console.error("getConsumerStatsFromParsedConsumerStats: ",o,e)}return a}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,a)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,a))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class sS extends Kg{}function td(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function Mh(s,t,e){const r=s.value;return s.value=function(...i){try{const a=r.apply(this,i);return a&&a instanceof Promise?a.catch(o=>{td(this,t,e,o)}):a}catch(a){td(this,t,e,a)}return null},s}const z=(s,t)=>(e,r,i)=>{const a=i.value;return i.value=function(...o){try{const c=a.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{td(this,s,t,d)}):c}catch(c){td(this,s,t,c)}return null},i},rS=(s,t)=>(e,r,i)=>{if(i)return Mh(i,s,t);for(const a of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,a);o.value instanceof Function&&Object.defineProperty(e.prototype,a,Mh(o,s,t))}};var W=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(a=(i<3?o(a):i>3?o(t,e,a):o(t,e))||a);return i>3&&a&&Object.defineProperty(t,e,a),a};const J=console;let j=class extends st{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Dg.PROD,a,o,c,d,l){super();h(this,"observer");h(this,"eventHandler");h(this,"measurements");h(this,"producingTransport");h(this,"consumingTransport");h(this,"producers",new Map);h(this,"consumers",new Map);h(this,"iceServers");h(this,"connectionInfoPromise");h(this,"pingStatsTimeout");h(this,"logger");h(this,"env");h(this,"apiHostnames");h(this,"peerId");h(this,"consumerSharedMediaStatesMap",new Map);h(this,"currentUserMediaStates",{});if(!l)throw Error("authToken is missing but required to initialize CallStats!");switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new HT({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new tS;break;case"Gecko":this.measurements=new Kg;break;case"WebKit":this.measurements=new sS;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new st,this.measurements.observer.on("consumer_score",u=>{o.debug(`callStats::consumer_score ${[...u.entries()]}`),this.eventHandler.emit("consumer_score",u)}),this.measurements.observer.on("producer_score",u=>{o.debug(`callStats::producer_score ${[...u.entries()]}`),this.eventHandler.emit("producer_score",u)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const i=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(i,r))}registerProducingTransport(e){var i;this.producingTransport=e,e.on("close",this.disconnectProducingTransport.bind(this,e)),e.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((i=e._producers)==null?void 0:i.values())||[]).forEach(a=>{this.registerProducer(a)}),e.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var i;this.consumingTransport=e,e.on("close",this.disconnectConsumingTransport.bind(this,e)),e.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((i=e._consumers)==null?void 0:i.values())||[]).forEach(a=>{this.registerConsumer(a)}),e.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1,r){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:D.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:D.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?D.SCREENSHARE_STARTED:D.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:D.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:D.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===$t.AUDIO&&D.AUDIO_DEVICES_UPDATES||e===$t.VIDEO&&D.VIDEO_DEVICES_UPDATES||e===$t.SPEAKER&&D.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===$t.AUDIO&&D.SELECTED_MICROHPONE_UPDATE||e===$t.VIDEO&&D.SELECTED_CAMERA_UPDATE||e===$t.SPEAKER&&D.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:D.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===$t.AUDIO&&D.AUDIO_PLAY_FAILED||e===$t.VIDEO&&D.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===$t.AUDIO&&D.AUDIO_TRACK_MUTED||e===$t.VIDEO&&D.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:D.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:D.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:D.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:D.LEGACY_SWITCH,metadata:{on:e},timestamp:r})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e,r){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:D.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_BEGIN,timestamp:r}),new Promise(async(a,o)=>{const c=[];try{for(const d of e)try{if(d.iceServers&&d.iceServers.length>0){const l=await this.measurements.getNetworkQuality(d.iceServers);c.push({...d,networkResults:l})}}catch(l){console.warn("Error handling ",l)}a({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(a=>{this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_END,timestamp:r,metaData:a})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:D.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:D.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=D.AUDIO_ON:i=D.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=D.VIDEO_ON:i=D.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:D.PARTICIPANT_ROLE,timestamp:r,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0,r){var c,d;let i,a;if(this.producingTransport&&(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!i||!((c=i==null?void 0:i.producerReport)!=null&&c.length))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const l=await this.measurements.getProducersReport([...this.producers.values()]);i&&l?i.producerReport=l:(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!i||!(i!=null&&i.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(a=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!a||!((d=a.consumerReport)!=null&&d.length))){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const l=await this.measurements.getConsumersReport([...this.consumers.values()]);a&&l?a.consumerReport=l:(a=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!a||!a.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const o={producingTransportStats:i?i==null?void 0:i.transportReport:void 0,consumingTransportStats:a?a==null?void 0:a.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((a==null?void 0:a.producerReport)||[]),consumerStats:[].concat((a==null?void 0:a.consumerReport)||[]).concat((i==null?void 0:i.consumerReport)||[])};if(e&&o.producerStats.length===0&&o.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:D.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:D.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:D.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:D.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"registerIceServers",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"registerConsumer",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"registerProducer",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendConsumerSharedMediaStateEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"registerProducingTransport",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"registerConsumingTransport",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"deRegisterConsumer",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"deRegisterProducer",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"disconnectConsumingTransport",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"disconnectProducingTransport",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendPreCallTestBeginEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendScreenShareToggleEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendScreenShareRequestedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendActiveSpeakerEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"devices",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"selectedDevice",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"mediaPermission",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"mediaPlaybackFailed",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"mediaTrackMuted",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"tabChanged",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"browserBackgrounded",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"browserForegrounded",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"legacySwitch",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"getPreCallTestResults",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendCallJoinBeginEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendNetworkQualityTestBeginEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendWebSocketConnectedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendTransportConnectedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendAudioToggleEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendVideoToggleEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendParticipantRoleToggleEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"startPingStats",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"stopPingStats",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendPingStatsEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerRebufferEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerAudioBlockEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerInitializedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerWorkerErrorEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerErrorEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerRecoverableErrorEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerAnalyticsEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerQualityChanged",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendPlayerLiveLatency",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendDisconnectEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendReconnectEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"expectedVideoResolution",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"expectedScreenshareResolution",null);j=W([rS(TypeError,(s,t)=>J.error(t,s))],j);const iS=j;class zg extends st{constructor(){super(...arguments);h(this,"stats");h(this,"peerId");h(this,"backend");h(this,"iceServers");h(this,"initialized",!1);h(this,"stalled",!1);h(this,"ipInformation");h(this,"logger")}async initialize({peerId:e,engineName:r,env:i=Dg.PROD,iceServers:a,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:p}){var f,T,E;try{if(this.peerId=e,this.logger=d,!p){this.logger.error("callStats::initialize",{event:"auth_token_missing",peerId:this.peerId}),this.stallCallStats();return}this.ipInformation=await Gg.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new iS(o,r,i,c,d,e,l,p),this.iceServers=a,(f=this.backend)==null||f.registerIceServers(this.iceServers),this.initialized=!0,(E=(T=this.backend)==null?void 0:T.eventHandler)==null||E.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(b){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:b instanceof Error?b.message:String(b),stack:b instanceof Error?b.stack:void 0}),this.stallCallStats()}}configureSendTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerConsumingTransport(e)})}async candidateRegionalNetworkQualityTest(e){const r=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,r)}catch(a){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:a.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,a;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(a=this.backend)==null||a.startPingStats()})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var r,i;(r=this.backend)==null||r.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!1,e,r)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,r)})}devices(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.mediaPermission(e,r,i)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.tabChanged(e,r)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserForegrounded(e)})}legacySwitch(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.legacySwitch(e,r)})}async startPreCallTest(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,r)})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=i=>{e(i,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){const i=new Date;this.onSafeInitialization(()=>{var a,o,c,d,l,u,p,f,T,E,b;switch(e){case"PlayerRebuffering":(a=this.backend)==null||a.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(p=this.backend)==null||p.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(f=this.backend)==null||f.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(T=this.backend)==null||T.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(E=this.backend)==null||E.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(b=this.backend)==null||b.sendIVSPlayerQualityChanged(r,i);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.expectedScreenshareResolution(e,r,i)})}}const nS=new zg;nS.setMaxListeners(30);var mo;class aS{constructor(){g(this,mo,void 0)}get telemetry(){var t;return(t=n(this,mo))==null?void 0:t.getValue("telemetry")}init(t){m(this,mo,t)}info(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("info",t,e,r)}error(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("error",t,e,r)}debug(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("debug",t,e,r)}log(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("log",t,e,r)}warn(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("warn",t,e,r)}}mo=new WeakMap;var Ls,Vs;class oS extends st.EventEmitter{constructor(e){super();g(this,Ls,void 0);g(this,Vs,void 0);h(this,"asyncPromiseTimeout");h(this,"logger");this.logger=e,m(this,Ls,new Map),m(this,Vs,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){n(this,Ls).set(e,[]);const i=n(this,Vs).get(e).map(()=>new Promise(a=>{n(this,Ls).get(e).push(a)}));super.emit(e,...r),await Promise.race([Promise.all(i),new Promise((a,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),n(this,Ls).delete(e)}onAsync(e,r){const i=n(this,Ls),a=async(...o)=>{var d;try{await r(...o)}catch(l){this.logger.error("[onAsync]",{error:l})}const c=(d=i.get(e))==null?void 0:d.shift();c==null||c()};return n(this,Vs).get(e)||n(this,Vs).set(e,[]),n(this,Vs).get(e).push(a),super.on(e,a)}reset(){m(this,Ls,new Map),m(this,Vs,new Map),super.removeAllListeners()}}Ls=new WeakMap,Vs=new WeakMap;var cS=typeof global=="object"&&global&&global.Object===Object&&global;const Yg=cS;var dS=typeof self=="object"&&self&&self.Object===Object&&self,lS=Yg||dS||Function("return this")();const fs=lS;var uS=fs.Symbol;const Ms=uS;var Qg=Object.prototype,hS=Qg.hasOwnProperty,pS=Qg.toString,Ha=Ms?Ms.toStringTag:void 0;function gS(s){var t=hS.call(s,Ha),e=s[Ha];try{s[Ha]=void 0;var r=!0}catch(a){}var i=pS.call(s);return r&&(t?s[Ha]=e:delete s[Ha]),i}var mS=Object.prototype,fS=mS.toString;function TS(s){return fS.call(s)}var SS="[object Null]",vS="[object Undefined]",Ih=Ms?Ms.toStringTag:void 0;function Ki(s){return s==null?s===void 0?vS:SS:Ih&&Ih in Object(s)?gS(s):TS(s)}function Is(s){return s!=null&&typeof s=="object"}var yS="[object Symbol]";function hl(s){return typeof s=="symbol"||Is(s)&&Ki(s)==yS}function ES(s,t){for(var e=-1,r=s==null?0:s.length,i=Array(r);++e<r;)i[e]=t(s[e],e,s);return i}var PS=Array.isArray;const Dt=PS;var bS=1/0,Ah=Ms?Ms.prototype:void 0,Dh=Ah?Ah.toString:void 0;function Xg(s){if(typeof s=="string")return s;if(Dt(s))return ES(s,Xg)+"";if(hl(s))return Dh?Dh.call(s):"";var t=s+"";return t=="0"&&1/s==-bS?"-0":t}var _S=/\s/;function CS(s){for(var t=s.length;t--&&_S.test(s.charAt(t)););return t}var wS=/^\s+/;function RS(s){return s&&s.slice(0,CS(s)+1).replace(wS,"")}function Zt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var Oh=0/0,kS=/^[-+]0x[0-9a-f]+$/i,MS=/^0b[01]+$/i,IS=/^0o[0-7]+$/i,AS=parseInt;function Nh(s){if(typeof s=="number")return s;if(hl(s))return Oh;if(Zt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Zt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=RS(s);var e=MS.test(s);return e||IS.test(s)?AS(s.slice(2),e?2:8):kS.test(s)?Oh:+s}function Fu(s){return s}var DS="[object AsyncFunction]",OS="[object Function]",NS="[object GeneratorFunction]",LS="[object Proxy]";function qu(s){if(!Zt(s))return!1;var t=Ki(s);return t==OS||t==NS||t==DS||t==LS}var VS=fs["__core-js_shared__"];const Nl=VS;var Lh=function(){var s=/[^.]+$/.exec(Nl&&Nl.keys&&Nl.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function xS(s){return!!Lh&&Lh in s}var US=Function.prototype,$S=US.toString;function zi(s){if(s!=null){try{return $S.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var BS=/[\\^$.*+?()[\]{}|]/g,HS=/^\[object .+?Constructor\]$/,FS=Function.prototype,qS=Object.prototype,jS=FS.toString,GS=qS.hasOwnProperty,WS=RegExp("^"+jS.call(GS).replace(BS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function JS(s){if(!Zt(s)||xS(s))return!1;var t=qu(s)?WS:HS;return t.test(zi(s))}function KS(s,t){return s==null?void 0:s[t]}function Yi(s,t){var e=KS(s,t);return JS(e)?e:void 0}var zS=Yi(fs,"WeakMap");const Kl=zS;var Vh=Object.create,YS=function(){function s(){}return function(t){if(!Zt(t))return{};if(Vh)return Vh(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const QS=YS;function XS(s,t,e){switch(e.length){case 0:return s.call(t);case 1:return s.call(t,e[0]);case 2:return s.call(t,e[0],e[1]);case 3:return s.call(t,e[0],e[1],e[2])}return s.apply(t,e)}function ZS(){}function Zg(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var ev=800,tv=16,sv=Date.now;function rv(s){var t=0,e=0;return function(){var r=sv(),i=tv-(r-e);if(e=r,i>0){if(++t>=ev)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function iv(s){return function(){return s}}var nv=function(){try{var s=Yi(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const sd=nv;var av=sd?function(s,t){return sd(s,"toString",{configurable:!0,enumerable:!1,value:iv(t),writable:!0})}:Fu;const ov=av;var cv=rv(ov);const dv=cv;function lv(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function uv(s,t,e,r){for(var i=s.length,a=e+(r?1:-1);r?a--:++a<i;)if(t(s[a],a,s))return a;return-1}function hv(s){return s!==s}function pv(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function gv(s,t,e){return t===t?pv(s,t,e):uv(s,hv,e)}function mv(s,t){var e=s==null?0:s.length;return!!e&&gv(s,t,0)>-1}var fv=9007199254740991,Tv=/^(?:0|[1-9]\d*)$/;function ju(s,t){var e=typeof s;return t=t==null?fv:t,!!t&&(e=="number"||e!="symbol"&&Tv.test(s))&&s>-1&&s%1==0&&s<t}function Gu(s,t,e){t=="__proto__"&&sd?sd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function Tc(s,t){return s===t||s!==s&&t!==t}var Sv=Object.prototype,vv=Sv.hasOwnProperty;function em(s,t,e){var r=s[t];(!(vv.call(s,t)&&Tc(r,e))||e===void 0&&!(t in s))&&Gu(s,t,e)}function Sc(s,t,e,r){var i=!e;e||(e={});for(var a=-1,o=t.length;++a<o;){var c=t[a],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?Gu(e,c,d):em(e,c,d)}return e}var xh=Math.max;function yv(s,t,e){return t=xh(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,a=xh(r.length-t,0),o=Array(a);++i<a;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),XS(s,this,c)}}function Ev(s,t){return dv(yv(s,t,Fu),s+"")}var Pv=9007199254740991;function Wu(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=Pv}function vc(s){return s!=null&&Wu(s.length)&&!qu(s)}function bv(s,t,e){if(!Zt(e))return!1;var r=typeof t;return(r=="number"?vc(e)&&ju(t,e.length):r=="string"&&t in e)?Tc(e[t],s):!1}function _v(s){return Ev(function(t,e){var r=-1,i=e.length,a=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(a=s.length>3&&typeof a=="function"?(i--,a):void 0,o&&bv(e[0],e[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,a)}return t})}var Cv=Object.prototype;function pl(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||Cv;return s===e}function wv(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var Rv="[object Arguments]";function Uh(s){return Is(s)&&Ki(s)==Rv}var tm=Object.prototype,kv=tm.hasOwnProperty,Mv=tm.propertyIsEnumerable,Iv=Uh(function(){return arguments}())?Uh:function(s){return Is(s)&&kv.call(s,"callee")&&!Mv.call(s,"callee")};const lo=Iv;function Av(){return!1}var sm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,$h=sm&&typeof module=="object"&&module&&!module.nodeType&&module,Dv=$h&&$h.exports===sm,Bh=Dv?fs.Buffer:void 0,Ov=Bh?Bh.isBuffer:void 0,Nv=Ov||Av;const Ta=Nv;var Lv="[object Arguments]",Vv="[object Array]",xv="[object Boolean]",Uv="[object Date]",$v="[object Error]",Bv="[object Function]",Hv="[object Map]",Fv="[object Number]",qv="[object Object]",jv="[object RegExp]",Gv="[object Set]",Wv="[object String]",Jv="[object WeakMap]",Kv="[object ArrayBuffer]",zv="[object DataView]",Yv="[object Float32Array]",Qv="[object Float64Array]",Xv="[object Int8Array]",Zv="[object Int16Array]",ey="[object Int32Array]",ty="[object Uint8Array]",sy="[object Uint8ClampedArray]",ry="[object Uint16Array]",iy="[object Uint32Array]",pe={};pe[Yv]=pe[Qv]=pe[Xv]=pe[Zv]=pe[ey]=pe[ty]=pe[sy]=pe[ry]=pe[iy]=!0;pe[Lv]=pe[Vv]=pe[Kv]=pe[xv]=pe[zv]=pe[Uv]=pe[$v]=pe[Bv]=pe[Hv]=pe[Fv]=pe[qv]=pe[jv]=pe[Gv]=pe[Wv]=pe[Jv]=!1;function ny(s){return Is(s)&&Wu(s.length)&&!!pe[Ki(s)]}function Ju(s){return function(t){return s(t)}}var rm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,to=rm&&typeof module=="object"&&module&&!module.nodeType&&module,ay=to&&to.exports===rm,Ll=ay&&Yg.process,oy=function(){try{var s=to&&to.require&&to.require("util").types;return s||Ll&&Ll.binding&&Ll.binding("util")}catch(t){}}();const Sa=oy;var Hh=Sa&&Sa.isTypedArray,cy=Hh?Ju(Hh):ny;const gl=cy;var dy=Object.prototype,ly=dy.hasOwnProperty;function im(s,t){var e=Dt(s),r=!e&&lo(s),i=!e&&!r&&Ta(s),a=!e&&!r&&!i&&gl(s),o=e||r||i||a,c=o?wv(s.length,String):[],d=c.length;for(var l in s)(t||ly.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||a&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||ju(l,d)))&&c.push(l);return c}function nm(s,t){return function(e){return s(t(e))}}var uy=nm(Object.keys,Object);const hy=uy;var py=Object.prototype,gy=py.hasOwnProperty;function am(s){if(!pl(s))return hy(s);var t=[];for(var e in Object(s))gy.call(s,e)&&e!="constructor"&&t.push(e);return t}function ml(s){return vc(s)?im(s):am(s)}function my(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var fy=Object.prototype,Ty=fy.hasOwnProperty;function Sy(s){if(!Zt(s))return my(s);var t=pl(s),e=[];for(var r in s)r=="constructor"&&(t||!Ty.call(s,r))||e.push(r);return e}function yc(s){return vc(s)?im(s,!0):Sy(s)}var vy=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,yy=/^\w*$/;function Ku(s,t){if(Dt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||hl(s)?!0:yy.test(s)||!vy.test(s)||t!=null&&s in Object(t)}var Ey=Yi(Object,"create");const uo=Ey;function Py(){this.__data__=uo?uo(null):{},this.size=0}function by(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var _y="__lodash_hash_undefined__",Cy=Object.prototype,wy=Cy.hasOwnProperty;function Ry(s){var t=this.__data__;if(uo){var e=t[s];return e===_y?void 0:e}return wy.call(t,s)?t[s]:void 0}var ky=Object.prototype,My=ky.hasOwnProperty;function Iy(s){var t=this.__data__;return uo?t[s]!==void 0:My.call(t,s)}var Ay="__lodash_hash_undefined__";function Dy(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=uo&&t===void 0?Ay:t,this}function Wi(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}Wi.prototype.clear=Py;Wi.prototype.delete=by;Wi.prototype.get=Ry;Wi.prototype.has=Iy;Wi.prototype.set=Dy;function Oy(){this.__data__=[],this.size=0}function fl(s,t){for(var e=s.length;e--;)if(Tc(s[e][0],t))return e;return-1}var Ny=Array.prototype,Ly=Ny.splice;function Vy(s){var t=this.__data__,e=fl(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():Ly.call(t,e,1),--this.size,!0}function xy(s){var t=this.__data__,e=fl(t,s);return e<0?void 0:t[e][1]}function Uy(s){return fl(this.__data__,s)>-1}function $y(s,t){var e=this.__data__,r=fl(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function dr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}dr.prototype.clear=Oy;dr.prototype.delete=Vy;dr.prototype.get=xy;dr.prototype.has=Uy;dr.prototype.set=$y;var By=Yi(fs,"Map");const ho=By;function Hy(){this.size=0,this.__data__={hash:new Wi,map:new(ho||dr),string:new Wi}}function Fy(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function Tl(s,t){var e=s.__data__;return Fy(t)?e[typeof t=="string"?"string":"hash"]:e.map}function qy(s){var t=Tl(this,s).delete(s);return this.size-=t?1:0,t}function jy(s){return Tl(this,s).get(s)}function Gy(s){return Tl(this,s).has(s)}function Wy(s,t){var e=Tl(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function lr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}lr.prototype.clear=Hy;lr.prototype.delete=qy;lr.prototype.get=jy;lr.prototype.has=Gy;lr.prototype.set=Wy;var Jy="Expected a function";function zu(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(Jy);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],a=e.cache;if(a.has(i))return a.get(i);var o=s.apply(this,r);return e.cache=a.set(i,o)||a,o};return e.cache=new(zu.Cache||lr),e}zu.Cache=lr;var Ky=500;function zy(s){var t=zu(s,function(r){return e.size===Ky&&e.clear(),r}),e=t.cache;return t}var Yy=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Qy=/\\(\\)?/g,Xy=zy(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(Yy,function(e,r,i,a){t.push(i?a.replace(Qy,"$1"):r||e)}),t});const Zy=Xy;function eE(s){return s==null?"":Xg(s)}function om(s,t){return Dt(s)?s:Ku(s,t)?[s]:Zy(eE(s))}var tE=1/0;function Sl(s){if(typeof s=="string"||hl(s))return s;var t=s+"";return t=="0"&&1/s==-tE?"-0":t}function cm(s,t){t=om(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[Sl(t[e++])];return e&&e==r?s:void 0}function sE(s,t,e){var r=s==null?void 0:cm(s,t);return r===void 0?e:r}function dm(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var rE=nm(Object.getPrototypeOf,Object);const Yu=rE;var iE="[object Object]",nE=Function.prototype,aE=Object.prototype,lm=nE.toString,oE=aE.hasOwnProperty,cE=lm.call(Object);function dE(s){if(!Is(s)||Ki(s)!=iE)return!1;var t=Yu(s);if(t===null)return!0;var e=oE.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&lm.call(e)==cE}function lE(){this.__data__=new dr,this.size=0}function uE(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function hE(s){return this.__data__.get(s)}function pE(s){return this.__data__.has(s)}var gE=200;function mE(s,t){var e=this.__data__;if(e instanceof dr){var r=e.__data__;if(!ho||r.length<gE-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new lr(r)}return e.set(s,t),this.size=e.size,this}function ms(s){var t=this.__data__=new dr(s);this.size=t.size}ms.prototype.clear=lE;ms.prototype.delete=uE;ms.prototype.get=hE;ms.prototype.has=pE;ms.prototype.set=mE;function fE(s,t){return s&&Sc(t,ml(t),s)}function TE(s,t){return s&&Sc(t,yc(t),s)}var um=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Fh=um&&typeof module=="object"&&module&&!module.nodeType&&module,SE=Fh&&Fh.exports===um,qh=SE?fs.Buffer:void 0,jh=qh?qh.allocUnsafe:void 0;function hm(s,t){if(t)return s.slice();var e=s.length,r=jh?jh(e):new s.constructor(e);return s.copy(r),r}function vE(s,t){for(var e=-1,r=s==null?0:s.length,i=0,a=[];++e<r;){var o=s[e];t(o,e,s)&&(a[i++]=o)}return a}function pm(){return[]}var yE=Object.prototype,EE=yE.propertyIsEnumerable,Gh=Object.getOwnPropertySymbols,PE=Gh?function(s){return s==null?[]:(s=Object(s),vE(Gh(s),function(t){return EE.call(s,t)}))}:pm;const Qu=PE;function bE(s,t){return Sc(s,Qu(s),t)}var _E=Object.getOwnPropertySymbols,CE=_E?function(s){for(var t=[];s;)dm(t,Qu(s)),s=Yu(s);return t}:pm;const gm=CE;function wE(s,t){return Sc(s,gm(s),t)}function mm(s,t,e){var r=t(s);return Dt(s)?r:dm(r,e(s))}function zl(s){return mm(s,ml,Qu)}function RE(s){return mm(s,yc,gm)}var kE=Yi(fs,"DataView");const Yl=kE;var ME=Yi(fs,"Promise");const Ql=ME;var IE=Yi(fs,"Set");const pn=IE;var Wh="[object Map]",AE="[object Object]",Jh="[object Promise]",Kh="[object Set]",zh="[object WeakMap]",Yh="[object DataView]",DE=zi(Yl),OE=zi(ho),NE=zi(Ql),LE=zi(pn),VE=zi(Kl),Yr=Ki;(Yl&&Yr(new Yl(new ArrayBuffer(1)))!=Yh||ho&&Yr(new ho)!=Wh||Ql&&Yr(Ql.resolve())!=Jh||pn&&Yr(new pn)!=Kh||Kl&&Yr(new Kl)!=zh)&&(Yr=function(s){var t=Ki(s),e=t==AE?s.constructor:void 0,r=e?zi(e):"";if(r)switch(r){case DE:return Yh;case OE:return Wh;case NE:return Jh;case LE:return Kh;case VE:return zh}return t});const va=Yr;var xE=Object.prototype,UE=xE.hasOwnProperty;function $E(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&UE.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var BE=fs.Uint8Array;const rd=BE;function Xu(s){var t=new s.constructor(s.byteLength);return new rd(t).set(new rd(s)),t}function HE(s,t){var e=t?Xu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var FE=/\w*$/;function qE(s){var t=new s.constructor(s.source,FE.exec(s));return t.lastIndex=s.lastIndex,t}var Qh=Ms?Ms.prototype:void 0,Xh=Qh?Qh.valueOf:void 0;function jE(s){return Xh?Object(Xh.call(s)):{}}function fm(s,t){var e=t?Xu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var GE="[object Boolean]",WE="[object Date]",JE="[object Map]",KE="[object Number]",zE="[object RegExp]",YE="[object Set]",QE="[object String]",XE="[object Symbol]",ZE="[object ArrayBuffer]",eP="[object DataView]",tP="[object Float32Array]",sP="[object Float64Array]",rP="[object Int8Array]",iP="[object Int16Array]",nP="[object Int32Array]",aP="[object Uint8Array]",oP="[object Uint8ClampedArray]",cP="[object Uint16Array]",dP="[object Uint32Array]";function lP(s,t,e){var r=s.constructor;switch(t){case ZE:return Xu(s);case GE:case WE:return new r(+s);case eP:return HE(s,e);case tP:case sP:case rP:case iP:case nP:case aP:case oP:case cP:case dP:return fm(s,e);case JE:return new r;case KE:case QE:return new r(s);case zE:return qE(s);case YE:return new r;case XE:return jE(s)}}function Tm(s){return typeof s.constructor=="function"&&!pl(s)?QS(Yu(s)):{}}var uP="[object Map]";function hP(s){return Is(s)&&va(s)==uP}var Zh=Sa&&Sa.isMap,pP=Zh?Ju(Zh):hP;const gP=pP;var mP="[object Set]";function fP(s){return Is(s)&&va(s)==mP}var ep=Sa&&Sa.isSet,TP=ep?Ju(ep):fP;const SP=TP;var vP=1,yP=2,EP=4,Sm="[object Arguments]",PP="[object Array]",bP="[object Boolean]",_P="[object Date]",CP="[object Error]",vm="[object Function]",wP="[object GeneratorFunction]",RP="[object Map]",kP="[object Number]",ym="[object Object]",MP="[object RegExp]",IP="[object Set]",AP="[object String]",DP="[object Symbol]",OP="[object WeakMap]",NP="[object ArrayBuffer]",LP="[object DataView]",VP="[object Float32Array]",xP="[object Float64Array]",UP="[object Int8Array]",$P="[object Int16Array]",BP="[object Int32Array]",HP="[object Uint8Array]",FP="[object Uint8ClampedArray]",qP="[object Uint16Array]",jP="[object Uint32Array]",de={};de[Sm]=de[PP]=de[NP]=de[LP]=de[bP]=de[_P]=de[VP]=de[xP]=de[UP]=de[$P]=de[BP]=de[RP]=de[kP]=de[ym]=de[MP]=de[IP]=de[AP]=de[DP]=de[HP]=de[FP]=de[qP]=de[jP]=!0;de[CP]=de[vm]=de[OP]=!1;function so(s,t,e,r,i,a){var o,c=t&vP,d=t&yP,l=t&EP;if(e&&(o=i?e(s,r,i,a):e(s)),o!==void 0)return o;if(!Zt(s))return s;var u=Dt(s);if(u){if(o=$E(s),!c)return Zg(s,o)}else{var p=va(s),f=p==vm||p==wP;if(Ta(s))return hm(s,c);if(p==ym||p==Sm||f&&!i){if(o=d||f?{}:Tm(s),!c)return d?wE(s,TE(o,s)):bE(s,fE(o,s))}else{if(!de[p])return i?s:{};o=lP(s,p,c)}}a||(a=new ms);var T=a.get(s);if(T)return T;a.set(s,o),SP(s)?s.forEach(function(_){o.add(so(_,t,e,_,s,a))}):gP(s)&&s.forEach(function(_,M){o.set(M,so(_,t,e,M,s,a))});var E=l?d?RE:zl:d?yc:ml,b=u?void 0:E(s);return lv(b||s,function(_,M){b&&(M=_,_=s[M]),em(o,M,so(_,t,e,M,s,a))}),o}var GP=4;function WP(s){return so(s,GP)}var JP=1,KP=4;function Zu(s){return so(s,JP|KP)}var zP="__lodash_hash_undefined__";function YP(s){return this.__data__.set(s,zP),this}function QP(s){return this.__data__.has(s)}function po(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new lr;++t<e;)this.add(s[t])}po.prototype.add=po.prototype.push=YP;po.prototype.has=QP;function XP(s,t){for(var e=-1,r=s==null?0:s.length;++e<r;)if(t(s[e],e,s))return!0;return!1}function Em(s,t){return s.has(t)}var ZP=1,eb=2;function Pm(s,t,e,r,i,a){var o=e&ZP,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=a.get(s),u=a.get(t);if(l&&u)return l==t&&u==s;var p=-1,f=!0,T=e&eb?new po:void 0;for(a.set(s,t),a.set(t,s);++p<c;){var E=s[p],b=t[p];if(r)var _=o?r(b,E,p,t,s,a):r(E,b,p,s,t,a);if(_!==void 0){if(_)continue;f=!1;break}if(T){if(!XP(t,function(M,A){if(!Em(T,A)&&(E===M||i(E,M,e,r,a)))return T.push(A)})){f=!1;break}}else if(!(E===b||i(E,b,e,r,a))){f=!1;break}}return a.delete(s),a.delete(t),f}function tb(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function eh(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var sb=1,rb=2,ib="[object Boolean]",nb="[object Date]",ab="[object Error]",ob="[object Map]",cb="[object Number]",db="[object RegExp]",lb="[object Set]",ub="[object String]",hb="[object Symbol]",pb="[object ArrayBuffer]",gb="[object DataView]",tp=Ms?Ms.prototype:void 0,Vl=tp?tp.valueOf:void 0;function mb(s,t,e,r,i,a,o){switch(e){case gb:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case pb:return!(s.byteLength!=t.byteLength||!a(new rd(s),new rd(t)));case ib:case nb:case cb:return Tc(+s,+t);case ab:return s.name==t.name&&s.message==t.message;case db:case ub:return s==t+"";case ob:var c=tb;case lb:var d=r&sb;if(c||(c=eh),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=rb,o.set(s,t);var u=Pm(c(s),c(t),r,i,a,o);return o.delete(s),u;case hb:if(Vl)return Vl.call(s)==Vl.call(t)}return!1}var fb=1,Tb=Object.prototype,Sb=Tb.hasOwnProperty;function vb(s,t,e,r,i,a){var o=e&fb,c=zl(s),d=c.length,l=zl(t),u=l.length;if(d!=u&&!o)return!1;for(var p=d;p--;){var f=c[p];if(!(o?f in t:Sb.call(t,f)))return!1}var T=a.get(s),E=a.get(t);if(T&&E)return T==t&&E==s;var b=!0;a.set(s,t),a.set(t,s);for(var _=o;++p<d;){f=c[p];var M=s[f],A=t[f];if(r)var x=o?r(A,M,f,t,s,a):r(M,A,f,s,t,a);if(!(x===void 0?M===A||i(M,A,e,r,a):x)){b=!1;break}_||(_=f=="constructor")}if(b&&!_){var N=s.constructor,$=t.constructor;N!=$&&"constructor"in s&&"constructor"in t&&!(typeof N=="function"&&N instanceof N&&typeof $=="function"&&$ instanceof $)&&(b=!1)}return a.delete(s),a.delete(t),b}var yb=1,sp="[object Arguments]",rp="[object Array]",kc="[object Object]",Eb=Object.prototype,ip=Eb.hasOwnProperty;function Pb(s,t,e,r,i,a){var o=Dt(s),c=Dt(t),d=o?rp:va(s),l=c?rp:va(t);d=d==sp?kc:d,l=l==sp?kc:l;var u=d==kc,p=l==kc,f=d==l;if(f&&Ta(s)){if(!Ta(t))return!1;o=!0,u=!1}if(f&&!u)return a||(a=new ms),o||gl(s)?Pm(s,t,e,r,i,a):mb(s,t,d,e,r,i,a);if(!(e&yb)){var T=u&&ip.call(s,"__wrapped__"),E=p&&ip.call(t,"__wrapped__");if(T||E){var b=T?s.value():s,_=E?t.value():t;return a||(a=new ms),i(b,_,e,r,a)}}return f?(a||(a=new ms),vb(s,t,e,r,i,a)):!1}function vl(s,t,e,r,i){return s===t?!0:s==null||t==null||!Is(s)&&!Is(t)?s!==s&&t!==t:Pb(s,t,e,r,vl,i)}var bb=1,_b=2;function Cb(s,t,e,r){var i=e.length,a=i,o=!r;if(s==null)return!a;for(s=Object(s);i--;){var c=e[i];if(o&&c[2]?c[1]!==s[c[0]]:!(c[0]in s))return!1}for(;++i<a;){c=e[i];var d=c[0],l=s[d],u=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var p=new ms;if(r)var f=r(l,u,d,s,t,p);if(!(f===void 0?vl(u,l,bb|_b,r,p):f))return!1}}return!0}function bm(s){return s===s&&!Zt(s)}function wb(s){for(var t=ml(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,bm(i)]}return t}function _m(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function Rb(s){var t=wb(s);return t.length==1&&t[0][2]?_m(t[0][0],t[0][1]):function(e){return e===s||Cb(e,s,t)}}function kb(s,t){return s!=null&&t in Object(s)}function Mb(s,t,e){t=om(t,s);for(var r=-1,i=t.length,a=!1;++r<i;){var o=Sl(t[r]);if(!(a=s!=null&&e(s,o)))break;s=s[o]}return a||++r!=i?a:(i=s==null?0:s.length,!!i&&Wu(i)&&ju(o,i)&&(Dt(s)||lo(s)))}function Ib(s,t){return s!=null&&Mb(s,t,kb)}var Ab=1,Db=2;function Ob(s,t){return Ku(s)&&bm(t)?_m(Sl(s),t):function(e){var r=sE(e,s);return r===void 0&&r===t?Ib(e,s):vl(t,r,Ab|Db)}}function Nb(s){return function(t){return t==null?void 0:t[s]}}function Lb(s){return function(t){return cm(t,s)}}function Vb(s){return Ku(s)?Nb(Sl(s)):Lb(s)}function xb(s){return typeof s=="function"?s:s==null?Fu:typeof s=="object"?Dt(s)?Ob(s[0],s[1]):Rb(s):Vb(s)}function Ub(s){return function(t,e,r){for(var i=-1,a=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(a[d],d,a)===!1)break}return t}}var $b=Ub();const Bb=$b;var Hb=function(){return fs.Date.now()};const xl=Hb;var Fb="Expected a function",qb=Math.max,jb=Math.min;function th(s,t,e){var r,i,a,o,c,d,l=0,u=!1,p=!1,f=!0;if(typeof s!="function")throw new TypeError(Fb);t=Nh(t)||0,Zt(e)&&(u=!!e.leading,p="maxWait"in e,a=p?qb(Nh(e.maxWait)||0,t):a,f="trailing"in e?!!e.trailing:f);function T(K){var Z=r,Ue=i;return r=i=void 0,l=K,o=s.apply(Ue,Z),o}function E(K){return l=K,c=setTimeout(M,t),u?T(K):o}function b(K){var Z=K-d,Ue=K-l,es=t-Z;return p?jb(es,a-Ue):es}function _(K){var Z=K-d,Ue=K-l;return d===void 0||Z>=t||Z<0||p&&Ue>=a}function M(){var K=xl();if(_(K))return A(K);c=setTimeout(M,b(K))}function A(K){return c=void 0,f&&r?T(K):(r=i=void 0,o)}function x(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function N(){return c===void 0?o:A(xl())}function $(){var K=xl(),Z=_(K);if(r=arguments,i=this,d=K,Z){if(c===void 0)return E(d);if(p)return clearTimeout(c),c=setTimeout(M,t),T(d)}return c===void 0&&(c=setTimeout(M,t)),o}return $.cancel=x,$.flush=N,$}function Xl(s,t,e){(e!==void 0&&!Tc(s[t],e)||e===void 0&&!(t in s))&&Gu(s,t,e)}function Gb(s){return Is(s)&&vc(s)}function Zl(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function Wb(s){return Sc(s,yc(s))}function Jb(s,t,e,r,i,a,o){var c=Zl(s,e),d=Zl(t,e),l=o.get(d);if(l){Xl(s,e,l);return}var u=a?a(c,d,e+"",s,t,o):void 0,p=u===void 0;if(p){var f=Dt(d),T=!f&&Ta(d),E=!f&&!T&&gl(d);u=d,f||T||E?Dt(c)?u=c:Gb(c)?u=Zg(c):T?(p=!1,u=hm(d,!0)):E?(p=!1,u=fm(d,!0)):u=[]:dE(d)||lo(d)?(u=c,lo(c)?u=Wb(c):(!Zt(c)||qu(c))&&(u=Tm(d))):p=!1}p&&(o.set(d,u),i(u,d,r,a,o),o.delete(d)),Xl(s,e,u)}function Cm(s,t,e,r,i){s!==t&&Bb(t,function(a,o){if(i||(i=new ms),Zt(a))Jb(s,t,o,e,Cm,r,i);else{var c=r?r(Zl(s,o),a,o+"",s,t,i):void 0;c===void 0&&(c=a),Xl(s,o,c)}},yc)}function Kb(s,t,e){for(var r=-1,i=s==null?0:s.length;++r<i;)if(e(t,s[r]))return!0;return!1}var zb="[object Map]",Yb="[object Set]",Qb=Object.prototype,Xb=Qb.hasOwnProperty;function Zb(s){if(s==null)return!0;if(vc(s)&&(Dt(s)||typeof s=="string"||typeof s.splice=="function"||Ta(s)||gl(s)||lo(s)))return!s.length;var t=va(s);if(t==zb||t==Yb)return!s.size;if(pl(s))return!am(s).length;for(var e in s)if(Xb.call(s,e))return!1;return!0}function e_(s,t){return vl(s,t)}var t_=_v(function(s,t,e){Cm(s,t,e)});const mr=t_;var s_=1/0,r_=pn&&1/eh(new pn([,-0]))[1]==s_?function(s){return new pn(s)}:ZS;const i_=r_;var n_=200;function wm(s,t,e){var r=-1,i=mv,a=s.length,o=!0,c=[],d=c;if(e)o=!1,i=Kb;else if(a>=n_){var l=t?null:i_(s);if(l)return eh(l);o=!1,i=Em,d=new po}else d=t?[]:c;e:for(;++r<a;){var u=s[r],p=t?t(u):u;if(u=e||u!==0?u:0,o&&p===p){for(var f=d.length;f--;)if(d[f]===p)continue e;t&&d.push(p),c.push(u)}else i(d,p,e)||(d!==c&&d.push(p),c.push(u))}return c}function a_(s){return s&&s.length?wm(s):[]}function o_(s,t){return s&&s.length?wm(s,xb(t)):[]}function Bc(s){const t={};return typeof(s==null?void 0:s.code)=="number"&&(t.code=s.code),typeof(s==null?void 0:s.code)=="string"&&(t.code=s.code.substring(0,100)),typeof(s==null?void 0:s.name)=="string"&&(t.name=s.name.substring(0,500)),typeof(s==null?void 0:s.message)=="string"&&(t.message=s.message.substring(0,500)),typeof(s==null?void 0:s.reason)=="string"&&(t.reason=s.reason.substring(0,500)),typeof(s==null?void 0:s.stack)=="string"&&(t.stack=s.stack.substring(0,500)),t}const c_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},np={STAGING:"staging",PROD:"prod"},Fa={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},d_={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,connectedMeetings:!0,devTools:{logs:!1}};function ya(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function l_({baseURI:s}){return s.includes("staging.realtime")?np.STAGING:np.PROD}function gn({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function u_(s){const t=s.getValue("baseURI");return{location:gn({servicePrefix:"location",baseURI:t}),locationLegacy:gn({servicePrefix:"location-legacy",baseURI:t}),daCollector:gn({servicePrefix:"da-collector",baseURI:t})}}const h_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m16.242 2.932 4.826 4.826a2.75 2.75 0 0 1-.715 4.404l-4.87 2.435a.75.75 0 0 0-.374.426l-1.44 4.166a1.25 1.25 0 0 1-2.065.476L8.5 16.561 4.06 21H3v-1.06l4.44-4.44-3.105-3.104a1.25 1.25 0 0 1 .476-2.066l4.166-1.44a.75.75 0 0 0 .426-.373l2.435-4.87a2.75 2.75 0 0 1 4.405-.715Zm3.766 5.886-4.826-4.826a1.25 1.25 0 0 0-2.002.325l-2.435 4.871a2.25 2.25 0 0 1-1.278 1.12l-3.789 1.31 6.705 6.704 1.308-3.789a2.25 2.25 0 0 1 1.12-1.277l4.872-2.436a1.25 1.25 0 0 0 .325-2.002Z" fill="currentColor"/></svg>',p_='<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z" fill="currentColor"></path></svg>',Mc=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(a=>{a(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((a,o)=>{r.onload=()=>{a(r),window.URL.revokeObjectURL(i)},r.onerror=()=>{o(),window.URL.revokeObjectURL(i)},r.src=i})},ri={logs:"https://api.realtime.cloudflare.com/logs/otel/logs",mock:{url:"https://api.realtime.cloudflare.com/mock",domain:"mock.realtime.cloudflare.com",app:"https://examples.realtime.cloudflare.com/meeting",stagingApp:"https://examples.staging.realtime.cloudflare.com/meeting"},apiBase:{prod:"https://api.realtime.cloudflare.com",staging:"https://api.staging.realtime.cloudflare.com",prodAlternate:"https://api.realtime.cloudflare.com"},baseURI:{prod:"realtime.cloudflare.com",staging:"staging.realtime.cloudflare.com"}},g_=["b3924730-93a3-4561-a9e5-441fb860aadb","f3eeb01c-13d9-4d89-ade4-62acbe36a91b","0b80d104-96aa-4de9-b907-2af213aecee8","b1f57ddb-02d3-43f9-9d19-b87ae060d754","0ea29cac-8161-4cb4-ac22-24b98a2d0ac0","ae3c467c-f261-4307-8a32-11454edb8619","f4fc4c6a-976e-4261-b063-c5a5fefe1fd7","2479fcba-5032-415e-96b9-0d789dbe6723","b340c4f8-43bc-4edb-a54c-5ab083bd9b16","b7703581-6e68-4bc1-bf1e-c95b3d61930a","f4776519-87bb-4d2c-b801-25ac11f96ac5","80a57014-1efe-44f8-b929-b8fca1cf18a1","4f43a422-f420-40f0-968e-c0515fb73c47","cd18cbda-0c13-41e5-a881-e99ef2f00995","da1258f4-666a-48fc-ab3b-21f69c17bddd","10ad9660-3bec-43f9-8304-acd5d4284180","ff830eaa-8c28-44b6-92de-527315f24552","32a8de63-bd77-4e2d-bd04-0048a3dbdf9c","e0d26ea8-066c-47bb-b0cf-57b79d68346a","3830f724-13ee-487f-b62f-2f039d76a09e","54c140a4-e4ff-402b-85d1-ce23182ad3e3","49f9e74a-bf03-4aac-a9c2-3db9f8fdfa41","7f11749e-d90b-4e41-be70-cc9f80641129","f7174bfd-c67c-4ee1-891f-4329333a28f8","e4d08973-cba5-434f-b38a-fc7908a0ea48","31e11e56-1705-4b52-963a-2cfa4af80142","ec8139f6-fe0f-4c09-a030-b97728c4c451","46a9290b-3d63-4ded-94a4-ab3cca22eec0","39d1d29a-aa47-444a-a77c-d075bca8a08a","531356db-519b-4d0f-a5da-086cc02bbafa","546de108-91aa-4bf8-a535-18110c3f57d8","6c7371c7-bc57-4cf9-8ab6-e377e8cedc0b","e8882a98-6276-4db0-b3a8-a216259dfb31","66292cea-49de-4acb-b695-d77153897a23","5f1d6cab-a385-48df-b6c9-a7f48ed7c58d","bdb1f51a-5eb8-4664-95b3-ee933075194e","6615e115-f38b-4cbb-bd50-acadaa16380e","4a1e79f2-0aab-43d4-ab15-d3a42b3ebd1f"],m_=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/;function Rm(s){var r,i,a;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(ri.baseURI.staging)),e=!!((a=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&a.logs);return t||e}function f_(s,t){var r;const e=(r=s==null?void 0:s.getValue("telemetry"))==null?void 0:r.logLevel;if(e==="off")return!1;if(e!=="all"){const i=["debug","log","info","warn","error"],a=i.indexOf(t.toLowerCase()),o=i.indexOf(e);if(a<o)return!1}return!0}function km(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var a;if([null,void 0,NaN].includes(s[r])||t&&(((a=t.match(/\./g))==null?void 0:a.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?km(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function ap(s,t,e={},r=""){const i={};try{const a=JSON.stringify(e),o=JSON.parse(a),c=km(o,r),d=JSON.stringify(c);if(!(t==null?void 0:t.startsWith("[SDP]"))&&d.length>5e3){const u=`Log named: "${t}" is trying to log an flattened object of size
|
|
5
|
-
${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw
|
|
6
|
-
${this.message}`;try{let d=a&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const l=Fr.getContext(Fr.getMostRecentPeerId());if(l){const u=l.getValue("onError");try{u(this)}catch(p){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(d){}}}function Ic(s,t,e,r){if(r instanceof R)throw r;if(r instanceof t){const i=new R(r.message,e);throw i.stack=r.stack,i}else throw r}function op(s,t,e){if(!s.value){const i=s.get,a=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Ic(this,t,e,o)}}),a&&(s.set=function(o){try{return a.apply(this,[o])}catch(c){Ic(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const a=r.apply(this,i);return a&&a instanceof Promise?a.catch(o=>{Ic(this,t,e,o)}):a}catch(a){Ic(this,t,e,a)}},s}function y_(s,t){return(e,r,i)=>{if(i)return op(i,s,t);for(const a of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,a);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,a,op(o,s,t))}}}const rt=s=>y_(Error,s);var rr=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(rr||{}),H=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(H||{}),zp;typeof process!="undefined"&&(zp=process==null?void 0:process.env)!=null&&zp.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var Mm=[-2,-1,0,1,2],E_=[0,1,2,3,4];function P_(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t=`0x${s[1]}${s[1]}`,e=`0x${s[2]}${s[2]}`,r=`0x${s[3]}${s[3]}`):s.length>6&&(t=`0x${s[1]}${s[2]}`,e=`0x${s[3]}${s[4]}`,r=`0x${s[5]}${s[6]}`),[+t,+e,+r]}var b_=(s,t,e)=>{let r,i,a;if(t==0)r=i=a=e;else{const o=(l,u,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?l+(u-l)*6*p:p<.5?u:p<.6666666666666666?l+(u-l)*(.6666666666666666-p)*6:l),c=e<.5?e*(1+t):e+t-e*t,d=2*e-c;r=o(d,c,s+1/3),i=o(d,c,s),a=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(a*255)]},__=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let a,o;const c=(r+i)/2;if(r==i)a=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:a=(t-e)/d+(t<e?6:0);break;case t:a=(e-s)/d+2;break;case e:a=(s-t)/d+4;break}a/=6}return[a,o,c]},C_=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},Im=(s,t=Mm,e=.4)=>{const r=[],[i,a,o]=P_(s),[c,d,l]=__(i,a,o),u=Math.round(l*100);u>70?e=.8:u>60?e=.9:u<10?e=.075:u<42&&(e=.3);const p=t.findIndex(_=>_===0);if(p===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const f=5-p,T=p+1,E=(100-u)/f,b=u/T;for(const _ of t){let M;_<0?M=u+_*b*e:_>0?M=u+_*E*e:M=u;const[A,x,N]=b_(c,d,M/100);r.push(C_(A,x,N))}return r},cp={dark:{background:{1e3:"#252525",900:"#2F2F2F",800:"#323232",700:"#3E3E3E",600:"#4A4A4A"},text:"#F5F5F5","video-bg":"#1C1C1C"},light:{background:{1e3:"#FFFFFF",900:"#F5F5F5",800:"#EBEBEB",700:"#E0E0E0",600:"#D6D6D6"},text:"#111111","text-on-brand":"#ffffff","video-bg":"#DADADA"}},w_=s=>{const[t,e,r,i,a]=Im(s,Mm);return{300:t,400:e,500:r,600:i,700:a}},R_=s=>{if(s==="#FFFFFF")return cp.light.background;if(s==="#000000")return cp.dark.background;const[t,e,r,i,a]=Im(s,E_);return{1e3:t,900:e,800:r,700:i,600:a}},k_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:w_("#2160FD"),background:R_("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Am(){return Zu(k_)}var M_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:Am(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function I_(){return Zu(M_)}var A_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:Am(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function sh(){return Zu(A_)}function D_(){ge.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(a=>{var o;return(o=a.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var C=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(C||{});class Pa extends st.EventEmitter{constructor(e){super();h(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}return super.on(e,r)}addListener(e,r){var i;try{const a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Lt extends st.EventEmitter{constructor(e){super();h(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}return super.on(e,r)}addListener(e,r){var i;try{const a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}function O_(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(i=>i.charAt(0)).join("").toUpperCase()}const dp=1080,lp=1920,N_=(s,t,e,r,i,a)=>{let o=.5,c=.5;const d=i,l=a,u=Math.min(e/d,r/l);let p=d*u,f=l*u,T,E,b,_,M=1;return p<e&&(M=e/p),Math.abs(M-1)<1e-14&&f<r&&(M=r/f),p*=M,f*=M,b=d/(p/e),_=l/(f/r),T=(d-b)*o,E=(l-_)*c,T<0&&(T=0),E<0&&(E=0),b>d&&(b=d),_>l&&(_=l),[T,E,b,_,s,t,e,r]};var Bt,ii,Ye,Ht,Pe,is,xs,it,ke,Sn,vn,Us,yn;const Ph=class extends Lt{constructor(e,r,i,a){const o=e.getValue("logger");super(o);g(this,Bt,void 0);g(this,ii,void 0);g(this,Ye,void 0);g(this,Ht,void 0);g(this,Pe,{height:dp,width:lp});g(this,is,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,xs,void 0);g(this,it,{});g(this,ke,void 0);g(this,Sn,void 0);g(this,vn,void 0);g(this,Us,void 0);g(this,yn,!1);h(this,"cleanupEventListeners",()=>{n(this,ii).unsubscribe("stageStatus",this.handlePipMediaControls),n(this,ke).removeListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,ke).removeListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,ke).removeListener("roomLeft",()=>this.disable())});h(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});h(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});h(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});h(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});h(this,"eventCallback",e=>{e==="CAMERA"&&(n(this,ke).videoEnabled?n(this,ke).disableVideo():n(this,ke).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(n(this,ke).audioEnabled?n(this,ke).disableAudio():n(this,ke).enableAudio(),this.emit("micToggled")),e==="END"&&(n(this,ii).getValue("peerSessionStore").emit(C.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});h(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});h(this,"animate",()=>{if(!this.isActive&&n(this,Us)==="active"){this.disable(!0);return}n(this,it)!==void 0&&this.paintCanvas(),n(this,xs)!==void 0&&m(this,xs,requestAnimationFrame(()=>this.animate()))});h(this,"disable",(e=!1)=>{m(this,Us,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(n(this,xs)),e!==!0&&document.body.removeChild(n(this,Ye)),m(this,xs,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});m(this,ii,e),m(this,Us,"idle"),m(this,ke,r),m(this,is,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),a&&this.setupIcon("handRaise",a)}static async _init(e,r){let i,a;try{i=await Mc(h_),a=await Mc(p_)}catch(o){}return new Ph(e,r,i,a)}async setupIcon(e,r){switch(e){case"handRaise":m(this,vn,r);break;case"pin":m(this,Sn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":m(this,vn,await Mc(r));break;case"pin":m(this,Sn,await Mc(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),a=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(a)},r.src=a})}createVideoContainer(){m(this,Ye,document.createElement("div")),n(this,Ye).style.width="0.1px",n(this,Ye).style.height="0.1px",n(this,Ye).style.overflow="hidden",n(this,Ye).style.position="absolute",n(this,Ye).style.bottom="0",n(this,Ye).style.right="0",n(this,Ye).style.opacity="0",n(this,Ye).appendChild(n(this,Ht))}setupEventListeners(){n(this,ii).subscribe("stageStatus",this.handlePipMediaControls),n(this,ke).addListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,ke).addListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,ke).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=n(this,Pe).height,e.width=n(this,Pe).width,m(this,Bt,e)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||n(this,ke).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||n(this,ke).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(n(this,it)).reduce((i,a)=>(i[a.pinned?"pinned":"regular"].push(a),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,a){if(n(this,Bt)===void 0)return;const o=n(this,Bt).getContext("2d"),c=n(this,Bt).width,d=0,l=0,u=r-d*2,p=i-d*2,f=Math.floor(c/u),T=Math.floor(e/f),b=e%f*(u+d)+d,_=T*(p+d)+d,{displayText:M,image:A}=a!=null?a:{};o.fillStyle=M||A?n(this,is).videoBackground:n(this,is).background,o.strokeStyle=n(this,is).brand,o.beginPath(),o.moveTo(b+l,_),o.arcTo(b+u,_,b+u,_+l,l),o.arcTo(b+u,_+p,b+u-l,_+p,l),o.arcTo(b,_+p,b,_+p-l,l),o.arcTo(b,_,b+l,_,l),o.closePath(),o.fill(),o.stroke();const x=u/6,N=u/2+b,$=p/2+_;o.save(),(M||A)&&(o.beginPath(),o.arc(N,$,x,0,Math.PI*2),o.fillStyle=n(this,is).brand,o.fill(),A?(o.clip(),o.drawImage(A,N-x,$-x,x*2,x*2),o.restore()):M&&(o.fillStyle=n(this,is).textOnBrand,o.font=`${x/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(M,N,$)),this.drawIcons(a,b,_,Math.max(u,p)))}drawIcons(e,r,i,a){const o=Math.min(Math.max(a*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,p=f=>{const T=n(this,Bt).getContext("2d");T.save(),T.fillStyle=n(this,is).background,T.beginPath(),T.moveTo(l+d,u),T.arcTo(l+o,u,l+o,u+d,d),T.arcTo(l+o,u+o,l+o-d,u+o,d),T.arcTo(l,u+o,l,u+o-d,d),T.arcTo(l,u,l+d,u,d),T.closePath(),T.fill(),typeof f=="string"?(T.font=`${o/1.5}px sans-serif`,T.fillStyle=n(this,is).text,T.textAlign="center",T.textBaseline="top",T.fillText(f,o/2+l,u+c)):T.drawImage(f,l+c,u+c,o-c*2,o-c*2),l+=o+c,T.restore()};e.pinned&&p(n(this,Sn)),e.handRaised&&p(n(this,vn)),e.reaction&&p(e.reaction)}drawTile(e,r,i){var l,u;if(n(this,Bt)===void 0)return;const a=n(this,Bt).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<n(this,Pe).height-5;){let p=0;for(;p<n(this,Pe).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const f=o[d].element,[T,E,b,_,M,A,x,N]=N_(p,c,e,r,f.videoWidth,f.videoHeight);((u=f==null?void 0:f.classList)==null?void 0:u.contains("mirror"))?(a.save(),a.scale(-1,1),a.drawImage(f,T,E,b,_,-1*M,A,-1*x,N),a.restore()):a.drawImage(f,T,E,b,_,M,A,x,N),this.drawIcons(o[d],M,A,Math.max(x,N))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,p+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[n(this,Pe).width,n(this,Pe).height];case 2:return[Math.floor(n(this,Pe).width/2),n(this,Pe).height];case 3:case 4:return[Math.floor(n(this,Pe).width/2),Math.floor(n(this,Pe).height/2)];case 5:case 6:return[Math.floor(n(this,Pe).width/3),Math.floor(n(this,Pe).height/2)];case 7:case 8:case 9:return[Math.floor(n(this,Pe).width/3),Math.floor(n(this,Pe).height/3)];default:return[Math.floor(n(this,Pe).width/3),Math.floor(n(this,Pe).height/2)]}}paintCanvas(){let e=this.getSources().length;e!==1&&(e=e%2>0?e+1:e);const[r,i]=this.calcGridElemSize(e);this.drawTile(r,i,e)}isSupported(){var e;return!!window.chrome&&document.pictureInPictureEnabled&&((e=n(this,ke).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(m(this,yn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),n(this,Ye))try{document.body.removeChild(n(this,Ye))}catch(e){}this.removeAllSources(),m(this,Bt,void 0),m(this,Ht,void 0),m(this,xs,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(n(this,yn))return;m(this,yn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");m(this,Pe,{height:e!=null?e:dp,width:r!=null?r:lp}),i.height=n(this,Pe).height,i.width=n(this,Pe).width,i.autoplay=!0,i.muted=!0,i.srcObject=n(this,Bt).captureStream(24),m(this,Ht,i),n(this,Ht).onloadedmetadata=()=>{try{this.emit("pipStarted"),n(this,Ht).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(a){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){n(this,it)[e]!==void 0&&(n(this,it)[e].enabled=!0)}disableSource(e){n(this,it)[e]!==void 0&&(n(this,it)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const a=await(await fetch(r)).blob(),o=window.URL.createObjectURL(a);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(a){this.logger.error("Pip::GenerateAvatar",{error:a})}}addSource(e,r,i,a=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),n(this,it)[e]={id:e,element:r,enabled:i,pinned:a,displayText:o?O_(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised,reaction:r.reaction}});const i=n(this,it)[e];i&&(n(this,it)[e]={...i,...r})}removeSource(e){delete n(this,it)[e]}removePinnedSource(){Object.values(n(this,it)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){m(this,it,{})}enable(){m(this,Us,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",n(this,ke).videoEnabled),this.updateMediaSession("MIC",n(this,ke).audioEnabled),document.body.appendChild(n(this,Ye)),m(this,xs,requestAnimationFrame(()=>this.animate())),n(this,Ht).onloadedmetadata=()=>{n(this,Ht).requestPictureInPicture().then(()=>{m(this,Us,"active")})},n(this,Ht).readyState===4&&n(this,Ht).requestPictureInPicture().then(()=>{m(this,Us,"active")})}};let eu=Ph;Bt=new WeakMap,ii=new WeakMap,Ye=new WeakMap,Ht=new WeakMap,Pe=new WeakMap,is=new WeakMap,xs=new WeakMap,it=new WeakMap,ke=new WeakMap,Sn=new WeakMap,vn=new WeakMap,Us=new WeakMap,yn=new WeakMap;var or;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(or||(or={}));var ir;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(ir||(ir={}));class L_ extends S.MessageType{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const Dm=new L_;class V_ extends S.MessageType{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const x_=new V_;class U_ extends S.MessageType{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new U_;class $_ extends S.MessageType{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",or]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const Ts=new $_;class B_ extends S.MessageType{constructor(){super("media.ProducerPayload",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const H_=new B_;class F_ extends S.MessageType{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>Ts},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>H_}])}}const q_=new F_;class j_ extends S.MessageType{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const G_=new j_;class W_ extends S.MessageType{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Om=new W_;class J_ extends S.MessageType{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts}])}}const K_=new J_;class z_ extends S.MessageType{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts}])}}new z_;class Y_ extends S.MessageType{constructor(){super("media.NestedScore",[{no:1,name:"encoding_idx",kind:"scalar",T:5},{no:2,name:"rid",kind:"scalar",T:9},{no:3,name:"score",kind:"scalar",T:5},{no:4,name:"ssrc",kind:"scalar",T:3,L:0}])}}const Q_=new Y_;class X_ extends S.MessageType{constructor(){super("media.ProducerTrack",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9},{no:3,name:"stream_id",kind:"scalar",T:9}])}}const Z_=new X_;class eC extends S.MessageType{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new eC;class tC extends S.MessageType{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new tC;class sC extends S.MessageType{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",ir]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"codec",kind:"message",T:()=>Dm}])}}const Ec=new sC;class rC extends S.MessageType{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ec},{no:3,name:"producer_track",kind:"message",T:()=>Z_},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const iC=new rC;class nC extends S.MessageType{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>iC}}])}}const Nm=new nC;class aC extends S.MessageType{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>hp},{no:2,name:"receiver",kind:"message",T:()=>hp}])}}const Lm=new aC;class oC extends S.MessageType{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Dm},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>x_}])}}const up=new oC;class cC extends S.MessageType{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>up},{no:2,name:"video",kind:"message",T:()=>up}])}}const hp=new cC;class dC extends S.MessageType{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const lC=new dC;class uC extends S.MessageType{constructor(){super("media.Simulcast",[{no:1,name:"preferred_rid",kind:"scalar",opt:!0,T:9},{no:2,name:"priority_ordering",kind:"scalar",opt:!0,T:9},{no:3,name:"rid_not_available",kind:"scalar",opt:!0,T:9}])}}const Vm=new uC;class hC extends S.MessageType{constructor(){super("media.edge.GeoLocation",[{no:1,name:"latitude",kind:"scalar",T:2},{no:2,name:"longitude",kind:"scalar",T:2},{no:3,name:"region",kind:"scalar",opt:!0,T:9}])}}const pC=new hC;class gC extends S.MessageType{constructor(){super("media.edge.PeerJoinRequest",[{no:1,name:"display_name",kind:"scalar",opt:!0,T:9},{no:2,name:"prejoined",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:5,name:"preset",kind:"scalar",opt:!0,T:12},{no:6,name:"user_id",kind:"scalar",opt:!0,T:9},{no:7,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:8,name:"location",kind:"message",T:()=>pC},{no:9,name:"capabilities",kind:"message",T:()=>Lm}])}}const mC=new gC;class fC extends S.MessageType{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const TC=new fC;class SC extends S.MessageType{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const vC=new SC;class yC extends S.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new yC;class EC extends S.MessageType{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>lC},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>Vm}])}}const PC=new EC;class bC extends S.MessageType{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>PC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const _C=new bC;class CC extends S.MessageType{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>Vm},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const wC=new CC;class RC extends S.MessageType{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>wC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const kC=new RC;class MC extends S.MessageType{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>Ts},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const IC=new MC;class AC extends S.MessageType{constructor(){super("media.edge.SelectedPeersRequest",[])}}new AC;class DC extends S.MessageType{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const OC=new DC;class NC extends S.MessageType{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Ac=new NC;class LC extends S.MessageType{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new LC;class VC extends S.MessageType{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const xC=new VC;class UC extends S.MessageType{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>Ts},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const $C=new UC;class BC extends S.MessageType{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new BC;class HC extends S.MessageType{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const xm=new HC;class FC extends S.MessageType{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const qC=new FC;class jC extends S.MessageType{constructor(){super("media.edge.HostMediaControlForPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"audio",kind:"scalar",T:8},{no:3,name:"video",kind:"scalar",T:8},{no:4,name:"scree_share",kind:"scalar",T:8}])}}const GC=new jC;class WC extends S.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerRequest",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8}])}}const JC=new WC;class KC extends S.MessageType{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const zC=new KC;class YC extends S.MessageType{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const QC=new YC;class XC extends S.MessageType{constructor(){super("media.edge.EmptyResponse",[])}}new XC;class ZC extends S.MessageType{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>Ec},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>Lm}])}}const Um=new ZC;class ew extends S.MessageType{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const tu=new ew;class tw extends S.MessageType{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const sw=new tw;class rw extends S.MessageType{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>sw}])}}const pp=new rw;class iw extends S.MessageType{constructor(){super("media.edge.PeerJoinResponse",[])}}new iw;class nw extends S.MessageType{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>zC},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Um},{no:3,name:"selected_peers",kind:"message",T:()=>tu},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const su=new nw;class aw extends S.MessageType{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const ow=new aw;class cw extends S.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Nm}])}}new cw;class dw extends S.MessageType{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Nm},{no:3,name:"description",kind:"message",T:()=>Ts}])}}const lw=new dw;class uw extends S.MessageType{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>Ts}])}}const hw=new uw;class pw extends S.MessageType{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>Q_}])}}new pw;class gw extends S.MessageType{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new gw;class mw extends S.MessageType{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new mw;class fw extends S.MessageType{constructor(){super("media.edge.ProducerToggleResponse",[])}}new fw;class Tw extends S.MessageType{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new Tw;class Sw extends S.MessageType{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Ts}])}}const vw=new Sw;class yw extends S.MessageType{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Ts}])}}const Ew=new yw;class Pw extends S.MessageType{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new Pw;class bw extends S.MessageType{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new bw;class _w extends S.MessageType{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new _w;class Cw extends S.MessageType{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const ww=new Cw;class Rw extends S.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const kw=new Rw;class Mw extends S.MessageType{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Iw=new Mw;class Aw extends S.MessageType{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Um}])}}const gp=new Aw;class Dw extends S.MessageType{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const mp=new Dw;class Ow extends S.MessageType{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>mp},{no:3,name:"screenshare",kind:"message",T:()=>mp}])}}const Nw=new Ow;class Lw extends S.MessageType{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Om},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>Nw}])}}new Lw;class Vw extends S.MessageType{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ec}])}}const xw=new Vw;class Uw extends S.MessageType{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ec},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const fp=new Uw;class $w extends S.MessageType{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ec}])}}const Bw=new $w;class Hw extends S.MessageType{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const ru=new Hw;class Fw extends S.MessageType{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Tp=new Fw;class qw extends S.MessageType{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new qw;class jw extends S.MessageType{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new jw;class Gw extends S.MessageType{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Gw;class Ww extends S.MessageType{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new Ww;class Jw extends S.MessageType{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new Jw;class Kw extends S.MessageType{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new Kw;class zw extends S.MessageType{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const Ul=new zw;class Yw extends S.MessageType{constructor(){super("socket.api.BaseSocketHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9}])}}new Yw;class Qw extends S.MessageType{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const Xw=new Qw;var ji;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(ji||(ji={}));var er;(function(s){s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.ON_STAGE=1]="ON_STAGE",s[s.APPROVED_STAGE=2]="APPROVED_STAGE",s[s.REQUESTED_STAGE=3]="REQUESTED_STAGE",s[s.OFF_STAGE=4]="OFF_STAGE"})(er||(er={}));var iu;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(iu||(iu={}));var nu;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(nu||(nu={}));var id;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(id||(id={}));class Zw extends S.MessageType{constructor(){super("socket.room.PeerFlags",[{no:1,name:"preset_name",kind:"scalar",T:9},{no:2,name:"recorder_type",kind:"scalar",T:9},{no:3,name:"hidden_participant",kind:"scalar",T:8}])}}const eR=new Zw;class tR extends S.MessageType{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",er,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>eR}])}}const yl=new tR;class sR extends S.MessageType{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>yl}])}}const tn=new sR;class rR extends S.MessageType{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",er,"STAGE_TYPE_"]}])}}const Sp=new rR;class iR extends S.MessageType{constructor(){super("socket.room.RoomPeersInfoRequest",[{no:1,name:"seach_query",kind:"scalar",T:9},{no:2,name:"limit",kind:"scalar",T:5},{no:3,name:"offset",kind:"scalar",T:5}])}}const nR=new iR;class aR extends S.MessageType{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>yl}])}}const $l=new aR;class oR extends S.MessageType{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const vp=new oR;class cR extends S.MessageType{constructor(){super("socket.room.Room",[{no:1,name:"room_id",kind:"scalar",T:9},{no:2,name:"title",kind:"scalar",T:9},{no:4,name:"created_at",kind:"scalar",T:4,L:2},{no:5,name:"active_recordings",kind:"message",repeat:1,T:()=>lR},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const $m=new cR;class dR extends S.MessageType{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",ji]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const lR=new dR;class uR extends S.MessageType{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>$m}])}}const yp=new uR;class hR extends S.MessageType{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Bm=new hR;class pR extends S.MessageType{constructor(){super("socket.room.UpdatePeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9}])}}new pR;class gR extends S.MessageType{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>yl},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:5,name:"use_hive",kind:"scalar",opt:!0,T:8},{no:6,name:"preset",kind:"scalar",opt:!0,T:12},{no:7,name:"capabilities",kind:"enum",repeat:1,T:()=>["socket.room.Capabilities",id,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const mR=new gR;class fR extends S.MessageType{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>yl},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const TR=new fR;class SR extends S.MessageType{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>$m}])}}new SR;class vR extends S.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new vR;class yR extends S.MessageType{constructor(){super("socket.room.ServiceError",[{no:1,name:"message",kind:"scalar",opt:!0,T:9},{no:2,name:"code",kind:"scalar",opt:!0,T:9}])}}const rh=new yR;class ER extends S.MessageType{constructor(){super("socket.room.ConnectedMeetingPeer",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:5,name:"display_picture_url",kind:"scalar",opt:!0,T:9}])}}const PR=new ER;class bR extends S.MessageType{constructor(){super("socket.room.ConnectedMeetingDump",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>PR}])}}const Ep=new bR;class _R extends S.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>Ep},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>Ep}])}}const CR=new _R;class wR extends S.MessageType{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const RR=new wR;class kR extends S.MessageType{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>RR}])}}const MR=new kR;class IR extends S.MessageType{constructor(){super("socket.room.CreateRoomResponsePayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>rh}])}}const AR=new IR;class DR extends S.MessageType{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>AR}])}}const Pp=new DR;class OR extends S.MessageType{constructor(){super("socket.room.UpdateRoomRequestPayload",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9}])}}const NR=new OR;class LR extends S.MessageType{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>NR}])}}new LR;class VR extends S.MessageType{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const xR=new VR;class UR extends S.MessageType{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>xR}])}}const $R=new UR;class BR extends S.MessageType{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>qR}])}}const HR=new BR;class FR extends S.MessageType{constructor(){super("socket.room.DisableConnectedRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"status",kind:"scalar",opt:!0,T:9},{no:3,name:"title",kind:"scalar",opt:!0,T:9},{no:4,name:"error",kind:"message",T:()=>rh}])}}const qR=new FR;class jR extends S.MessageType{constructor(){super("socket.room.MovePeerPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"preset_id",kind:"scalar",opt:!0,T:9}])}}const GR=new jR;class WR extends S.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsRequest",[{no:1,name:"source_meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"destination_meeting_id",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>GR}])}}const JR=new WR;class KR extends S.MessageType{constructor(){super("socket.room.MovedPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>rh}])}}const Hm=new KR;class zR extends S.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Hm}])}}new zR;class YR extends S.MessageType{constructor(){super("socket.room.TransferPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"auth_token",kind:"scalar",opt:!0,T:9}])}}const QR=new YR;class XR extends S.MessageType{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>tk}])}}const ZR=new XR;class ek extends S.MessageType{constructor(){super("socket.room.AddedParticipant",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const tk=new ek;class sk extends S.MessageType{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Fm=new sk;class rk extends S.MessageType{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"ids",kind:"scalar",repeat:2,T:9},{no:5,name:"broadcast_type",kind:"enum",opt:!0,T:()=>["socket.room.BroadcastType",nu,"BROADCAST_TYPE_"]}])}}const qa=new rk;class ik extends S.MessageType{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const nk=new ik;class ak extends S.MessageType{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const ok=new ak;class ck extends S.MessageType{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const dk=new ck;class lk extends S.MessageType{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>dk}])}}const bp=new lk;class uk extends S.MessageType{constructor(){super("socket.room.GetRoomStageStateResponse",[{no:1,name:"on_stage_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"approved_stage_peers",kind:"scalar",repeat:2,T:9},{no:3,name:"requested_stage_peers",kind:"scalar",repeat:2,T:9}])}}const _p=new uk;var au;(function(s){s[s.NONE=0]="NONE",s[s.SKIP=1]="SKIP",s[s.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",s[s.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(au||(au={}));var $r;(function(s){s[s.NONE=0]="NONE",s[s.ALLOWED=1]="ALLOWED",s[s.NOT_ALLOWED=2]="NOT_ALLOWED",s[s.CAN_REQUEST=3]="CAN_REQUEST"})($r||($r={}));class hk extends S.MessageType{constructor(){super("socket.preset.PollsPermissionUpdate",[{no:1,name:"can_create",kind:"scalar",opt:!0,T:8},{no:2,name:"can_vote",kind:"scalar",opt:!0,T:8},{no:3,name:"can_view",kind:"scalar",opt:!0,T:8}])}}const pk=new hk;class gk extends S.MessageType{constructor(){super("socket.preset.PluginsPermissionsUpdate",[{no:1,name:"can_close",kind:"scalar",opt:!0,T:8},{no:2,name:"can_start",kind:"scalar",opt:!0,T:8}])}}const mk=new gk;class fk extends S.MessageType{constructor(){super("socket.preset.PublicChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"text",kind:"scalar",opt:!0,T:8},{no:3,name:"files",kind:"scalar",opt:!0,T:8}])}}const Tk=new fk;class Sk extends S.MessageType{constructor(){super("socket.preset.PrivateChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"can_receive",kind:"scalar",opt:!0,T:8},{no:3,name:"text",kind:"scalar",opt:!0,T:8},{no:4,name:"files",kind:"scalar",opt:!0,T:8}])}}const vk=new Sk;class yk extends S.MessageType{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>Tk},{no:2,name:"private",kind:"message",T:()=>vk}])}}const Ek=new yk;class Pk extends S.MessageType{constructor(){super("socket.preset.ConnectedMeetingPermissionUpdate",[{no:1,name:"can_alter_connected_meetings",kind:"scalar",opt:!0,T:8},{no:2,name:"can_switch_to_parent_meeting",kind:"scalar",opt:!0,T:8},{no:3,name:"can_switch_connected_meetings",kind:"scalar",opt:!0,T:8}])}}const bk=new Pk;class _k extends S.MessageType{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",$r,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",$r,"STREAM_PERMISSION_TYPE_"]}])}}const Bl=new _k;class Ck extends S.MessageType{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Bl},{no:2,name:"audio",kind:"message",T:()=>Bl},{no:3,name:"screenshare",kind:"message",T:()=>Bl}])}}const wk=new Ck;class Rk extends S.MessageType{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>pk},{no:2,name:"plugins",kind:"message",T:()=>mk},{no:3,name:"chat",kind:"message",T:()=>Ek},{no:4,name:"accept_waiting_requests",kind:"scalar",opt:!0,T:8},{no:5,name:"can_accept_production_requests",kind:"scalar",opt:!0,T:8},{no:6,name:"can_edit_display_name",kind:"scalar",opt:!0,T:8},{no:7,name:"can_record",kind:"scalar",opt:!0,T:8},{no:8,name:"can_livestream",kind:"scalar",opt:!0,T:8},{no:9,name:"can_spotlight",kind:"scalar",opt:!0,T:8},{no:10,name:"disable_participant_audio",kind:"scalar",opt:!0,T:8},{no:11,name:"disable_participant_screensharing",kind:"scalar",opt:!0,T:8},{no:12,name:"disable_participant_video",kind:"scalar",opt:!0,T:8},{no:13,name:"kick_participant",kind:"scalar",opt:!0,T:8},{no:14,name:"pin_participant",kind:"scalar",opt:!0,T:8},{no:15,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:16,name:"waiting_room_type",kind:"enum",opt:!0,T:()=>["socket.preset.WaitingRoomType",au,"WAITING_ROOM_TYPE_"]},{no:17,name:"is_recorder",kind:"scalar",opt:!0,T:8},{no:18,name:"recorder_type",kind:"enum",opt:!0,T:()=>["socket.room.RecorderType",iu,"RECORDER_TYPE_"]},{no:19,name:"hidden_participant",kind:"scalar",opt:!0,T:8},{no:20,name:"show_participant_list",kind:"scalar",opt:!0,T:8},{no:21,name:"can_change_participant_permissions",kind:"scalar",opt:!0,T:8},{no:22,name:"connected_meetings",kind:"message",T:()=>bk},{no:23,name:"media",kind:"message",T:()=>wk}])}}const ih=new Rk;class kk extends S.MessageType{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Mk=new kk;class Ik extends S.MessageType{constructor(){super("socket.preset.PeerPreset",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"preset",kind:"scalar",T:12}])}}const Ak=new Ik;class Dk extends S.MessageType{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>Ak}])}}const Ok=new Dk;class Nk extends S.MessageType{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>ih}])}}const qm=new Nk;class Lk extends S.MessageType{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>qm}])}}const Vk=new Lk;class xk extends S.MessageType{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>qm}])}}const Cp=new xk;class Uk extends S.MessageType{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const $k=new Uk;class Bk extends S.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>$k},{no:2,name:"patch",kind:"message",T:()=>ih}])}}new Bk;class Hk extends S.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>ih}])}}new Hk;class Fk extends S.MessageType{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const Gr=new Fk;class qk extends S.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageFilters",[{no:1,name:"pinned",kind:"scalar",oneof:"filters",T:8},{no:2,name:"user_id",kind:"scalar",oneof:"filters",T:9}])}}const jk=new qk;class Gk extends S.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageRoomRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"filters",kind:"message",T:()=>jk}])}}const Wk=new Gk;class Jk extends S.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Gr},{no:2,name:"next",kind:"scalar",T:8}])}}const Kk=new Jk;class zk extends S.MessageType{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Gr}])}}const jm=new zk;class Yk extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const Qk=new Yk;class Xk extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}const Hl=new Xk;class Zk extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const eM=new Zk;class tM extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}const Fl=new tM;class sM extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}new sM;class rM extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}new rM;class iM extends S.MessageType{constructor(){super("socket.chat.EditChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",opt:!0,T:5},{no:3,name:"payload",kind:"scalar",opt:!0,T:9},{no:4,name:"pinned",kind:"scalar",opt:!0,T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const nM=new iM;class aM extends S.MessageType{constructor(){super("socket.chat.PinChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const oM=new aM;class cM extends S.MessageType{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:4,name:"message",kind:"message",T:()=>Gr}])}}const Dc=new cM;class dM extends S.MessageType{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}const Oc=new dM;class lM extends S.MessageType{constructor(){super("socket.chat.DeleteChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const uM=new lM;class hM extends S.MessageType{constructor(){super("socket.chat.DeleteChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Nc=new hM;class pM extends S.MessageType{constructor(){super("socket.chat.SearchChatMessagesRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"search_term",kind:"scalar",T:9}])}}const gM=new pM;class mM extends S.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"channel_index",kind:"scalar",T:9}])}}new mM;class fM extends S.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new fM;class TM extends S.MessageType{constructor(){super("socket.chat.CreateChatChannelRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8}])}}new TM;class SM extends S.MessageType{constructor(){super("socket.chat.UpdateChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:4,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:5,name:"visibility",kind:"scalar",opt:!0,T:9},{no:6,name:"is_direct_message",kind:"scalar",opt:!0,T:8}])}}new SM;class vM extends S.MessageType{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new vM;class yM extends S.MessageType{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new yM;class EM extends S.MessageType{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Gr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const PM=new EM;class bM extends S.MessageType{constructor(){super("socket.chat.ChatChannel",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8},{no:6,name:"latest_message_and_unread_count",kind:"message",T:()=>PM},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const _M=new bM;class CM extends S.MessageType{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>_M}])}}new CM;class wM extends S.MessageType{constructor(){super("socket.chat.ChannelMember",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const RM=new wM;class kM extends S.MessageType{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>RM}])}}new kM;class MM extends S.MessageType{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const IM=new MM;class AM extends S.MessageType{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const DM=new AM;class OM extends S.MessageType{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const NM=new OM;class LM extends S.MessageType{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const VM=new LM;class xM extends S.MessageType{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const UM=new xM;class $M extends S.MessageType{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const BM=new $M;class HM extends S.MessageType{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const FM=new HM;class qM extends S.MessageType{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}const jM=new qM;class GM extends S.MessageType{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const nh=new GM;class WM extends S.MessageType{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>nh}])}}const wp=new WM;class JM extends S.MessageType{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>nh}])}}const KM=new JM;class zM extends S.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>nh}])}}const YM=new zM;class QM extends S.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const XM=new QM;class ZM extends S.MessageType{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const ou=new ZM;class eI extends S.MessageType{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>ou}])}}const tI=new eI;class sI extends S.MessageType{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const Rp=new sI;class rI extends S.MessageType{constructor(){super("socket.plugin.PluginStoreItem",[{no:1,name:"timestamp",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"store_key",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}])}}const iI=new rI;class nI extends S.MessageType{constructor(){super("socket.plugin.PluginStoreResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"store_items",kind:"message",repeat:1,T:()=>iI}])}}const kp=new nI;class aI extends S.MessageType{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const Mp=new aI;class oI extends S.MessageType{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const Ip=new oI;class cI extends S.MessageType{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Ap=new cI;class dI extends S.MessageType{constructor(){super("socket.livestreaming.StageRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9}])}}const lI=new dI;class uI extends S.MessageType{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>lI}])}}const ql=new uI;class hI extends S.MessageType{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const pI=new hI;class gI extends S.MessageType{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const mI=new gI;class fI extends S.MessageType{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Dp=new fI;class TI extends S.MessageType{constructor(){super("socket.polls.Poll",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"created_by",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"question",kind:"scalar",T:9},{no:5,name:"options",kind:"message",repeat:1,T:()=>vI},{no:6,name:"hide_votes",kind:"scalar",T:8},{no:7,name:"anonymous",kind:"scalar",T:8},{no:8,name:"votes",kind:"scalar",repeat:2,T:9}])}}const Gm=new TI;class SI extends S.MessageType{constructor(){super("socket.polls.PollOption",[{no:1,name:"text",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",opt:!0,T:4,L:2},{no:3,name:"votes",kind:"message",repeat:1,T:()=>EI}])}}const vI=new SI;class yI extends S.MessageType{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const EI=new yI;class PI extends S.MessageType{constructor(){super("socket.polls.NewPollRequest",[{no:1,name:"question",kind:"scalar",T:9},{no:2,name:"options",kind:"scalar",repeat:2,T:9},{no:3,name:"anonymous",kind:"scalar",T:8},{no:4,name:"hide_votes",kind:"scalar",T:8},{no:5,name:"created_by",kind:"scalar",opt:!0,T:9},{no:6,name:"created_by_user_id",kind:"scalar",opt:!0,T:9}])}}const bI=new PI;class _I extends S.MessageType{constructor(){super("socket.polls.VotePollRequest",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"index",kind:"scalar",T:4,L:2}])}}const CI=new _I;class wI extends S.MessageType{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Gm}])}}const jl=new wI;class RI extends S.MessageType{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Gm}])}}const kI=new RI;class MI extends S.MessageType{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",ji]}])}}const Op=new MI;class II extends S.MessageType{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const t=this.create(),e=Date.now();return t.seconds=S.PbLong.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(S.PbLong.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=S.PbLong.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=S.PbLong.from(t.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(t.nanos>0){let a=(t.nanos+1e9).toString().substring(1);a.substring(3)==="000000"?i="."+a.substring(0,3)+"Z":a.substring(6)==="000"?i="."+a.substring(0,6)+"Z":i="."+a+"Z"}return new Date(r).toISOString().replace(".000Z",i)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+S.typeofJsonValue(t)+".");let i=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let a=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(a))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(a<Date.parse("0001-01-01T00:00:00Z")||a>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=S.PbLong.from(a/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new II;class AI extends S.MessageType{constructor(){super("common.BaseHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9},{no:11,name:"use_start_session",kind:"scalar",opt:!0,T:8}])}}const cu=new AI;class DI extends S.MessageType{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>cu}])}}new DI;class OI extends S.MessageType{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>cu},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>cu}])}}new OI;const NI=0,LI=1,VI=2,xI=3,UI=5,$I={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToEntity:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43,livestreamingInvoked:44},BI={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},HI={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},FI={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Wm={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,updateConsumersSimulcastConfig:8,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94,audioActivity:100},qI={getUserPresets:0,updateUserPreset:1};function Pc(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Jm(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const V=Pc(NI,$I),Oe=Pc(LI,BI),F=Pc(VI,HI),Ns=Pc(xI,FI),yr=Jm(Wm,16777216),gs=Jm(Wm,50331648),Fc=Pc(UI,qI);var jI=Object.defineProperty,GI=Object.getOwnPropertyDescriptor,Wr=(s,t,e,r)=>{for(var i=r>1?void 0:r?GI(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&jI(t,e,i),i},Qt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(Qt||{}),Ct,En;class ur{constructor(t,e){g(this,Ct,void 0);g(this,En,void 0);m(this,Ct,e),m(this,En,t)}get telemetry(){return n(this,En).getValue("telemetry")}get logger(){return n(this,En).getValue("logger")}getChatMessages(){return n(this,Ct).sendMessagePromise(Oe.getMessages)}async getChatMessagesPaginated(t,e,r,i){const a={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await n(this,Ct).sendMessagePromise(Oe.getPaginatedMessages,Wk.toBinary(a));return o.payload?Kk.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};n(this,Ct).sendMessage(Oe.sendMessageToRoom,Qk.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};n(this,Ct).sendMessage(Oe.sendMessageToPeers,eM.toBinary(i))}sendMessage(t,e,r){if(r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i){const a={chatId:t,payloadType:r,payload:e};i!==void 0&&(a.pinned=i);const o=await n(this,Ct).sendMessagePromise(Oe.editMessage,nM.toBinary(a));return Oc.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await n(this,Ct).sendMessagePromise(Oe.deleteMessage,uM.toBinary(e));return{id:Nc.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,a,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(a=e.limit)!=null?a:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await n(this,Ct).sendMessagePromise(Oe.searchChannelMessages,gM.toBinary(r));return jm.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await n(this,Ct).sendMessagePromise(Oe.pinMessage,oM.toBinary(r));return Dc.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Oe.sendMessageToRoom:{r=Hl.fromBinary.bind(Hl),i=Hl.create();break}case Oe.sendMessageToPeers:{r=Fl.fromBinary.bind(Fl),i=Fl.create();break}case Oe.editMessage:{r=Oc.fromBinary.bind(Oc),i=Oc.create();break}case Oe.pinMessage:{r=Dc.fromBinary.bind(Dc),i=Dc.create();break}case Oe.deleteMessage:{r=Nc.fromBinary.bind(Nc),i=Nc.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}n(this,Ct).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Ct=new WeakMap,En=new WeakMap;Wr([y.trace("SocketService.getChatMessages")],ur.prototype,"getChatMessages",1);Wr([y.trace("SocketService.getChatMessagesPaginated")],ur.prototype,"getChatMessagesPaginated",1);Wr([y.trace("SocketService.sendMessageToRoom")],ur.prototype,"sendMessageToRoom",1);Wr([y.trace("SocketService.sendMessageToPeers")],ur.prototype,"sendMessageToPeers",1);Wr([y.trace("SocketService.sendMessage")],ur.prototype,"sendMessage",1);Wr([y.trace("SocketService.editMessage")],ur.prototype,"editMessage",1);Wr([y.trace("SocketService.deleteMessage")],ur.prototype,"deleteMessage",1);Wr([y.trace("SocketService.searchMessages")],ur.prototype,"searchMessages",1);function WI(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function ks(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>ks(e));const t={};return Object.keys(s).forEach(e=>{const r=nr.validate(e)?e:WI(e);t[r]=ks(s[e])}),t}function JI(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Km(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Km(e));const t={};return Object.keys(s).forEach(e=>{const r=nr.validate(e)?e:JI(e);t[r]=s[e]}),t}function nd(s,t={}){return s==null?{}:(Object.getOwnPropertyNames(s).forEach(e=>{if(typeof s[e]!="function"){if(typeof s[e]=="object"){nd(s[e],t[e]={});return}t[e]=s[e]}}),t)}class Np{constructor(t){h(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const a=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{a.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${a.toString()}`}return i}async request(t){var p;const e=((p=t.method)==null?void 0:p.toUpperCase())||"GET",r=this.buildURL(t.url||"",t.params),i={...this.defaults.headers.common,...t.headers};e!=="GET"&&e!=="HEAD"&&t.data&&!i["Content-Type"]&&(i["Content-Type"]="application/json");const o=i["Content-Type"]==="application/json"?JSON.stringify(t.data):t.data,c={method:e,headers:i,body:e!=="GET"&&e!=="HEAD"&&t.data?o:void 0},d=t.timeout||this.defaults.timeout,l=t.retry!==void 0?t.retry:this.defaults.retry,u=t.retryDelay||this.defaults.retryDelay;try{const f=new AbortController,T=setTimeout(()=>f.abort(),d);c.signal=f.signal;const E=await fetch(r,c);clearTimeout(T);let b=null;const _=E.headers.get("content-type");_&&_.includes("application/json")?b=await E.json():b=await E.text();const M={};E.headers.forEach((x,N)=>{M[N]=x});const A={data:b,status:E.status,statusText:E.statusText,headers:M,config:t};if(!E.ok)throw A;return A}catch(f){if(f instanceof Error&&l>0)return await new Promise(T=>setTimeout(T,u)),this.defaults.baseURL===ri.apiBase.prod?this.defaults.baseURL=ri.apiBase.prodAlternate:this.defaults.baseURL===ri.apiBase.prodAlternate&&(this.defaults.baseURL=ri.apiBase.prod),this.request({...t,retry:l-1});throw f}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const KI=3,zI=30,YI=8e3;class QI{constructor(t,e){h(this,"fetchClient");h(this,"requests");h(this,"roomName");h(this,"roomUUID");h(this,"authToken");h(this,"organizationId");h(this,"iceServers");h(this,"pluginInformation");h(this,"userDetails");h(this,"roomDetails");h(this,"context");this.context=t;const{timeout:r=YI,retry:i=KI,retryDelay:a=zI,baseURL:o=ri.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new Np({baseURL:o,timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.fetchClient=new Np({baseURL:"",timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var f,T,E,b,_;const p=t.getValue("telemetry");try{p.injectContext(this.requests.defaults.headers.common);const M=await l(u);return u.url!==p.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:M.status,statusText:M.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),M}catch(M){throw M?(((f=M.config)==null?void 0:f.url)!==p.logsEndpoint&&this.logger.error("xhr::fetch",{error:M,networkCall:{status:M.status,statusText:M.statusText,baseURL:((T=M.config)==null?void 0:T.baseURL)||this.requests.defaults.baseURL,url:(E=M.config)==null?void 0:E.url,retries:(b=M.config)==null?void 0:b.retry,method:(_=M.config)==null?void 0:_.method,isOnline:navigator.onLine?"online":"offline"}}),new R(M.message||"Network request failed","0011")):new R("Unknown network error occurred","0011")}}}get peerId(){return this.context.getValue("peerId")}get logger(){return this.context.getValue("logger")}setAuthToken(t,e){const{bearer:r}=e||{};this.authToken=t,this.requests.defaults.headers.common.Authorization=r?`Bearer ${t}`:t}setHeader(t,e){this.requests.defaults.headers.common[t]=e}setRoomName(t){this.roomName=t}setRoomUUID(t){this.roomUUID=t}setOrganizationId(t){this.organizationId=t}}var XI=Object.defineProperty,ZI=Object.getOwnPropertyDescriptor,As=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZI(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&XI(t,e,i),i};class Ss extends QI{constructor(e,r){super(e,r);h(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(await this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r}async getPlugins(){var a,o,c,d,l;if(this.pluginInformation)return this.pluginInformation;const{plugins:e}=(await this.requests.get("/v2/plugins/user")).data.data,r=g_,i=e.reduce((u,p)=>(u[r.includes(p.id)?"v1":"v2"].push({...p,name:p.name.replace("v2","")}),u),{v1:[],v2:[]});return(c=(o=(a=this.context.getValue("modules"))==null?void 0:a.devTools)==null?void 0:o.plugins)!=null&&c.length&&((l=(d=this.context.getValue("modules"))==null?void 0:d.devTools)==null||l.plugins.forEach(u=>{var f,T,E;const p={...Fa,tags:[...Fa.tags],baseUrl:`http://localhost:${u.port}`,name:u.name,picture:(f=u.picture)!=null?f:Fa.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:u.id,organizationId:this.organizationId,description:(T=u.description)!=null?T:Fa.description,staggered:(E=u.staggered)!=null?E:Fa.staggered};i.v2.push(p)})),i.v2}async getPluginDetails(e){const{plugin:r}=(await this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r}async getPluginConfig(e){return(await this.fetchClient.get(`${e}/dyte-config.json`)).data}async authorizePlugin(e){const r={peerId:this.peerId},{token:i}=(await this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return i}async getPresignedUrls(e){const r=ya(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:a,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:a,putLocation:o}}async uploadFile(e,r){if(navigator.isReactNative&&"uri"in e)try{await fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){this.logger.error(`sendFileMessage::${i}`)}else await this.fetchClient.put(r,e,{headers:{"Content-Type":e.type}})}async startLivestreaming({manualIngestion:e}){const r=ks(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!e})).data.data;return{playbackUrl:r.playbackUrl,status:r.status,manualIngest:r.manualIngest,ingestionCredentials:r.streamKey?{ingestionServer:r.ingestServer,streamKey:r.streamKey}:null}}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const e=ks((await this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{playbackUrl:e.playbackUrl,status:e.status,manualIngest:e.manualIngest,ingestionCredentials:e.streamKey?{ingestionServer:e.ingestServer,streamKey:e.streamKey}:null}}async getUserDetails(){if(this.userDetails)return this.userDetails;const e=(await this.requests.get("v2/internals/participant-details")).data.data;return ks(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...Km(e),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r})).data.data.id}async updateRecording(e,r){return this.requests.put(`v2/recordings/${e}`,{action:r})}async getActiveRecording(){const{status:e,id:r}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}}async getActiveTranscript(){const{transcript_download_url:e}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.fetchClient.get(e)).data}}catch(r){throw new R("Cant fetch transcript s3 url","1801")}}}As([y.trace("APIClient.getICEServers")],Ss.prototype,"getICEServers",1);As([y.trace("APIClient.getPlugins")],Ss.prototype,"getPlugins",1);As([y.trace("APIClient.startLivestreaming")],Ss.prototype,"startLivestreaming",1);As([y.trace("APIClient.stopLivestreaming")],Ss.prototype,"stopLivestreaming",1);As([y.trace("APIClient.getActiveLivestream")],Ss.prototype,"getActiveLivestream",1);As([y.trace("APIClient.getUserDetails")],Ss.prototype,"getUserDetails",1);As([y.trace("APIClient.startRecording")],Ss.prototype,"startRecording",1);As([y.trace("APIClient.stopRecording")],Ss.prototype,"updateRecording",1);As([y.trace("APIClient.getActiveRecording")],Ss.prototype,"getActiveRecording",1);As([y.trace("APIClient.getActiveTranscript")],Ss.prototype,"getActiveTranscript",1);let du;function eA(s,t){return du=new Ss(s,t),du}function ht(){return du}const ba={maxInvocations:5,period:1};function Et(s,t){return function(e,r,i){const a=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),u=t?this[t]:s;if(l-c>u.period*1e3&&(c=l,o=0),o>=u.maxInvocations)throw new R(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,a.apply(this,d)},i}}var tA=Object.defineProperty,sA=Object.getOwnPropertyDescriptor,vs=(s,t,e,r)=>{for(var i=r>1?void 0:r?sA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&tA(t,e,i),i};const rA=["text","image","file","custom","poll"],qc={maxInvocations:180,period:60};var X,ni,$e,Pn,md,zm,fo,lu,Yp;let Ot=(Yp=class extends Lt{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,md);g(this,fo);h(this,"messages");g(this,X,void 0);g(this,ni,void 0);g(this,$e,void 0);g(this,Pn,void 0);h(this,"maxTextLimit",2e3);m(this,Pn,t),m(this,$e,e),m(this,X,r),m(this,ni,i),this.messages=[]}get telemetry(){return n(this,Pn).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e){switch(t.type){case"text":{await this.sendTextMessageInternal(t.message,e);break}case"image":await this.sendImageMessageInternal(t.image,e);break;case"file":await this.sendFileMessageInternal(t.file,e);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e){var i,a,o,c,d,l;if(t.length>this.maxTextLimit)throw new R("Max character limit breached","0503");if(e&&e.length>0){if(!((i=n(this,X).permissions)!=null&&i.chatPrivate.canSend)||!((a=n(this,X).permissions)!=null&&a.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new R("Could not send message to private chat.","0501")}else if(!((c=(o=n(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=n(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new R("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new R("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(n(this,X).id),r=n(this,ni).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(n(this,X).userId)),n(this,$e).sendMessage(t,Qt.TEXT,e)}async sendImageMessageInternal(t,e){var i,a,o,c,d,l;if(e&&e.length>0){if(!((i=n(this,X).permissions)!=null&&i.chatPrivate.canSend)||!((a=n(this,X).permissions)!=null&&a.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=n(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=n(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:t.type}});return}try{const u=ht(),{getLocation:p,putLocation:f}=await u.getPresignedUrls(t.name);await u.uploadFile(t,f);let T=[];e&&e.length>0&&(e.push(n(this,X).id),T=n(this,ni).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),T.push(n(this,X).userId)),n(this,$e).sendMessage(p,Qt.IMAGE,e)}catch(u){throw new R("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,a,o,c,d;if(e&&e.length>0){if(!((r=n(this,X).permissions)!=null&&r.chatPrivate.canSend)||!((i=n(this,X).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(a=n(this,X).permissions)==null?void 0:a.chatPublic)!=null&&o.canSend)||!((d=(c=n(this,X).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=ht(),{getLocation:u,putLocation:p}=await l.getPresignedUrls(t.name);await l.uploadFile(t,p);let f=[];e&&e.length>0&&(e.push(n(this,X).id),f=n(this,ni).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),f.push(n(this,X).userId));const T=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});n(this,$e).sendMessage(T,Qt.FILE,e)}catch(l){throw new R("Error sending file message.","0500",this.logger)}}get rateLimits(){return qc}updateRateLimits(t,e){qc.maxInvocations=t,qc.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var a,o,c,d,l,u,p,f,T,E,b,_,M,A,x;if(e&&e.length>0){if(!((a=n(this,X).permissions)!=null&&a.chatPrivate.canSend)||!((o=n(this,X).permissions)!=null&&o.chatPrivate.files)||!((c=n(this,X).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=n(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((p=(u=n(this,X).permissions)==null?void 0:u.chatPublic)!=null&&p.files)||!((T=(f=n(this,X).permissions)==null?void 0:f.chatPublic)!=null&&T.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async N=>{try{if(typeof N=="string")return{link:N};const $=ht(),{getLocation:K,putLocation:Z}=await $.getPresignedUrls(N.name);return await $.uploadFile(N,Z),{link:K,type:N.type,name:N.name,size:N.size}}catch($){throw new R("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((b=(E=t.files)!=null?E:[])==null?void 0:b.map(async N=>r(N))),images:await Promise.all((M=(_=t.images)!=null?_:[])==null?void 0:M.map(async N=>r(N))),videos:await Promise.all((x=(A=t.videos)!=null?A:[])==null?void 0:x.map(async N=>r(N)))};n(this,$e).sendMessage(JSON.stringify(i),Qt.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,X).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(a=n(this,X).permissions)==null?void 0:a.chatPublic)!=null&&o.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}n(this,$e).editMessage(t,e,Qt.TEXT)}async editImageMessage(t,e){var i,a,o,c;if(!((a=(i=n(this,X).permissions)==null?void 0:i.chatPublic)!=null&&a.canSend)||!((c=(o=n(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:e.type}});return}try{const d=ht(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),n(this,$e).editMessage(t,l,Qt.IMAGE)}catch(d){throw new R("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,X).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(a=n(this,X).permissions)==null?void 0:a.chatPublic)!=null&&o.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=ht(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),n(this,$e).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Qt.FILE)}catch(c){throw new R("Error editing file message.","0500",this.logger)}}async editMessage(t,e){switch(e.type){case"text":{this.editTextMessage(t,e.message);break}case"image":{this.editImageMessage(t,e.image);break}case"file":{this.editFileMessage(t,e.file);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t){n(this,$e).deleteMessage(t)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!n(this,fo,lu))throw new R("Can`t pin message without joining room","0505");try{await n(this,$e).setPinState(t,!0)}catch(e){throw new R(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!n(this,fo,lu))throw new R("Can`t unpin message without joining room","0505");try{await n(this,$e).setPinState(t,!1)}catch(e){throw new R(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,$e).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>Xt.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await n(this,$e).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>Xt.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,$e).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>Xt.formatSocketPeerMessage(o))}async getMessages(t,e,r,i=0){const a=await n(this,$e).getChatMessagesPaginated(t,e,r);return{messages:a.messages.map(o=>Xt.formatSocketPeerMessage(o)),next:a.next}}async searchMessages(t,e){throw new R("searchMessages is disabled! Please use `fetchPublicMessages` method instead.","0506")}get pinned(){return this.messages.filter(t=>t.pinned)}},X=new WeakMap,ni=new WeakMap,$e=new WeakMap,Pn=new WeakMap,md=new WeakSet,zm=function(){return n(this,Pn).getValue("connectionHandler")},fo=new WeakSet,lu=function(){return n(this,md,zm).socketJoined===!0},Yp);vs([y.trace("Chat.sendTextMessage"),Et(qc)],Ot.prototype,"sendTextMessage",1);vs([y.trace("Chat.sendImageMessage"),Et({maxInvocations:20,period:60})],Ot.prototype,"sendImageMessage",1);vs([y.trace("Chat.sendFileMessage"),Et({maxInvocations:20,period:60})],Ot.prototype,"sendFileMessage",1);vs([y.trace("Chat.sendMessage"),Et({maxInvocations:180,period:60})],Ot.prototype,"sendMessage",1);vs([y.trace("Chat.editTextMessage")],Ot.prototype,"editTextMessage",1);vs([y.trace("Chat.editImageMessage")],Ot.prototype,"editImageMessage",1);vs([y.trace("Chat.editFileMessage")],Ot.prototype,"editFileMessage",1);vs([y.trace("Chat.editMessage")],Ot.prototype,"editMessage",1);vs([y.trace("Chat.deleteMessage")],Ot.prototype,"deleteMessage",1);vs([y.trace("Chat.searchMessages")],Ot.prototype,"searchMessages",1);Ot=vs([rt("0500")],Ot);var iA=Object.defineProperty,nA=Object.getOwnPropertyDescriptor,aA=(s,t,e,r)=>{for(var i=r>1?void 0:r?nA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&iA(t,e,i),i},ai,Qp;const fr=(Qp=class{constructor(s,t,e,r){h(this,"chat");h(this,"chatSocketHandler");h(this,"self");g(this,ai,void 0);m(this,ai,s),this.chatSocketHandler=t,this.chat=new Ot(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return n(this,ai).getValue("telemetry")}get logger(){return n(this,ai).getValue("logger")}static async init(s,t,e,r){return new fr(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:rA[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case Qt.TEXT:{e.message=s.payload;break}case Qt.IMAGE:{e.link=s.payload;break}case Qt.FILE:{const{link:r,name:i,size:a}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=a;break}case Qt.CUSTOM:{const{html:r,images:i,message:a,videos:o,files:c}=JSON.parse(s.payload);e.message=a,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return fr.formatMessage(e)}async getChatMessages(){if(this.self.config.viewType==="LIVESTREAM")return;const s=await this.chatSocketHandler.getChatMessages();if(!(s!=null&&s.payload))return;const t=jm.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>fr.formatSocketPeerMessage(e))}setupEvents(){n(this,ai).getValue("peerSessionStore").on(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Oe.sendMessageToRoom,s=>{if(!s.message)return;const t=fr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Oe.sendMessageToPeers,s=>{const t=fr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Oe.editMessage,s=>{if(!s.message)return;const t=fr.formatSocketPeerMessage(s.message),e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t),this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Oe.deleteMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);let e={id:s.chatId};t!==-1&&([e]=this.chat.messages.splice(t,1)),this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Oe.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=fr.formatSocketPeerMessage(s.message);t!==-1&&(this.chat.messages[t]=e),this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}),s.pinned?this.chat.emit("pinMessage",{message:e,messages:this.chat.messages}):this.chat.emit("unpinMessage",{message:e,messages:this.chat.messages})})}},ai=new WeakMap,Qp);let Xt=fr;aA([y.trace("ChatController.setupEvents")],Xt.prototype,"setupEvents",1);var oA=Object.defineProperty,cA=Object.getOwnPropertyDescriptor,dA=(s,t,e,r)=>{for(var i=r>1?void 0:r?cA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&oA(t,e,i),i},fd,Ym,Td,Qm,bn,_n,To,Xp;let uu=(Xp=class extends Lt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,fd);g(this,Td);h(this,"items");g(this,bn,void 0);g(this,_n,void 0);g(this,To,void 0);m(this,To,t),m(this,bn,e),m(this,_n,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!n(this,Td,Qm))throw new R("Can't create polls without joining room","0705");if(!n(this,bn).permissions.polls.canCreate){this.logger.error("Polls::create::permission_denied");return}if(!t||!e){this.logger.error("Polls::question_and_options_can_not_be_empty",{polls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){this.logger.error("Polls::there_must_be_at_least_two_options",{polls:{hasQuestion:!!t,optionsLength:e.length}});return}await n(this,_n).createPoll(t,e,r,i)}async vote(t,e){if(!n(this,bn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await n(this,_n).votePoll(t,e)}},fd=new WeakSet,Ym=function(){return n(this,To).getValue("connectionHandler")},Td=new WeakSet,Qm=function(){var t;return((t=n(this,fd,Ym))==null?void 0:t.socketJoined)===!0},bn=new WeakMap,_n=new WeakMap,To=new WeakMap,Xp);uu=dA([rt("0700")],uu);var lA=Object.defineProperty,uA=Object.getOwnPropertyDescriptor,hA=(s,t,e,r)=>{for(var i=r>1?void 0:r?uA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&lA(t,e,i),i},Er,Cn,oi,Zp;const sn=(Zp=class{constructor(s,t,e){h(this,"polls");g(this,Er,void 0);g(this,Cn,void 0);g(this,oi,void 0);this.polls=new uu(s,t,e),m(this,Cn,t),m(this,Er,s),m(this,oi,e),this.setupEvents()}get telemetry(){return n(this,Er).getValue("telemetry")}get logger(){return n(this,Er).getValue("logger")}static async init(s,t,e){return new sn(s,t,e)}canViewPolls(){return n(this,Cn).permissions.polls.canView}setupEvents(){const s={[Ns.createPoll]:r=>{r.poll&&this.updatePoll(sn.formatSocketServicePoll(r.poll))},[Ns.updatePoll]:r=>{r.poll&&this.updatePoll(sn.formatSocketServicePoll(r.poll))},[Ns.votePoll]:r=>{r.poll&&this.updatePoll(sn.formatSocketServicePoll(r.poll))}},t=()=>{n(this,Er).getValue("peerSessionStore").on(C.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,oi).on(r,s[r])})},e=()=>{n(this,Er).getValue("peerSessionStore").on(C.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,oi).removeListeners(r)})};n(this,Cn).permissions.on("permissionsUpdate",async r=>{var i;r!=null&&r.polls&&((i=r==null?void 0:r.polls)!=null&&i.canView?(await this.getPolls(),t()):(this.polls.items=[],e()))}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await n(this,oi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=kI.fromBinary(s.payload);this.polls.items=t.map(e=>sn.formatSocketServicePoll(e))}static formatSocketServicePoll(s){const t=s.options.map(e=>({count:e.count,text:e.text,votes:e.votes.map(r=>({id:r.userId,name:r.name}))}));return{anonymous:s.anonymous,createdBy:s.createdBy,createdByUserId:s.createdByUserId,hideVotes:s.hideVotes,id:s.pollId,options:t,question:s.question,voted:s.votes}}},Er=new WeakMap,Cn=new WeakMap,oi=new WeakMap,Zp);let Xm=sn;hA([y.trace("PollController.setupEvents")],Xm.prototype,"setupEvents",1);var pA=Object.defineProperty,gA=Object.getOwnPropertyDescriptor,mA=(s,t,e,r)=>{for(var i=r>1?void 0:r?gA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&pA(t,e,i),i},Zm=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(Zm||{}),wn,So,pu,ci,vo,eg;let hu=(eg=class extends Lt{constructor(t,e,r,i,a){const o=t.getValue("logger");super(o);g(this,So);h(this,"selfActiveTab");h(this,"broadcastTabChanges");g(this,wn,void 0);g(this,ci,void 0);g(this,vo,void 0);h(this,"viewType");h(this,"meetingStartedTimestamp");h(this,"meetingTitle");h(this,"sessionId");m(this,wn,t),m(this,ci,e),this.viewType=r,m(this,vo,i),this.meetingTitle=a,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return n(this,So,pu).socketState}get mediaState(){return n(this,So,pu).mediaState}get meetingId(){return n(this,wn).getValue("meetingId")}setBroadcastTabChanges(t){if(!n(this,ci).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new R("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=n(this,ci).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){n(this,vo).broadcastMessage("spotlight",{userId:n(this,ci).userId,currentTab:this.selfActiveTab})}},wn=new WeakMap,So=new WeakSet,pu=function(){return n(this,wn).getValue("connectionHandler")},ci=new WeakMap,vo=new WeakMap,eg);hu=mA([rt("0800")],hu);function fA(s){let t="",e=[""];const r=[e];let i=0,a=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
|
|
7
|
-
`&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++a]=[c=""],i=0):e[i]+=c,t=c;return r}var
|
|
8
|
-
`).map(e=>qr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=ht(),{transcript:e}=await t.getActiveTranscript();this.transcripts=qr.parseTranscripts(e)}catch(t){}}async onTranscript(t){var r;const e=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((r=e==null?void 0:e.at(-1))!=null&&r.isPartialTranscript){const i=e.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)}},yo=new WeakMap,tg);ef([y.trace("Ai.getActiveTranscript")],qr.prototype,"getActiveTranscript",1);qr=ef([rt("0000")],qr);var vA=Object.defineProperty,yA=Object.getOwnPropertyDescriptor,EA=(s,t,e,r)=>{for(var i=r>1?void 0:r?yA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vA(t,e,i),i},Pr,Rn,wt,sg;const tf=(sg=class{constructor(s,t,e,r,i,a){h(this,"meta");h(this,"ai");g(this,Pr,void 0);g(this,Rn,void 0);h(this,"aiSocketHandler");g(this,wt,void 0);m(this,wt,s),this.meta=new hu(s,t,t.config.viewType,e,a),this.ai=r,m(this,Pr,t),m(this,Rn,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return n(this,wt).getValue("telemetry")}get logger(){return n(this,wt).getValue("logger")}static async init(s,t,e,r,i){const a=await qr.init(s,t.permissions.transcriptionEnabled);return new tf(s,t,e,a,r,i)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,Zm.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){n(this,wt).getValue("peerSessionStore").on(C.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),n(this,wt).getValue("peerSessionStore").on(C.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),n(this,wt).getValue("peerSessionStore").on(C.ROOM_STATE,({createdAt:s,roomUuid:t})=>{const e=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!e){const r=new Date(s*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),n(this,wt).getValue("peerSessionStore").on(C.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),n(this,Pr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&n(this,Rn).broadcastMessage("spotlight",{userId:n(this,Pr).userId,currentTab:this.meta.selfActiveTab})),n(this,wt).getValue("peerSessionStore").on(C.PEER_JOINED_INTERNAL,async s=>{n(this,Pr).permissions.canSpotlight&&this.meta.selfActiveTab&&n(this,Rn).broadcastToPeers("spotlight",[s.id],{userId:n(this,Pr).userId,currentTab:this.meta.selfActiveTab})}),n(this,wt).getValue("peerSessionStore").on(C.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),n(this,wt).getValue("peerSessionStore").on(C.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),this.aiSocketHandler.on(V.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=qr.parseTranscript(e,r)}catch(d){this.logger.error(`Failed to parse transcript: ${e}`,d)}if(!i){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(i),this.meta.emit("transcript",i);const{peerId:a,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${a} - ${o}: ${c}`)})}},Pr=new WeakMap,Rn=new WeakMap,wt=new WeakMap,sg);let sf=tf;EA([y.trace("MetaController.setupEvents")],sf.prototype,"setupEvents",1);const ja={},hr={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,a)=>{const o=a.value;return a.value=function(...d){var E,b;const l=(b=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.authToken))!=null?b:"",u=`${t}-${l}`,p=this==null?void 0:this.logger;if(ja[u]){const _=new Error(`Unsupported concurrent calls on method: ${s}.`);throw _.name="UnsupportedConcurrentMethodExecution",p==null||p.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:_.stack},locker:{methodName:s,lockName:u}}),_}ja[u]=!0;const f=setTimeout(()=>delete ja[u],e),T=o.apply(this,d);return Promise.resolve(T).then(()=>{delete ja[u],clearTimeout(f)}).catch(()=>{delete ja[u],clearTimeout(f)}),T},a}}};var PA=Object.defineProperty,bA=Object.getOwnPropertyDescriptor,Qi=(s,t,e,r)=>{for(var i=r>1?void 0:r?bA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&PA(t,e,i),i},Ft,Sd,ee,Eo,Es,Be,Po,gu,kn,jc;class Jr extends Lt{constructor(e,r,i,a,o){const c=e.getValue("logger");super(c);g(this,Po);g(this,kn);g(this,Ft,void 0);g(this,Sd,void 0);g(this,ee,void 0);g(this,Eo,void 0);g(this,Es,void 0);g(this,Be,void 0);m(this,Be,e),m(this,Ft,a),m(this,Sd,o),m(this,ee,r),m(this,Eo,i),m(this,Es,[]),this.setupEvents()}get telemetry(){return n(this,Be).getValue("telemetry")}get status(){return n(this,Be).getValue("stageStatus")}setupEvents(){const e={[C.GET_STAGE_REQUESTS]:async a=>{m(this,Es,a)},[C.UPDATE_STAGE_REQUESTS]:async({add:a})=>{const o=n(this,Es).length,{stageRequests:c}=this.getAccessRequests();(a||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([a,o])=>{n(this,Be).getValue("peerSessionStore").onAsync(a,o)})},i=()=>{Object.entries(e).forEach(([a,o])=>{n(this,Be).getValue("peerSessionStore").removeListener(a,o)})};n(this,ee).permissions.on("permissionsUpdate",a=>{const{canAcceptProductionRequests:o}=a;o!==void 0&&(n(this,ee).permissions.acceptStageRequests?(r(),n(this,Ft).getStageRequests()):(i(),m(this,Es,[]),this.emit("stageAccessRequestUpdate",n(this,Es))))}),n(this,ee).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!n(this,ee).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new R("You do not have permission to perform this action","2001");const e=n(this,Eo).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return m(this,Es,e),{stageRequests:n(this,Es)}}async requestAccess(){if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new R(`Unable to request access you are currently ${this.status}`,"2006");if(n(this,ee).permissions.stageAccess===H.Allowed){L(this,kn,jc).call(this,"ACCEPTED_TO_JOIN_STAGE");return}n(this,Ft).requestAccess(),L(this,kn,jc).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");n(this,Ft).cancelRequestAccess(),L(this,kn,jc).call(this,"OFF_STAGE")}grantAccess(e){if(!n(this,ee).roomJoined)throw new R("Can`t grant for participant without joining room");if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!n(this,ee).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new R("You do not have permission to perform this action","2001");return n(this,Ft).grantAccess(e)}denyAccess(e){if(!n(this,ee).roomJoined)throw new R("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!n(this,ee).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new R("You do not have permission to perform this action","2001");return n(this,Ft).denyAccess(e)}get peerId(){return n(this,Be).getValue("peerId")}async join(){const e=n(this,Be).getValue("viewType");if(this.status==="ON_STAGE")throw new R("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||n(this,ee).permissions.stageAccess===H.NotAllowed)throw new R(`Unable to join stage you are currently ${this.status}`,"2006");if(n(this,Be).setValue("stageStatus","ON_STAGE",!1),await n(this,Ft).joinStage(),e===rr.Livestream){await n(this,Be).getValue("selfController").joinRoom();return}n(this,Be).notify("stageStatus"),n(this,ee).audioEnabled&&n(this,Po,gu).shareMic(n(this,ee).audioTrack),n(this,ee).videoEnabled&&n(this,Po,gu).shareWebcam(n(this,ee).videoTrack)}async leave(){if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new R(`Unable to leave stage you are currently ${this.status}`,"2006");n(this,ee).setIsPinned(!1),n(this,Be).setValue("stageStatus","OFF_STAGE",!1),await n(this,Ft).leaveStage(n(this,ee).userId);try{await n(this,Be).getValue("peerSessionStore").emitAsync(C.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}n(this,Be).notify("stageStatus")}async kick(e){if(!n(this,ee).roomJoined)throw new R("Can`t kick participant without joining room","2005");if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!n(this,ee).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new R("You do not have permissions for kick","2001");return n(this,Ft).kick(e)}}Ft=new WeakMap,Sd=new WeakMap,ee=new WeakMap,Eo=new WeakMap,Es=new WeakMap,Be=new WeakMap,Po=new WeakSet,gu=function(){return n(this,Be).getValue("roomNodeClient")},kn=new WeakSet,jc=async function(e){this.status!==e&&n(this,Be).setValue("stageStatus",e)};Qi([y.trace("Stage.getStageRequests")],Jr.prototype,"getAccessRequests",1);Qi([y.trace("Stage.requestAccess")],Jr.prototype,"requestAccess",1);Qi([y.trace("Stage.cancelRequestAccess")],Jr.prototype,"cancelRequestAccess",1);Qi([y.trace("Stage.grantAccess")],Jr.prototype,"grantAccess",1);Qi([y.trace("Stage.denyAccess")],Jr.prototype,"denyAccess",1);Qi([hr.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),y.trace("Stage.joinStage")],Jr.prototype,"join",1);Qi([y.trace("Stage.leaveStage")],Jr.prototype,"leave",1);function _A(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function ah(s){switch(s){case er.UNSPECIFIED:return"OFF_STAGE";case er.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case er.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case er.OFF_STAGE:return"OFF_STAGE";case er.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var CA=Object.defineProperty,wA=Object.getOwnPropertyDescriptor,RA=(s,t,e,r)=>{for(var i=r>1?void 0:r?wA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&CA(t,e,i),i},br,ns,_r,bo,nt;class rf{constructor(t,e,r,i,a){h(this,"stage");g(this,br,void 0);g(this,ns,void 0);g(this,_r,void 0);g(this,bo,0);g(this,nt,void 0);m(this,nt,t),this.stage=new Jr(t,i,a,e,r),m(this,_r,e),m(this,br,i),m(this,ns,a),this.setupEvents()}get telemetry(){return n(this,nt).getValue("telemetry")}get logger(){return n(this,nt).getValue("logger")}setupEvents(){n(this,nt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),n(this,_r).on(V.grantStageAccess,()=>{n(this,br).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),n(this,_r).on(V.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===n(this,br).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),n(this,_r).on(V.denyStageAccess,()=>{n(this,br).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),n(this,_r).on(V.getStageRequests,async t=>{var r;if(n(this,br).permissions.stageAccess!==H.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await n(this,nt).getValue("peerSessionStore").emitAsync(C.GET_STAGE_REQUESTS,e),n(this,bo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),m(this,bo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return n(this,ns).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&n(this,nt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=ah(t.stageType),r=n(this,nt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:n(this,nt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:n(this,nt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=n(this,ns).joined.get(t.peerId),r=n(this,ns).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&n(this,nt).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:n(this,ns).viewMode,page:n(this,ns).currentPage});break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&n(this,nt).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:n(this,ns).viewMode,page:n(this,ns).currentPage});break}n(this,nt).getValue("peerSessionStore").emit(C.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}br=new WeakMap,ns=new WeakMap,_r=new WeakMap,bo=new WeakMap,nt=new WeakMap;RA([y.trace("Stage.setupEvents")],rf.prototype,"setupEvents",1);var kA=Object.defineProperty,MA=Object.getOwnPropertyDescriptor,El=(s,t,e,r)=>{for(var i=r>1?void 0:r?MA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kA(t,e,i),i};const _e={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};var Qe,Rt,Mn,In,$s,An,Cr,Dn,rg;let Ea=(rg=class extends Pa{constructor(t,{baseURL:e,createdAt:r,description:i,id:a,name:o,organizationId:c,picture:d,private:l,published:u,staggered:p,tags:f,type:T,updatedAt:E},b,_,M,A,x){const N=t.getValue("logger");super(N);g(this,Qe,void 0);h(this,"baseURL");h(this,"createdAt");h(this,"description");h(this,"id");h(this,"name");g(this,Rt,void 0);g(this,Mn,void 0);g(this,In,void 0);h(this,"organizationId");h(this,"picture");h(this,"private");h(this,"published");h(this,"staggered");h(this,"tags");h(this,"type");h(this,"updatedAt");g(this,$s,void 0);h(this,"config");g(this,An,void 0);h(this,"active");h(this,"iframes");h(this,"enabledBy");g(this,Cr,void 0);g(this,Dn,void 0);m(this,Cr,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=a,this.name=o,m(this,Rt,_),this.organizationId=c,this.picture=d,this.private=l,this.published=u,this.staggered=p,this.tags=f,this.type=T,this.updatedAt=new Date(E),this.active=!1,this.iframes=new Map,m(this,Qe,b),m(this,Mn,M),m(this,In,A),this.enabledBy="",m(this,Dn,x)}get telemetry(){return n(this,Cr).getValue("telemetry")}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}async handleIframeMessage(t){var o;if(!this.active)return;const e=t,{payload:r,uuid:i,type:a}=e;switch(a){case F.customPluginEventToRoom:{n(this,Qe).customPluginEventToRoom(this.id,r,i);break}case F.customPluginEventToPeers:{n(this,Qe).customPluginEventToPeers(this.id,r.peerIds,r,i);break}case F.enablePluginForRoom:{n(this,Qe).enablePluginForRoom(this.id,i);break}case F.enablePluginForPeers:{n(this,Qe).enablePluginForPeers(this.id,r.peerIds,i);break}case F.disablePluginForRoom:{n(this,Qe).disablePluginForRoom(this.id,i);break}case F.disablePluginForPeers:{n(this,Qe).disablePluginForPeers(this.id,r.peerIds,i);break}case F.storeInsertKeys:{n(this,Qe).storeInsertKeys(this.id,r.store,r.insertKeys,i);break}case F.storeGetKeys:{n(this,Qe).storeGetKeys(this.id,r.store,r.getKeys,i);break}case F.storeDeleteKeys:{n(this,Qe).storeDeleteKeys(this.id,r.store,r.deleteKeys,i);break}case F.storeDelete:{n(this,Qe).storeDelete(this.id,r.store,i);break}case _e.chatMessage:{const{messagePayload:c,peerIds:d}=r;if(!n(this,In)){this.sendIframeEvent({type:_e.chatMessage,uuid:e.uuid,payload:{error:"Chat is disabled for this room."}});return}try{await n(this,In).sendMessage(c,d),this.sendIframeEvent({type:_e.chatMessage,uuid:e.uuid,payload:{success:!0}})}catch(l){this.sendIframeEvent({type:_e.chatMessage,uuid:e.uuid,payload:{error:l}})}break}case _e.getPeer:{let c;const{peerId:d}=r,l={...n(this,Rt),id:n(this,Rt).id,isRecorder:(o=n(this,Rt).permissions)==null?void 0:o.isRecorder,isHidden:n(this,Rt).permissions.hiddenParticipant,stageStatus:n(this,Rt).stageStatus};d?(c=n(this,Mn).joined.get(r.peerId),n(this,Rt).id===d&&(c=l)):c=l,this.sendIframeEvent({type:_e.getPeer,payload:{peer:c&&nd(c)},uuid:e.uuid});break}case _e.getPeers:{const c=n(this,Mn).joined.toArray().map(d=>nd(d));this.sendIframeEvent({type:_e.getPeers,payload:{peers:c},uuid:e.uuid});break}case _e.getPluginInitiator:{this.sendIframeEvent({type:_e.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:e.uuid});break}case _e.getDisplayTitle:{this.sendIframeEvent({type:_e.getDisplayTitle,payload:{displayTitle:n(this,Dn)},uuid:e.uuid});break}case _e.getRoomName:{this.sendIframeEvent({type:_e.getRoomName,payload:{roomName:n(this,Cr).getValue("meetingId")},uuid:e.uuid});break}case _e.customPluginEventToParent:{this.emit(e.payload.eventName,e.payload.data);break}}}sendData(t){this.active&&(this.logger.info("Plugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:_e.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var i;const{iframe:e,listener:r}=(i=this.iframes.get(t))!=null?i:{};(e||r)&&(navigator.isReactNative?e.props.onMessage=void 0:window.removeEventListener("message",r),this.iframes.delete(t))}addPluginView(t,e="default"){var o;if(!n(this,An))throw this.logger.error("Plugin::addPluginView::no_auth_token_set_for_plugin"),new R("No auth token set for plugin.","0602");if(!t)throw this.logger.error("Plugin::addPluginView::iframe_was_not_provided"),new R("Iframe was not provided.","0603");this.removePluginView(e);const r=t,i=new URL(this.baseURL),a={auth:n(this,An),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:n(this,Cr).getValue("apiBase"),pluginId:this.id,roomName:(o=n(this,Cr).getValue("meetingId"))!=null?o:"",displayTitle:n(this,Dn)};if(Object.keys(a).forEach(c=>{i.searchParams.set(c,a[c])}),r.src=i.href,r.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",r.title=e,navigator.isReactNative)r.props.onMessage=c=>{this.handleIframeMessage(JSON.parse(c.nativeEvent.data))},this.iframes.set(e,{iframe:r});else{const c=async d=>{d.source===t.contentWindow&&await this.handleIframeMessage(d.data)};window.addEventListener("message",c),this.iframes.set(e,{iframe:r,listener:c})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}async activateForSelf(){const t=ht(),e=await t.authorizePlugin(this.id);m(this,An,e),m(this,$s,new Date);try{const r=await t.getPluginConfig(this.baseURL);this.config=r}catch(r){this.logger.error("Plugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),m(this,$s,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}async enable(){return this.activateForSelf()}disable(){return this.deactivateForSelf()}async activate(){var t,e;this.active||(e=(t=n(this,Rt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(n(this,Qe).addPlugin(this.id,this.staggered),m(this,$s,new Date),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))}async deactivate(){var t,e;this.active&&(!((e=(t=n(this,Rt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==n(this,Rt).id||(n(this,Qe).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:n(this,$s)?new Date().getTime()-n(this,$s).getTime():0}}),m(this,$s,void 0)))}},Qe=new WeakMap,Rt=new WeakMap,Mn=new WeakMap,In=new WeakMap,$s=new WeakMap,An=new WeakMap,Cr=new WeakMap,Dn=new WeakMap,rg);El([Et({maxInvocations:5,period:1})],Ea.prototype,"sendData",1);El([y.trace("Plugin.activatePlugin")],Ea.prototype,"activate",1);El([y.trace("Plugin.deactivatePlugin")],Ea.prototype,"deactivate",1);Ea=El([rt("0600")],Ea);var Me,di;class nf extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:a,onClearEvent:o}=e;super();g(this,Me,void 0);g(this,di,void 0);h(this,"onAddEvent");h(this,"onDeleteEvent");h(this,"onClearEvent");m(this,Me,new Pa(r)),this.onAddEvent=i,this.onDeleteEvent=a,this.onClearEvent=o,m(this,di,new Map)}emit(e,...r){return n(this,Me).emit(e,...r)}on(e,r){return n(this,Me).on(e,r)}addListener(e,r){return n(this,Me).addListener(e,r)}off(e,r){return n(this,Me).off(e,r)}once(e,r){return n(this,Me).once(e,r)}prependListener(e,r){return n(this,Me).prependListener(e,r)}prependOnceListener(e,r){return n(this,Me).prependOnceListener(e,r)}removeListener(e,r){return n(this,Me).removeListener(e,r)}removeAllListeners(e){return n(this,Me).removeAllListeners(e)}listeners(e){return n(this,Me).listeners(e)}listenerCount(e){return n(this,Me).listenerCount(e)}getMaxListeners(){return n(this,Me).getMaxListeners()}setMaxListeners(e){return n(this,Me).setMaxListeners(e)}eventNames(){return n(this,Me).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const a=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return n(this,di).set(e,o),r.on("*",o),i&&n(this,Me).emit(this.onAddEvent,r),a}delete(e,r=!0,i=!1){const a=this.get(e);if(!a)return!1;a.removeListener("*",n(this,di).get(e));const o=super.delete(e);return i&&a.removeAllListeners(),r&&n(this,Me).emit(this.onDeleteEvent,a),o}clear(e=!0,r=!1){this.forEach(a=>{a.removeListener("*",n(this,di).get(a.id)),r&&a.removeAllListeners()});const i=super.clear();return e&&n(this,Me).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Me=new WeakMap,di=new WeakMap;class Lp extends nf{constructor(t){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"},t)}add(t,e=!0){return super.add(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var IA=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,DA=(s,t,e,r)=>{for(var i=r>1?void 0:r?AA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&IA(t,e,i),i};let mu=class{constructor(s){h(this,"all");h(this,"active");this.all=new Lp(s),this.active=new Lp(s)}};mu=DA([rt("0600")],mu);var OA=Object.defineProperty,NA=Object.getOwnPropertyDescriptor,Pl=(s,t,e,r)=>{for(var i=r>1?void 0:r?NA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&OA(t,e,i),i},qt,On,as,ig;const af=(ig=class{constructor(s,t,e,r){h(this,"plugins");g(this,qt,void 0);g(this,On,void 0);g(this,as,void 0);m(this,qt,t),m(this,On,e),m(this,as,s),this.plugins=r,this.setupEvents()}get telemetry(){return n(this,as).getValue("telemetry")}get logger(){return n(this,as).getValue("logger")}static async init(s,t,e,r,i,a,o,c){const d=s.getValue("logger"),l=new mu(d);return t.forEach(u=>{const p=new Ea(s,u,e,a,o,i,c);l.all.add(p)}),new af(s,e,r,l)}async getRoomPlugins(){var t;const{plugins:s}=await n(this,qt).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(e=>{this.disablePlugin({id:e.id})}),await Promise.all(s.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))}async enablePlugin({id:s,enabledBy:t}){const e=this.plugins.all.get(s);e&&(await e.activateForSelf(),e.enabledBy=t)}async disablePlugin({id:s}){const t=this.plugins.all.get(s);t&&t.deactivateForSelf()}sendIframeEvent(s,t,e,r){const i=this.plugins.all.get(t);i&&i.sendIframeEvent({type:s,uuid:e,payload:r})}broadcastIframeEvent(s,t){this.plugins.active.forEach(e=>{this.sendIframeEvent(s,e.id,"",t)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),n(this,as).getValue("peerSessionStore").onAsync(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{await this.getRoomPlugins(),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")}),n(this,qt).on(F.addPlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active||await this.enablePlugin({id:t,enabledBy:s.enabledBy})}),n(this,qt).on(F.removePlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active&&await this.disablePlugin({id:t})}),[F.enablePluginForPeers,F.enablePluginForRoom].forEach(s=>{n(this,qt).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{enabledBy:t.enabledBy})})}),[F.disablePluginForPeers,F.disablePluginForRoom].forEach(s=>{n(this,qt).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{disabledBy:t.disabledBy})})}),[F.customPluginEventToPeers,F.customPluginEventToRoom].forEach(s=>{n(this,qt).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{data:JSON.parse(new TextDecoder().decode(t.pluginData))})})}),[F.storeInsertKeys,F.storeGetKeys,F.storeDeleteKeys].forEach(s=>{n(this,qt).on(s,async(t,e)=>{var i;const r=(i=t.storeItems)==null?void 0:i.map(a=>{var o;return{timestamp:a.timestamp,peerId:a.peerId,payload:JSON.parse((o=a.payload)!=null&&o.length?new TextDecoder().decode(a.payload):"{}"),key:a.storeKey}});this.sendIframeEvent(s,t.pluginId,e,{storeName:t.storeName,storeItems:r})})}),n(this,qt).on(F.storeDelete,async(s,t)=>{this.sendIframeEvent(F.storeDelete,s.pluginId,t,{storeName:s.storeName})}),n(this,On).on(Oe.sendMessageToPeers,s=>{const t=Xt==null?void 0:Xt.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(_e.chatMessage,{message:t})}),n(this,On).on(Oe.sendMessageToRoom,s=>{const t=Xt==null?void 0:Xt.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(_e.chatMessage,{message:t})}),n(this,as).getValue("peerSessionStore").on(C.PEER_JOINED_INTERNAL,s=>{const t=nd(s);this.broadcastIframeEvent(_e.peerJoined,t)}),n(this,as).getValue("peerSessionStore").on(C.PEER_CLOSED,s=>{this.broadcastIframeEvent(_e.peerLeft,s)}),n(this,as).getValue("peerSessionStore").on(C.UPDATE_PEER_STAGE_STATUS,s=>{this.broadcastIframeEvent(_e.peerStageStatusUpdate,s)}),n(this,as).subscribe("stageStatus",s=>{this.broadcastIframeEvent(_e.stageStatusUpdate,s)})}},qt=new WeakMap,On=new WeakMap,as=new WeakMap,ig);let bc=af;Pl([y.trace("PluginController.getRoomPlugins")],bc.prototype,"getRoomPlugins",1);Pl([y.trace("PluginController.enableForSelf")],bc.prototype,"enablePlugin",1);Pl([y.trace("PluginController.disableForSelf")],bc.prototype,"disablePlugin",1);Pl([y.trace("PluginController.setupEvents")],bc.prototype,"setupEvents",1);var _o;class LA{constructor(t){h(this,"mediaJoined");h(this,"socketJoined");h(this,"socketJoinAttempted");h(this,"mediaJoinAttempted");h(this,"socketState");h(this,"mediaState");g(this,_o,void 0);this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0},m(this,_o,t)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(t,e){let r;const{reconnected:i}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(n(this,_o).getValue("peerSessionStore").emit(C.SOCKET_STATE_UPDATE,r),this.socketState=r)}}_o=new WeakMap;var VA=Object.defineProperty,xA=Object.getOwnPropertyDescriptor,_c=(s,t,e,r)=>{for(var i=r>1?void 0:r?xA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&VA(t,e,i),i},Nn,Ln,Vn,Gc,ng;let Ji=(ng=class extends Lt{constructor(t,e){const r=t.getValue("logger");super(r);g(this,Vn);g(this,Nn,void 0);g(this,Ln,void 0);h(this,"recordingPeerIds",[]);h(this,"recordings",[]);m(this,Ln,t),m(this,Nn,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}get telemetry(){return n(this,Ln).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!n(this,Nn).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new R("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw this.logger.error("Recording::start::recording_in_progress",{recording:{state:this.recordingState}}),new R(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=ht(),{recording:r={}}=n(this,Ln).getValue("defaults"),i=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("Recording::stop::recording_failed_to_start",{error:e}),new R("Error while starting recording","1000",this.logger)}}async stop(t){await L(this,Vn,Gc).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await L(this,Vn,Gc).call(this,"pause",["RECORDING"],t)}async resume(t){await L(this,Vn,Gc).call(this,"resume",["PAUSED"],t)}},Nn=new WeakMap,Ln=new WeakMap,Vn=new WeakSet,Gc=async function(t,e,r){if(!n(this,Nn).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new R("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const a=this.recordings.find(o=>o.id===r);if(a===void 0)throw new R("Could not find the specified recording","1004");if(e.includes(a.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:a.state}});return}i.push(a)}else i=this.recordings.filter(a=>e.includes(a.state));i.forEach(async a=>{const o=a.state;t==="stop"&&(a.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await ht().updateRecording(a.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),a.state!==o&&(a.state=o,this.emit("recordingUpdate",o)),new R("Error while stopping recording","1000",this.logger)}})},ng);_c([y.trace("Recording.start")],Ji.prototype,"start",1);_c([y.trace("Recording.stop")],Ji.prototype,"stop",1);_c([y.trace("Recording.stop")],Ji.prototype,"pause",1);_c([y.trace("Recording.stop")],Ji.prototype,"resume",1);Ji=_c([rt("1000")],Ji);var UA=Object.defineProperty,$A=Object.getOwnPropertyDescriptor,BA=(s,t,e,r)=>{for(var i=r>1?void 0:r?$A(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&UA(t,e,i),i},li;class of{constructor(t,e,r){h(this,"recording");h(this,"room");g(this,li,void 0);m(this,li,t),this.recording=new Ji(t,e),this.room=r,this.setupEvents()}get telemetry(){return n(this,li).getValue("telemetry")}get logger(){return n(this,li).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case ji.BROWSER:e="BROWSER";break;case ji.COMPOSITE:e="COMPOSITE";break;case ji.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){n(this,li).getValue("peerSessionStore").on(C.ROOM_STATE,t=>{t.activeRecordings.length!==0?this.recording.updateRecordings(t.activeRecordings.map(e=>{const r=this.getRecordingTypeFromProtoType(e.recordingType);return{id:e.recordingId,state:e.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(V.recordingStarted,t=>{let e=!1;const r=[...this.recording.recordings];if(r.forEach(i=>{i.id===t.recordingId&&(e=!0,i.state="RECORDING")}),e===!1){const i=this.getRecordingTypeFromProtoType(t.recordingType);r.push({id:t.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(r)}),this.room.on(V.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(V.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}li=new WeakMap;BA([y.trace("RecordingController.setupEvents")],of.prototype,"setupEvents",1);var ui;class HA{constructor(t){g(this,ui,void 0);m(this,ui,t)}hasFeature(t){return n(this,ui).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return n(this,ui).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return n(this,ui).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}ui=new WeakMap;class oh{constructor(t,e,r,i){h(this,"authToken");h(this,"logger");h(this,"features");h(this,"browserSpecs");h(this,"callStats");this.authToken=t,this.logger=e,this.features=r,this.browserSpecs=ge,this.callStats=i}static init(t){return new oh(t.getValue("authToken"),t.getValue("logger"),new HA(t),t.getValue("callstats"))}}class ch{constructor(t){h(this,"internals");this.internals=t}static async init(t){const e=oh.init(t);return new ch(e)}}var FA=Object.defineProperty,qA=Object.getOwnPropertyDescriptor,Vt=(s,t,e,r)=>{for(var i=r>1?void 0:r?qA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FA(t,e,i),i},Le,he,oe,Bs,jt,Co,be;class Pt extends Pa{constructor(e,r,i=ad,a=!0){const o=e.getValue("logger");super(o);g(this,Le,void 0);g(this,he,void 0);g(this,oe,void 0);g(this,Bs,void 0);g(this,jt,void 0);g(this,Co,void 0);g(this,be,void 0);h(this,"audioUpdateInProgress");h(this,"videoUpdateInProgress");m(this,be,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,m(this,Le,new cf(e,r)),m(this,he,new h0(e,n(this,Le),void 0,i)),m(this,oe,new v0(e,n(this,Le),void 0,i)),m(this,jt,new f0(n(this,be),n(this,Le))),m(this,Bs,new g0(e,n(this,Le))),m(this,Co,a),n(this,he).on("trackMuted",this.onAudioTrackMuted.bind(this)),n(this,he).on("trackChanged",this.onAudioTrackChanged.bind(this)),n(this,oe).on("trackChanged",this.onVideoTrackChanged.bind(this)),n(this,oe).on("trackEnded",this.onVideoTrackEnded.bind(this)),n(this,jt).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return n(this,be).getValue("telemetry")}set context(e){m(this,be,e)}async onVisibilityChange(){n(this,be).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?n(this,be).getValue("callstats").browserBackgrounded():(n(this,be).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?n(this,be).getValue("callstats").audioOn():n(this,be).getValue("callstats").audioOff(),r?n(this,be).getValue("callstats").videoOn():n(this,be).getValue("callstats").videoOff();let i,a;if(e&&r)try{const c=await n(this,Le).getAudioAndVideoTrack(n(this,he).userSelectedDevice,n(this,oe).userSelectedDevice);i=c.audioTrack,a=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await n(this,Le).getAudioTrack(!1,n(this,he).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!a&&r)try{a=await n(this,Le).getVideoTrack(n(this,oe).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&n(this,be).getValue("callstats").audioOff(),r&&!a&&n(this,be).getValue("callstats").videoOff(),await n(this,he).setMediaTrack(i),await n(this,oe).setMediaTrack(a);try{await this.setupSpeaker()}catch(c){}if(a){const c=await this.getDeviceById(a.getSettings().deviceId);n(this,be).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);n(this,be).getValue("callstats").selectedDevice("AUDIO",c)}(o=n(this,Bs).currentDevice)!=null&&o.deviceId&&n(this,be).getValue("callstats").selectedDevice("SPEAKER",n(this,Bs).currentDevice),n(this,Le).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:n(this,he).currentDevice,video:n(this,oe).currentDevice,speaker:n(this,Bs).currentDevice}}get permissions(){return n(this,Le).permissions}getAllDevices(){return n(this,Le).getAvailableDevices()}getDeviceById(e,r){return n(this,Le).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return n(this,he).mediaTrack}get audioTrack(){return n(this,he).transformedMediaTrack}get audioEnabled(){return n(this,he).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await n(this,he).enableTrack(!1,e):await n(this,he).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){n(this,he).mediaTrack&&!n(this,he).isCustomTrack?n(this,he).muteTrack():n(this,he).disableTrack()}getAudioDevices(e){return n(this,Le).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await n(this,he).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,be).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await n(this,Bs).setPreferredSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})}async setSpeakerDevice(e,{saveDevicePreference:r}){await n(this,Bs).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,be).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return n(this,oe).mediaTrack}get videoTrack(){return n(this,oe).transformedMediaTrack}get videoEnabled(){return n(this,oe).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await n(this,oe).enableTrack(!1,e):await n(this,oe).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){n(this,oe).disableTrack()}getVideoDevices(e){return n(this,Le).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await n(this,oe).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,be).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await n(this,oe).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:n(this,jt).audioMediaTrack,video:n(this,jt).videoMediaTrack}}get screenShareEnabled(){return n(this,jt).trackEnabled}async enableScreenShare(){await n(this,jt).enableScreenShare()}async disableScreenShare(){n(this,jt).disableScreenShare()}async updateScreenshareConstraints(e){await n(this,jt).updateConstraints(e)}getSpeakerDevices(e){return n(this,Le).getAudioOutputDevices(e)}addAudioMiddleware(e){return n(this,he).addMiddleware(e)}removeAudioMiddleware(e){return n(this,he).removeMiddleware(e)}removeAllAudioMiddlewares(){return n(this,he).removeAllMiddlewares()}addVideoMiddleware(e){return n(this,oe).addMiddleware(e)}removeVideoMiddleware(e){return n(this,oe).removeMiddleware(e)}removeAllVideoMiddlewares(){return n(this,oe).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return n(this,oe).setVideoMiddlewareGlobalConfig(e)}destruct(){n(this,he).disableTrack(),n(this,oe).disableTrack(),n(this,oe).terminateMiddlewareWebWorker(),n(this,jt).disableScreenShare(),n(this,Le).destruct()}async onDeviceChange(e,r){var a,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!n(this,Co))return;let i=!1;(a=e==null?void 0:e.added)==null||a.reverse().forEach(async c=>{var d;c&&!ad(c)&&(c.kind==="audioinput"&&((d=this.audioTrack)==null?void 0:d.enabled)===!0?await this.setAudioDevice(c,{saveDevicePreference:!1}):c.kind==="audiooutput"&&(i=!0,await this.setSpeakerDevice(c,{saveDevicePreference:!1})))}),i||(o=e==null?void 0:e.removed)==null||o.forEach(async c=>{var d;if(c.kind==="audiooutput"&&((d=this.getCurrentDevices().speaker)==null?void 0:d.deviceId)===c.deviceId){const l=await this.getSpeakerDevices();(l==null?void 0:l.length)>0&&await this.setSpeakerDevice(l[0],{saveDevicePreference:!1})}})}removeAllTracks(){this.destruct()}removeAudioTrack(){n(this,he).disableTrack()}removeVideoTrack(){n(this,oe).disableTrack(),n(this,oe).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Le=new WeakMap,he=new WeakMap,oe=new WeakMap,Bs=new WeakMap,jt=new WeakMap,Co=new WeakMap,be=new WeakMap;Vt([y.trace("MediaHandler.setupStreams")],Pt.prototype,"setupStreams",1);Vt([y.trace("MediaHandler.enableAudio")],Pt.prototype,"enableAudio",1);Vt([y.trace("MediaHandler.disableAudio")],Pt.prototype,"disableAudio",1);Vt([y.trace("MediaHandler.setAudioDevice")],Pt.prototype,"setAudioDevice",1);Vt([y.trace("MediaHandler.enableVideo")],Pt.prototype,"enableVideo",1);Vt([y.trace("MediaHandler.disableVideo")],Pt.prototype,"disableVideo",1);Vt([y.trace("MediaHandler.setVideoDevice")],Pt.prototype,"setVideoDevice",1);Vt([y.trace("MediaHandler.updateVideoConstraints")],Pt.prototype,"updateVideoConstraints",1);Vt([y.trace("MediaHandler.enableScreenShare")],Pt.prototype,"enableScreenShare",1);Vt([y.trace("MediaHandler.disableScreenShare")],Pt.prototype,"disableScreenShare",1);Vt([y.trace("MediaHandler.updateScreenshareConstraints")],Pt.prototype,"updateScreenshareConstraints",1);Vt([y.trace("MediaHandler.destruct")],Pt.prototype,"destruct",1);Vt([y.trace("MediaHandler.onDeviceChange")],Pt.prototype,"onDeviceChange",1);function Lc(s,t,e){switch(!0){case ge.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case ge.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case ge.isFirefox():switch(t){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const jA=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function ad(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=ge._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:jA.some(i=>t==null?void 0:t.includes(i))}async function GA(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,a=await Promise.all(t==null?void 0:t.map(d=>d(i))),o=i.createMediaStreamSource(new MediaStream([e])),c=i.createMediaStreamDestination();try{let d=o;for(let l=0;l<a.length;l+=1)d.connect(a[l]),d=a[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}var hi,wo;class WA{constructor(t){g(this,hi,void 0);g(this,wo,void 0);m(this,wo,t)}get logger(){return n(this,wo).getValue("logger")}terminateMiddlewareWebWorker(){if(n(this,hi))try{Uc.clearInterval(n(this,hi)),m(this,hi,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),a=await Promise.all(t==null?void 0:t.map(f=>f({canvas:i,WorkerTimers:Uc})));if(r.disablePerFrameCanvasRendering){const T=i.captureStream().getVideoTracks()[0];return Object.defineProperty(T,"originalSettings",{value:e.getSettings()}),T}const o=document.createElement("video"),c=new MediaStream;c.addTrack(e);const d=i.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let f=0;f<a.length;f+=1)typeof a[f]=="function"&&await a[f](i,d)}catch(f){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:f})}};try{o.play()}catch(f){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,m(this,hi,Uc.setInterval(l,50))},!1);const p=i.captureStream().getVideoTracks()[0];return Object.defineProperty(p,"originalSettings",{value:e.getSettings()}),p}}hi=new WeakMap,wo=new WeakMap;const JA={qvga:{width:{ideal:320},height:{ideal:240},frameRate:{ideal:30}},vga:{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30}},hd:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},fhd:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},uhd:{width:{ideal:3840},height:{ideal:2160},frameRate:{ideal:30}}},KA=[[320,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[640,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[1280,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[1920,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[3840,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]]],zA=(s,t)=>{var d,l,u;const e=(d=s==null?void 0:s.getValue("overrides"))==null?void 0:d.simulcastConfig;if((l=e==null?void 0:e.encodings)!=null&&l.length)return e.encodings;const r="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((u=t.originalSettings)==null?void 0:u.width),i=KA,a=i.map(([p])=>p).sort((p,f)=>p-f);let o=Number.MAX_VALUE,c=0;return a.forEach((p,f)=>{Math.abs(p-r)<o&&(o=Math.abs(p-r),c=f)}),i[c][1]};var Ee=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Ee||{});const YA=I_(),en=ks(YA.config.media);function QA(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}var pi,vd;class XA{constructor(t,e){g(this,pi,void 0);g(this,vd,void 0);h(this,"getScreenShareConstraints",()=>{var l,u,p,f,T,E,b,_,M;const t=(l=n(this,pi))==null?void 0:l.screenshare,e=(p=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?p:1920,r=(T=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?T:1080,i=(b=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?b:5,a=(M=(_=t==null?void 0:t.frameRate)==null?void 0:_.ideal)!=null?M:5,o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;let d={width:{max:e},height:{max:r},frameRate:{ideal:a,max:i}};return o!==void 0&&["monitor","browser","window"].includes(o)&&(d={...d,displaySurface:o}),c!==void 0&&(d={...d,selfBrowserSurface:c}),{audio:!0,video:d}});h(this,"getAudioConstraints",t=>{var a,o,c,d,l,u,p;const e={},r=(a=n(this,pi))==null?void 0:a.audio,i=r!=null&&r.enableStereo?2:1;return ge.isFirefox()||ge.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(o=r==null?void 0:r.autoGainControl)!=null?o:!0,echoCancellation:(c=r==null?void 0:r.echoCancellation)!=null?c:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:i},e):(e.audio={autoGainControl:(l=r==null?void 0:r.autoGainControl)!=null?l:!0,echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0,noiseSuppression:(p=r==null?void 0:r.noiseSupression)!=null?p:!0,channelCount:i},t&&(e.audio.deviceId={exact:t}),e)});h(this,"getVideoConstraints",t=>{var o,c,d;const e={},r=(o=n(this,pi))==null?void 0:o.video,i=WP(JA);let a=i.vga;if(typeof r=="string"){const l=i[r];l&&(a=l)}else r!==void 0&&(a.height.ideal=r.height.ideal,a.width.ideal=r.width.ideal,a.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=a,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});m(this,vd,t),m(this,pi,e)}getUpdatedVideoConstraints(t){return t}}pi=new WeakMap,vd=new WeakMap;class Gl extends Error{constructor(e,r,i){super(r);h(this,"constraints");h(this,"name");this.name=e,this.constraints=i}}class ZA{constructor(){h(this,"permissions");this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}async getAudioInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audioinput")}async getVideoInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="videoinput")}async getAudioOutputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audiooutput")}}var e0=Object.defineProperty,t0=Object.getOwnPropertyDescriptor,ys=(s,t,e,r)=>{for(var i=r>1?void 0:r?t0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&e0(t,e,i),i},xn,Gt,He,ag;let Nt=(ag=class extends ZA{constructor(t,e){super();g(this,xn,void 0);g(this,Gt,void 0);g(this,He,void 0);m(this,He,t),m(this,Gt,new XA(t,e)),m(this,xn,new AbortController)}get telemetry(){return n(this,He).getValue("telemetry")}get logger(){return n(this,He).getValue("logger")}get constraintsBuilder(){return n(this,Gt)}async destruct(){var t;(t=n(this,xn))==null||t.abort()}handlePermissionErrors(t,e){const r=Lc(t,e.name,e.message);return this.permissions[t]=r,n(this,He).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,a,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(M=>M.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const p=!!(d!=null&&d.find(M=>M.deviceId===e));let f;e&&p?f=e:d&&((a=d[0])!=null&&a.deviceId)&&(f=(o=d[0])==null?void 0:o.deviceId);const T={audio:n(this,Gt).getAudioConstraints(u).audio,video:n(this,Gt).getVideoConstraints(f).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(T)});const E=await navigator.mediaDevices.getUserMedia(T);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(T)});const b=E.getAudioTracks()[0];let _=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",_.label.includes("OBS Virtual")){const A=(await this.getVideoInputDevices()).find(x=>x.label.includes("OBS Virtual"));_=await this.getVideoTrack(A.deviceId)}return n(this,He).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),n(this,He).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:b,videoTrack:_}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new R("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",n(this,He).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new R("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let a;e&&i?a=e:(c=r[0])!=null&&c.deviceId&&(a=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(f=>f.deviceId!==l),u=n(this,Gt).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[p]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),p}catch(p){const f=Lc("audio",p.name,p.message),T=new Gl(p.name,p.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw T;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const b=n(this,Gt).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(b)}),o(E.deviceId)}throw T}};try{const l=await o(a);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",n(this,He).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new R(l.message,"1601")}}async getVideoTrack(t){var c,d,l;const e=(c=await this.getCurrentDeviceLabel(t))==null?void 0:c.includes("OBS Virtual"),r=await this.getVideoInputDevices();if(!(r!=null&&r.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",n(this,He).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new R("No video devices available","1607");const i=!!(r!=null&&r.find(u=>u.deviceId===t));let a;t&&i?a=t:(d=r[0])!=null&&d.deviceId&&(a=(l=r[0])==null?void 0:l.deviceId);const o=async u=>{try{let p=u;const{video:f}=p;e&&typeof f!="boolean"&&(p={video:{deviceId:f.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(p)});const[T]=(await navigator.mediaDevices.getUserMedia(p)).getVideoTracks();if(e&&typeof f!="boolean"&&typeof f.width=="object"){const{width:E,height:b}=T.getSettings(),{ideal:_}=f.width;T.applyConstraints({width:{ideal:_},height:{ideal:Math.floor(b*_/E)},frameRate:f.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(p)}),T}catch(p){const f=Lc("video",p.name,p.message),T=new Gl(p.name,p.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw T;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const b=n(this,Gt).getVideoConstraints(E.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(b)}),o({video:b.video})}throw T}};try{const u=n(this,Gt).getVideoConstraints(a),p=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",n(this,He).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),p}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new R(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),n(this,He).getValue("callstats").screenShareRequested();const r=await navigator.mediaDevices.getDisplayMedia(e);return this.logger.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const i=Lc("video",r.name,r.message),a=new Gl(r.name,r.message,e),o={video:!0};if(e_(e,o))throw a;if(i==="COULD_NOT_START")return t(o);throw a}};try{const e=n(this,Gt).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",n(this,He).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new R(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const a=((o=i.label)==null?void 0:o.toLowerCase())||"";return ad(i)?4:a.includes("airpods")||a.includes("airdopes")||a.includes("bluetooth")||a.includes("wireless")||a.includes("headphones")||a.includes("headset")||a.includes("earbuds")||a.includes("usb")||a.includes("external")?0:i.deviceId==="default"||a.includes("default")?1:a.includes("built-in")||a.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const a=((o=i.label)==null?void 0:o.toLowerCase())||"";return a.includes("front")||a.includes("user")||a.includes("selfie")?!0:!(a.includes("back")||a.includes("rear")||a.includes("environment"))};return t.sort((i,a)=>{var u,p;const o=e(i),c=e(a);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=a.deviceId==="default"||((p=a.label)==null?void 0:p.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&a.kind==="videoinput"){const f=r(i),T=r(a);if(f&&!T)return-1;if(!f&&T)return 1}return 0})}async getAvailableDevices(){try{return await this.enumerateDevicesWithExternalFirst()||[]}catch(t){return this.logger.error("enumerate_devices_failed",{error:t}),[]}}async getAvailableDevicesByKind(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(({kind:e})=>t===e)}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new R("Failed to get available devices by kind","1609")}}async getDevice(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(r=>r.deviceId===t)[0]}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new R("Failed to get device","1609")}}async onDeviceChange(t){if(ge.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;const i=p=>`${p.kind}-${p.label}-${p.deviceId}-${p.groupId}`,a=new Set(e.map(p=>i(p))),o=await this.getAvailableDevices(),c=new Set(o.map(p=>i(p))),d={added:o.filter(p=>!a.has(i(p))),removed:e.filter(p=>!c.has(i(p))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(u=d.removed)!=null&&u.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const p=[...d.added,...d.removed];p.some(f=>f.kind==="audioinput")&&n(this,He).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&n(this,He).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&n(this,He).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(f=>f.kind==="audiooutput")),t(r,d,!1)}},{signal:n(this,xn).signal})}}},xn=new WeakMap,Gt=new WeakMap,He=new WeakMap,ag);ys([y.trace("WebMediaInterface.destruct")],Nt.prototype,"destruct",1);ys([y.trace("WebMediaInterface.handlePermissionErrors")],Nt.prototype,"handlePermissionErrors",1);ys([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Nt.prototype,"getAudioAndVideoTrack",1);ys([y.trace("WebMediaInterface.getAudioTrack")],Nt.prototype,"getAudioTrack",1);ys([y.trace("WebMediaInterface.getVideoTrack")],Nt.prototype,"getVideoTrack",1);ys([y.trace("WebMediaInterface.getScreenShareTracks")],Nt.prototype,"getScreenShareTracks",1);ys([y.trace("WebMediaInterface.getAvailableDevices")],Nt.prototype,"getAvailableDevices",1);ys([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Nt.prototype,"getAvailableDevicesByKind",1);ys([y.trace("WebMediaInterface.getDevice")],Nt.prototype,"getDevice",1);ys([y.trace("WebMediaInterface.onDeviceChange")],Nt.prototype,"onDeviceChange",1);Nt=ys([rt("1600")],Nt);const cf=Nt,Gi={setItem:(s,t,e)=>{try{localStorage.setItem(s,t)}catch(r){e==null||e.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:s,value:t}})}},getItem:(s,t)=>{try{return localStorage.getItem(s)}catch(e){t==null||t.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:s}})}return null}},s0=(s=0)=>new Promise(t=>setTimeout(t,s)),r0=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),a=s.createAnalyser();a.fftSize=2048,i.connect(a);const o=new Uint8Array(a.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(a.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):s0().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},i0=typeof AudioContext!="undefined"?AudioContext:null;class dh{constructor(t){h(this,"_AudioContext");h(this,"audioContext");h(this,"_audioContextRefContainers");const e={AudioContext:i0,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:dh}})}getOrCreate(t){if(!this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.add(t),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(e){}return this.audioContext}release(t){this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.delete(t),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Vp=new dh,n0=3,a0=250;function o0(s){const t={},e=Vp.getOrCreate(t);let r=n0;function i(){return r-=1,r0(e,s.srcObject,a0).then(a=>a?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Vp.release(t)})}async function xp(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const a=e.play();a&&await a,i=await o0(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(a){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:a})}finally{e.pause(),e.remove()}return i}var c0=Object.defineProperty,d0=Object.getOwnPropertyDescriptor,df=(s,t,e,r)=>{for(var i=r>1?void 0:r?d0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&c0(t,e,i),i};let od=class extends Pa{constructor(t,e,r,i){var o;const a=t.getValue("logger");super(a);h(this,"constructorName",this.constructor.name);h(this,"userSelectedDevice");h(this,"mediaInterface");h(this,"isNonPreferredDevice");h(this,"_mediaTrack");h(this,"transformedMediaTrack");h(this,"middlewares",[]);h(this,"currentDevice");h(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);h(this,"setUserPreferredDevice",t=>Gi.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>Gi.getItem(this.userPreferredDeviceKey,this.logger));h(this,"isCustomTrack",!1);h(this,"context");this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(o=this.getUserPreferredDevice())!=null?o:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}async setMediaTrack(t,e=!1){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=await this.conditionallyChangeTrack(t,e),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){r(i)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new R("Failed to unmute track","1611")}}getCurrentDeviceId(){var e;const{kind:t}=this.mediaTrack;switch(t){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((e=i==null?void 0:i.advanced)==null?void 0:e[0].deviceId)||"default":this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}async setCurrentDevice(){var e;if(!this.mediaTrack){this.currentDevice=void 0;return}const t=this.getCurrentDeviceId();((e=this.currentDevice)==null?void 0:e.deviceId)!==t&&(this.currentDevice=await this.mediaInterface.getDevice(t))}async setDevice(t,{saveDevicePreference:e}){if(!t)throw this.logger.warn(`${this.constructorName}.setDevice No device received`),new R("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(ge.isWebKitBased()&&!(ge.isSafari()&&m_.test(ge.getVersion())))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return this.logger.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return this.logger.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}}async removeAllMiddlewares(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return this.logger.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};df([y.trace("BaseMediaHandler.unmuteTrack")],od.prototype,"unmuteTrack",1);od=df([rt("1600")],od);const lf=od;var l0=Object.defineProperty,u0=Object.getOwnPropertyDescriptor,lh=(s,t,e,r)=>{for(var i=r>1?void 0:r?u0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&l0(t,e,i),i};const Wl="[Realtimekit]nonSilentDeviceLabels";class bl extends lf{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new R("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new R("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,this.userSelectedDevice))}catch(e){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new R(e.message,"1604")}}async enableTrack(t,e){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(e){this.isCustomTrack=!0,await this.setMediaTrack(e,!0);return}this.isCustomTrack=!1;const r=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(r)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await GA(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t,e=!1){var d;if(!t||this.userSelectedDevice||e)return t;let r=t;const i=await this.mediaInterface.getAudioInputDevices(),a=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(a!=null&&a.length))return r;a.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,a[0].deviceId));const o=JSON.parse(Gi.getItem(Wl,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await xp(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return Gi.setItem(Wl,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return a.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await xp(this.logger,r)){const p=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return Gi.setItem(Wl,JSON.stringify({devices:p}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}lh([y.trace("AudioMediaHandler.setTransformedTrack")],bl.prototype,"setTransformedTrack",1);lh([y.trace("AudioMediaHandler.onTrackEnded")],bl.prototype,"onTrackEnded",1);lh([y.trace("AudioMediaHandler.conditionallyChangeTrack")],bl.prototype,"conditionallyChangeTrack",1);const h0=bl;var gi;class p0{constructor(t,e){g(this,gi,void 0);h(this,"currentDevice");h(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");h(this,"logger");h(this,"setUserPreferredDevice",t=>Gi.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>Gi.getItem(this.userPreferredDeviceKey,this.logger));m(this,gi,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await n(this,gi).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var a,o;if(!(n(this,gi)instanceof cf))return;let r=t;if(t||([r]=(await n(this,gi).getAvailableDevicesByKind("audiooutput")).filter(d=>!ad(d))),!r)throw new R("No speaker found","1608");if(((a=this.currentDevice)==null?void 0:a.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}gi=new WeakMap;const g0=p0;var Ro;class m0 extends Pa{constructor(e,r){const i=e.getValue("logger");super(i);h(this,"mediaInterface");h(this,"audioMediaTrack");h(this,"videoMediaTrack");g(this,Ro,void 0);m(this,Ro,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:a}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=a,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",n(this,Ro).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}async updateConstraints(e){if(!this.videoMediaTrack)throw new R("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new R("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),ge.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}Ro=new WeakMap;const f0=m0;var T0=Object.defineProperty,S0=Object.getOwnPropertyDescriptor,_l=(s,t,e,r)=>{for(var i=r>1?void 0:r?S0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&T0(t,e,i),i},Un,ko;class Cc extends lf{constructor(e,r,i,a){super(e,r,i,a);g(this,Un,void 0);g(this,ko,{disablePerFrameCanvasRendering:!1});m(this,Un,new WA(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new R("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new R("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){this.logger.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new R("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await n(this,Un).getTransformedVideoTrack(this.middlewares,this.mediaTrack,n(this,ko)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){m(this,ko,e)}async updateConstraints(e){if(!this._mediaTrack)throw new R("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new R("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){n(this,Un).terminateMiddlewareWebWorker()}async onTrackEnded(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e,r=!1){if(!e||this.userSelectedDevice||r)return e;let i=e;const a=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?a.filter(c=>!this.isNonPreferredDevice(c)):a;return!(o!=null&&o.length)||window.FAST_RTK||o.find(c=>c.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=await this.mediaInterface.getVideoTrack(o[0].deviceId)),i}}Un=new WeakMap,ko=new WeakMap;_l([y.trace("VideoMediaHandler.setTransformedTrack")],Cc.prototype,"setTransformedTrack",1);_l([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Cc.prototype,"setVideoMiddlewareGlobalConfig",1);_l([y.trace("VideoMediaHandler.onTrackEnded")],Cc.prototype,"onTrackEnded",1);_l([y.trace("VideoMediaHandler.conditionallyChangeTrack")],Cc.prototype,"conditionallyChangeTrack",1);const v0=Cc,Up=ks(sh());var at,mi,Mo,$n;const cn=class{constructor(t){g(this,at,void 0);g(this,mi,void 0);g(this,Mo,void 0);g(this,$n,void 0);if(!t)throw new R("Could not load preset.","0904");m(this,at,t.config),m(this,Mo,t.name),m(this,mi,t.ui||ks(sh().ui)),m(this,$n,t.permissions.plugins.config)}static fromResponse(t){return new cn(t)}static default(){return new cn(Up)}static init(t,e=!0){return!t||e?new cn(Up):new cn(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:n(this,mi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return n(this,at).viewType}get livestreamViewerQualities(){return n(this,at).livestreamViewerQualities||[]}get maxVideoStreams(){return n(this,at).maxVideoStreams}get maxScreenShareCount(){return n(this,at).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(n(this,$n)).filter(t=>n(this,$n)[t].disabled)}get designTokens(){return n(this,mi).designTokens}get configDiff(){return n(this,mi).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=n(this,at))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,a,o,c,d,l,u,p,f,T,E,b,_,M,A,x,N,$,K,Z,Ue;return{audio:{enableStereo:(i=(r=(e=(t=n(this,at))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:en.audio.enableStereo,enableHighBitrate:(d=(c=(o=(a=n(this,at))==null?void 0:a.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:en.audio.enableHighBitrate},video:{quality:(f=(p=(u=(l=n(this,at))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:p.quality)!=null?f:en.video.quality,frameRate:(_=(b=(E=(T=n(this,at))==null?void 0:T.media)==null?void 0:E.video)==null?void 0:b.frameRate)!=null?_:en.video.frameRate},screenshare:{quality:(N=(x=(A=(M=n(this,at))==null?void 0:M.media)==null?void 0:A.screenshare)==null?void 0:x.quality)!=null?N:en.screenshare.quality,frameRate:(Ue=(Z=(K=($=n(this,at))==null?void 0:$.media)==null?void 0:K.screenshare)==null?void 0:Z.frameRate)!=null?Ue:en.screenshare.frameRate}}}get name(){return n(this,Mo)}};let fu=cn;at=new WeakMap,mi=new WeakMap,Mo=new WeakMap,$n=new WeakMap;var y0=Object.defineProperty,E0=Object.getOwnPropertyDescriptor,uf=(s,t,e,r)=>{for(var i=r>1?void 0:r?E0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&y0(t,e,i),i},Bn,Io;class uh extends Lt{constructor(e,r){const i=e.getValue("logger");super(i);g(this,Bn,void 0);h(this,"state","IDLE");h(this,"playbackUrl");h(this,"ingestionCredentials");h(this,"viewerCount");g(this,Io,void 0);m(this,Bn,r),m(this,Io,e),this.viewerCount=0}get telemetry(){return n(this,Io).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(e={manualIngestion:!1}){if(!n(this,Bn).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new R("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=ht(),{playbackUrl:i,ingestionCredentials:a}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=a,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new R("Error while starting livestream","1900",this.logger)}}async stop(){if(!n(this,Bn).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new R("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw this.logger.error("Livestream::stop::inconsistent_state"),new R("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await ht().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new R("Error while stopping livestream","1900",this.logger)}}}Bn=new WeakMap,Io=new WeakMap;uf([y.trace("livestream.start")],uh.prototype,"start",1);uf([y.trace("livestream.stop")],uh.prototype,"stop",1);var P0=Object.defineProperty,b0=Object.getOwnPropertyDescriptor,_0=(s,t,e,r)=>{for(var i=r>1?void 0:r?b0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&P0(t,e,i),i},Hn,Fn,Hs,Ps;class hf{constructor(t,e,r){h(this,"livestream");g(this,Hn,void 0);g(this,Fn,void 0);g(this,Hs,void 0);g(this,Ps,void 0);m(this,Ps,t),m(this,Fn,e),this.livestream=new uh(t,e),m(this,Hs,r),this.setupEvents()}get logger(){return n(this,Ps).getValue("logger")}get telemetry(){return n(this,Ps).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=ht(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:a}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=a,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){n(this,Hs).on(V.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{n(this,Fn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),n(this,Hs).on(V.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{n(this,Fn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),n(this,Hs).on(V.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),n(this,Hs).on(V.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),n(this,Hs).on(V.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),n(this,Ps).getValue("peerSessionStore").on(C.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(m(this,Hn,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),n(this,Ps).getValue("peerSessionStore").on(C.PEER_CLOSED,t=>{t.id===n(this,Hn)&&(m(this,Hn,void 0),this.livestream.setLivestreamState("IDLE"))}),n(this,Ps).getValue("peerSessionStore").onAsync(C.LEAVE_MEDIA_ROOM,async()=>{if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:t})}}}),n(this,Ps).getValue("peerSessionStore").on(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Hn=new WeakMap,Fn=new WeakMap,Hs=new WeakMap,Ps=new WeakMap;_0([y.trace("LivestreamController.setupEvents")],hf.prototype,"setupEvents",1);var C0=Object.defineProperty,w0=Object.getOwnPropertyDescriptor,wc=(s,t,e,r)=>{for(var i=r>1?void 0:r?w0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&C0(t,e,i),i},Xe,wr,Rr,yd,pf;class _a{constructor({name:t,socketHandler:e,meetingId:r}){g(this,yd);h(this,"name","");g(this,Xe,{});g(this,wr,"");g(this,Rr,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});h(this,"listeners",{});this.name=t,m(this,Rr,e),m(this,wr,r)}async set(t,e,r=!0,i=!1){n(this,Xe)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(a=>a({[t]:n(this,Xe)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(a=>a({[t]:n(this,Xe)[t]})))}remoteSet(t,e){n(this,Rr).storeInsertKeys(n(this,wr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{n(this,Xe)[e]=r}),n(this,Rr).storeInsertKeys(n(this,wr),this.name,t)}async update(t,e,r=!0){L(this,yd,pf).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(n(this,Xe)[t]&&delete n(this,Xe)[t],e)return n(this,Rr).storeDeleteKeys(n(this,wr),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(i=>i({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{n(this,Xe)[e]&&delete n(this,Xe)[e]}),n(this,Rr).storeDeleteKeys(n(this,wr),this.name,t)}get(t){if(n(this,Xe)[t])return n(this,Xe)[t]}getAll(){return n(this,Xe)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){m(this,Xe,t)}}Xe=new WeakMap,wr=new WeakMap,Rr=new WeakMap,yd=new WeakSet,pf=function(t,e,r=!0){let i;const a=n(this,Xe)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(a);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...a,...e];break;case"[object Object]":i={...a,...e};break;case"[object Map]":i=new Map([...a,...e]);break;case"[object Set]":i=new Set([...a,...e]);break;default:i=e;break}this.set(t,i,r)};wc([Et(ba,"rateLimitConfig")],_a.prototype,"remoteSet",1);wc([Et(ba,"bulkRateLimitConfig")],_a.prototype,"bulkSet",1);wc([Et(ba,"rateLimitConfig")],_a.prototype,"update",1);wc([Et(ba,"rateLimitConfig")],_a.prototype,"delete",1);wc([Et(ba,"bulkRateLimitConfig")],_a.prototype,"bulkDelete",1);var fi,Ti,Ao,Tu,Do,kr,Ed,gf;class R0{constructor(t,e){g(this,Ao);g(this,Ed);h(this,"stores",new Map);g(this,fi,void 0);g(this,Ti,"");g(this,Do,void 0);g(this,kr,new Map);m(this,fi,e),m(this,Ti,t.getValue("meetingId")),m(this,Do,t),L(this,Ed,gf).call(this)}create(t){const e=new _a({name:t,socketHandler:n(this,fi),meetingId:n(this,Ti)});return n(this,fi).storeGetKeys(n(this,Ti),t,[]),new Promise((i,a)=>{const o=setTimeout(()=>a(Error("Failed")),3e3);n(this,kr).set(t,{rejectTimeout:o,resolve:i,store:e})})}}fi=new WeakMap,Ti=new WeakMap,Ao=new WeakSet,Tu=function(){return n(this,Do).getValue("peerId")},Do=new WeakMap,kr=new WeakMap,Ed=new WeakSet,gf=function(){[F.storeInsertKeys,F.storeGetKeys,F.storeDeleteKeys].forEach(t=>{n(this,fi).on(t,async e=>{var a,o;if(e.pluginId!==n(this,Ti))return;const r=(a=e.storeItems)==null?void 0:a.map(c=>{var d;return{timestamp:c.timestamp,peerId:c.peerId,payload:JSON.parse((d=c.payload)!=null&&d.length?new TextDecoder().decode(c.payload):"{}"),key:c.storeKey}});if(t===F.storeGetKeys){const c=n(this,kr).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);n(this,kr).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),n(this,kr).delete(e.storeName)),r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=n(this,kr).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===F.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==n(this,Ao,Tu)&&i.set(c,l,!1,!0)}),t===F.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==n(this,Ao,Tu)&&i.delete(c,!1,!0)}))})})};function ti(s){var t,e,r,i,a,o,c,d,l,u,p,f,T;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(a=s.mediaPermissions)==null?void 0:a.screenshare:null,audio:{enabled:(c=(o=s.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(p=(u=s.screenShareTracks)==null?void 0:u.video)==null?void 0:p.enabled,trackId:(T=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:T.id}}}}:{}}var k0=Object.defineProperty,M0=Object.getOwnPropertyDescriptor,Ca=(s,t,e,r)=>{for(var i=r>1?void 0:r?M0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&k0(t,e,i),i};const I0=.8,A0=1.2;var qn,jn,kt,Si,Wa,Mr,rn,vi,Ja,Pd,mf,Fs,Oo,Ir,yi,Ka,qs,bd,No,Su,_d,ff,Cd,Tf,og;let cr=(og=class extends Lt{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,Si);g(this,Mr);g(this,vi);g(this,Pd);g(this,yi);g(this,No);g(this,_d);g(this,Cd);h(this,"id");h(this,"userId");h(this,"name");h(this,"picture");h(this,"isHost");h(this,"customParticipantId");h(this,"flags");h(this,"device");h(this,"videoTrack");h(this,"audioTrack");h(this,"screenShareTracks");h(this,"videoEnabled");h(this,"audioEnabled");h(this,"screenShareEnabled");h(this,"producers");h(this,"manualProducerConfig");g(this,qn,void 0);h(this,"supportsRemoteControl",!1);g(this,jn,void 0);h(this,"presetName");g(this,kt,void 0);g(this,Fs,void 0);g(this,Oo,void 0);g(this,Ir,new Map);g(this,qs,1);g(this,bd,th(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:a}=this.videoTrack.getSettings();if(!i||!a)return;const o=a/r,c=i/e,d=Math.max(o,c);d>A0&&n(this,qs)===1?(m(this,qs,0),n(this,kt).getValue("peerSessionStore").emit(C.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,qs)})):d<I0&&n(this,qs)===0&&(m(this,qs,1),n(this,kt).getValue("peerSessionStore").emit(C.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,qs)}))},2e3));m(this,kt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:p,flags:f,clientSpecificId:T,stageStatus:E,customParticipantId:b,audioMuted:_,audioTrack:M,videoEnabled:A=!1,videoTrack:x,producers:N,metadata:$}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=p,this.flags=f,this.manualProducerConfig=c_,m(this,jn,E!=null?E:"ON_STAGE"),this.customParticipantId=b!=null?b:T,this.audioEnabled=!_,this.audioTrack=M,this.videoEnabled=A,this.videoTrack=x,this.screenShareTracks={audio:void 0,video:void 0},this.producers=N!=null?N:[],this.presetName=$==null?void 0:$.preset_name,m(this,qn,!1),m(this,Fs,r),m(this,Oo,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),L(this,No,Su).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return n(this,jn)}get telemetry(){return n(this,kt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...ti(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...ti(this)}),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",L(this,No,Su)),n(this,Mr,rn)&&(this.on("audioUpdate",L(this,_d,ff)),this.on("screenShareUpdate",L(this,Cd,Tf)))}async pin(){if(!n(this,vi,Ja))throw new R("Can`t pin participant without joining room","1205");if(!n(this,Fs).permissions.pinParticipant)throw new R("You do not have permission to pin participants.","1201");return n(this,Si,Wa).pinPeer(this.id)}async unpin(){if(!n(this,vi,Ja))throw new R("Can`t unpin participant without joining room","1205");if(!n(this,Fs).permissions.pinParticipant)throw new R("You do not have permission to unpin participants.","1201");return n(this,Si,Wa).pinPeer(null)}setIsPinned(t,e=!0){var i;m(this,qn,t);const r=t?"pinned":"unpinned";(i=n(this,yi,Ka))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info("Participant::disable_audio",{participant:{id:t}}),!n(this,vi,Ja))throw new R("Can`t disable participant audio without joining room","1205");if(n(this,Fs).permissions.canDisableParticipantAudio)return n(this,Si,Wa).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new R("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info("Participant::kick",{participant:{id:t}}),!n(this,Pd,mf))throw new R("Can`t kick participant without joining room","1205");if(n(this,Fs).permissions.kickParticipant){await n(this,kt).getValue("peerSessionStore").emitAsync(C.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new R("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info("Participant::disable_video",{participant:{id:t}}),!n(this,vi,Ja))throw new R("Can`t disable participant video without joining room","1205");if(n(this,Fs).permissions.canDisableParticipantVideo)return n(this,Si,Wa).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new R("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return n(this,Oo).getUserPermissions(this.userId)}setStageStatus(t){m(this,jn,t),this.emit("stageStatusUpdate",this)}get isPinned(){return n(this,qn)}registerVideoElement(t){var r,i,a,o;if(!t)return;let e;(i=(r=n(this,Ir).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>n(this,bd).call(this,t)),e.observe(t)),n(this,Ir).set(t,{observer:e}),this.updateVideo(t),(o=n(this,yi,Ka))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(a=this.raised)!=null?a:!1)}deregisterVideoElement(t){var e,r,i,a;if(!t){(e=n(this,yi,Ka))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=n(this,Ir).get(t))==null?void 0:r.observer)==null||i.disconnect(),n(this,Ir).delete(t),(a=n(this,yi,Ka))==null||a.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},qn=new WeakMap,jn=new WeakMap,kt=new WeakMap,Si=new WeakSet,Wa=function(){return n(this,kt).getValue("roomNodeClient")},Mr=new WeakSet,rn=function(){return n(this,kt).getValue("audioPlayback")},vi=new WeakSet,Ja=function(){return n(this,kt).getValue("connectionHandler").mediaJoined},Pd=new WeakSet,mf=function(){return n(this,kt).getValue("connectionHandler").socketJoined},Fs=new WeakMap,Oo=new WeakMap,Ir=new WeakMap,yi=new WeakSet,Ka=function(){return n(this,kt).getValue("pip")},qs=new WeakMap,bd=new WeakMap,No=new WeakSet,Su=function(){Array.from(n(this,Ir).keys()).forEach(this.updateVideo)},_d=new WeakSet,ff=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=n(this,Mr,rn))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=n(this,Mr,rn))==null||e.removeParticipantTrack(this.id)},Cd=new WeakSet,Tf=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=n(this,Mr,rn))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=n(this,Mr,rn))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},og);Ca([y.trace("Participant.disableAudio")],cr.prototype,"disableAudio",1);Ca([y.trace("Participant.kick")],cr.prototype,"kick",1);Ca([y.trace("Participant.disableVideo")],cr.prototype,"disableVideo",1);Ca([y.trace("Participant.getPermissions")],cr.prototype,"getPermissions",1);Ca([y.trace("Participant.setStageStatus")],cr.prototype,"setStageStatus",1);cr=Ca([rt("1200")],cr);class Ga extends nf{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:a="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:a},t)}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var Ar;class D0 extends Pa{constructor(e){super(e);g(this,Ar,void 0);m(this,Ar,new Map)}__set(e,r){return n(this,Ar).set(e,r)}__clear(){return n(this,Ar).clear()}get(e){return n(this,Ar).get(e)}toArray(){return Array.from(n(this,Ar).values())}}Ar=new WeakMap;class O0{constructor(){h(this,"_orderedArray");h(this,"_map");this._map=new Map,this._orderedArray=[]}add(t,e){if(!this._map.has(t))return this._map.set(t,{peerId:t,priority:e}),this._orderedArray.splice(Math.max(e-1,0),0,t),this.index(t);const r=this.index(t);this.delete(t);const i=this.add(t,e);return r!==i?i:-1}delete(t){if(this._map.has(t)){const e=this.index(t);this._map.delete(t),this._orderedArray.splice(e,1)}}index(t){return this._map.has(t)?this._orderedArray.indexOf(t):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class N0{constructor(){h(this,"_activeSpeakerPeers");h(this,"_compulsoryPeers");this._activeSpeakerPeers=new O0,this._compulsoryPeers=new Set}add(t,e,r){if(!t)return-1;if(e<0)return this._compulsoryPeers.add(t),0;const i=r.getValue("logger");if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(i.info("SelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t,r),-1;return this._activeSpeakerPeers.add(t,e)}delete(t,e){const r=e==null?void 0:e.getValue("logger");r==null||r.info("SelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}index(t){return this._activeSpeakerPeers.index(t)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(t){this._compulsoryPeers.delete(t)}}const Sf=new N0;var L0=Object.defineProperty,V0=Object.getOwnPropertyDescriptor,xt=(s,t,e,r)=>{for(var i=r>1?void 0:r?V0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&L0(t,e,i),i};const x0=["ACTIVE_GRID","PAGINATED","MANUAL"];var Se,Lo,vu,Ei,za,Gn,Wc,Pi,mt,cg;let pt=(cg=class extends Lt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Lo);g(this,Ei);g(this,Gn);h(this,"waitlisted");h(this,"joined");h(this,"active");h(this,"videoSubscribed");h(this,"audioSubscribed");h(this,"pinned");h(this,"all");g(this,Se,void 0);g(this,Pi,void 0);g(this,mt,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"viewMode");h(this,"currentPage");h(this,"lastActiveSpeaker");h(this,"selectedPeers",Sf);m(this,Se,t),m(this,Pi,e),m(this,mt,r),this.waitlisted=new Ga(i),this.joined=new Ga(i),this.videoSubscribed=new Ga(i),this.audioSubscribed=new Ga(i),this.active=this.videoSubscribed,this.pinned=new Ga(i),this.all=new D0(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return n(this,Se).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return n(this,Se).getValue("telemetry")}setupEvents(){n(this,Se).getValue("peerSessionStore").on(C.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=n(this,Se).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=n(this,Se).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=n(this,Se))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new R("0 <= Max active participants count limit <= 24","1203");n(this,Se).setValue("maxPreferredStreams",t),n(this,Gn,Wc)&&n(this,Se).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var r,i;if(!n(this,Ei,za))throw new R("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return n(this,mt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,a;return(a=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?a:r});return n(this,mt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!n(this,Ei,za))throw new R("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;n(this,mt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(this.logger.info("Participants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>x0.includes(r))(t))throw this.logger.error("Participants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new R(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,n(this,Se).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,n(this,Se).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,n(this,Se).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new R("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),n(this,Se).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new R("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),n(this,Se).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),a=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(a,o))}async setPage(t){if(this.logger.info("Participants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw this.logger.error("Participants::invalid_page_number"),new R(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,n(this,Se).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(this.logger.info("Participants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!n(this,Gn,Wc))throw new R("Can`t disable all audio without joining room","1205");if(n(this,Pi).permissions.canAllowParticipantAudio)return n(this,Lo,vu).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new R("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!n(this,Gn,Wc))throw new R("Can`t disable all video without joining room","1205");if(n(this,Pi).permissions.canAllowParticipantVideo)return n(this,Lo,vu).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new R("Unauthorized: User does not have permission to disable peer video.","1201")}async disableAudio(t){this.joined.get(t).disableAudio()}async disableVideo(t){this.joined.get(t).disableVideo()}async kick(t){await n(this,Se).getValue("peerSessionStore").emitAsync(C.KICK_PEER,{peerId:t})}async kickAll(){if(this.logger.info("Participants::kick_all"),n(this,Se).getValue("viewType")!=="LIVESTREAM"&&!n(this,Ei,za))throw new R("Can`t kick all without joining room","1205");if(!n(this,Pi).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new R("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;n(this,mt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!n(this,Ei,za))throw new R("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new R("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await n(this,mt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(a=>{var o;return(o=r.presetNames)==null?void 0:o.includes(a.presetName)}).map(a=>a.id),await n(this,mt).broadcastToPeers(t,i,e)}else await n(this,mt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await n(this,mt).getRoomPeers(t,e,r)).peers.map(pr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(a=>t.includes(a.id)).map(a=>a.userId),i=[...new Set(r)];if(!i.length)throw new R("Cannot update permissions, no valid userIDs found","1204");n(this,mt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return n(this,mt).getRoomPeersNonPaginated()}},Se=new WeakMap,Lo=new WeakSet,vu=function(){return n(this,Se).getValue("roomNodeClient")},Ei=new WeakSet,za=function(){var t;return((t=n(this,Se).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Gn=new WeakSet,Wc=function(){var t;return((t=n(this,Se).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Pi=new WeakMap,mt=new WeakMap,cg);xt([y.trace("Participants.setViewMode")],pt.prototype,"setViewMode",1);xt([y.trace("Participants.setPage")],pt.prototype,"setPage",1);xt([y.trace("Participants.disableAllAudio")],pt.prototype,"disableAllAudio",1);xt([y.trace("Participants.disableAllVideo")],pt.prototype,"disableAllVideo",1);xt([y.trace("Participants.disablePeerAudio")],pt.prototype,"disableAudio",1);xt([y.trace("Participants.disablePeerVideo")],pt.prototype,"disableVideo",1);xt([y.trace("Participants.kickPeer")],pt.prototype,"kick",1);xt([y.trace("Participants.kickAll")],pt.prototype,"kickAll",1);xt([y.trace("Participants.broadcastMessage"),Et(ba,"rateLimitConfig")],pt.prototype,"broadcastMessage",1);xt([y.trace("Participants.getAllJoinedPeers"),Et({maxInvocations:10,period:60})],pt.prototype,"getAllJoinedPeers",1);xt([y.trace("Participant.updatePermissions"),Et({maxInvocations:1e3,period:60})],pt.prototype,"updatePermissions",1);xt([y.trace("Participants.getParticipantsInMeetingPreJoin")],pt.prototype,"getParticipantsInMeetingPreJoin",1);pt=xt([rt("1200")],pt);var U0=Object.defineProperty,$0=Object.getOwnPropertyDescriptor,Xi=(s,t,e,r)=>{for(var i=r>1?void 0:r?$0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&U0(t,e,i),i},Wt,os,Wn,dg;const vf=(dg=class{constructor(s,t,e){h(this,"participants");h(this,"self");h(this,"selectedPeers",Sf);h(this,"maxSpatialLayerUpdates",new Map);h(this,"consumerPeerMap");h(this,"events");h(this,"roomSocketHandler");h(this,"context");h(this,"videoPeerConsumerMap",new Map);g(this,Wt,{mode:"ACTIVE_GRID",page:0});g(this,os,!1);g(this,Wn,!1);h(this,"updateConsumerSpatialLayers",th(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];this.logger.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));h(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, ConsumersSyncing: ${n(this,os)}`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${s.length} producers: [${s.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(e){this.logger.error("updateConsumers: Error creating consumers",{error:e})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${t.length} producers: [${t.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.closeConsumers(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(e){this.logger.error("updateConsumers: Error closing consumers",{error:e})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new pt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=gs,t.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}setupEvents(){this.roomSocketHandler.on(V.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(C.SOCKET_PEERS,async s=>{s==null||s.forEach(t=>{t.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(t))})}),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:s})=>{this.logger.info("PEER_INFO:::MEDIA_JOIN",{participant:{id:s.peerId,maskedName:[...(s==null?void 0:s.displayName)||""].map((t,e)=>e%2?"*":t).join("")}}),this.onParticipantMediaJoined(s.peerId,s.producerStates)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:s,selectedPeers:t,roomState:e})=>{s.forEach(({peerId:a,producerStates:o})=>this.onParticipantMediaJoined(a,o));const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};e.pinnedPeerIds.length!==0&&this.onParticipantPinned(e.pinnedPeerIds[0]),this.computeActivateParticipants(r!=null?r:[],i),this.logger.info("selfJoinComplete: Emitting UPDATE_ACTIVE with createAllConsumers=true"),this.context.getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(C.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers())}),this.context.getValue("peerSessionStore").on(C.NEW_PRODUCER,({peerId:s,producer:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:t==null?void 0:t.producerId,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}},participant:{id:s}});return}e.producers.push(t),this.logger.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}}}),(t==null?void 0:t.kind)==="audio"&&this.participants.audioSubscribed.get(s)||(t==null?void 0:t.kind)==="video"&&this.participants.videoSubscribed.get(s)||t!=null&&t.screenShare?(this.logger.info(`NEW_PRODUCER: scheduling syncConsumer (AUTO mode) - Producer: ${t.producerId}, Peer: ${s}, Kind: ${t.kind}, ScreenShare: ${t.screenShare}, ConsumersSyncing: ${n(this,os)}, VideoSub: ${t.kind==="video"?this.participants.videoSubscribed.has(s):"N/A"}, AudioSub: ${t.kind==="audio"?this.participants.audioSubscribed.has(s):"N/A"}`),this.scheduleSyncConsumers({source:"NEW_PRODUCER_AUTO"})):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer_auto",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"UNKNOWN",appData:{screenShare:t==null?void 0:t.screenShare}}})}),this.context.getValue("peerSessionStore").on(C.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{participant:{id:s}});return}e.producers=e.producers.filter(r=>r.producerId!==t)}),this.context.getValue("peerSessionStore").on(C.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){r==="audio"&&i.setAudioEnabled(!e);const a=i.producers.find(o=>o.producerId===t);a&&(a.pause=e),r==="video"&&this.context.getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,s=>{let t;if(s&&(t=s.participantId),!this.mediaJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);r&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${e} - ProducerCount: ${r.producers.length}, ConsumersSyncing: ${n(this,os)}, ProducerIds: [${r.producers.map(i=>i.producerId).join(", ")}]`),this.scheduleSyncConsumers({source:"GLOBAL_PEER_PIN"}))}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:s,compulsoryPeers:t})=>{this.mediaJoined&&this.onSelectedPeers(t.concat(s))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:s})=>{if(!this.mediaJoined)return;const t=s.map(e=>({peerId:e.peerId,priority:e.priority}));this.updateActiveParticipantsWithPriorities(t,!0)})}waitingRoomRequestHandler(s){const t=s.requests.filter(r=>!this.participants.waitlisted.toArray().find(i=>i.userId===r.userId)),e=this.participants.waitlisted.toArray().filter(r=>!s.requests.find(i=>i.userId===r.userId));t.forEach(r=>this.participants.waitlisted.add(new cr(this.context,{id:r.peerId,displayName:r.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:r.userId,flags:{},isHost:!1,customParticipantId:r.customParticipantId,picture:r.picture,metadata:{preset_name:r.presetName}},this.self,this.roomSocketHandler))),e.forEach(r=>this.participants.waitlisted.delete(r.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(s){const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(d=>this.participants.joined.has(d)),r=Array.from(this.participants.pinned.keys()).filter(d=>!e.includes(d)),i=Array.from(this.participants.joined.toArray().filter(d=>d.stageStatus==="ON_STAGE").map(d=>d.id)),a=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(a,o))}selectActivePeers(s){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(u=>u.stageStatus==="ON_STAGE").map(u=>(t.set(u.id,!0),u.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((u,p)=>(p.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(p.id):u.push(p.id),u),[]),a=this.self.stageStatus==="ON_STAGE"?1:0,o=s-a,c=new Set(r.concat(i).filter(u=>u!==this.self.id&&t.has(u)));let d=Array.from(c);const l=o-c.size;if(l>=0){const u=e.filter(p=>!c.has(p)&&p!==this.self.id).slice(0,l);d=Array.from(c).concat(u)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&n(this,Wt).mode!==s&&(n(this,Wt).mode=s),e&&n(this,Wt).page!==e&&(n(this,Wt).page=e);const{mode:r,page:i}=n(this,Wt);switch(r){case"PAGINATED":{if(!i)return;const a=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,a),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:a});break}case"ACTIVE_GRID":{const a=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,a),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":break;default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=n(this,Wt))==null?void 0:e.mode)==="PAGINATED"&&!n(this,os)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=n(this,Wt))==null?void 0:r.mode}, ConsumersSyncing: ${n(this,os)}, Delay: ${t}, Page: ${(i=n(this,Wt))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var o,c,d,l,u;if(((d=(c=(o=this.context.getValue("connectionHandler"))==null?void 0:o.mediaState)==null?void 0:c.recv)==null?void 0:d.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(n(this,os)){m(this,Wn,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),m(this,os,!0),m(this,Wn,!1);let s=[];this.participants.videoSubscribed.forEach(p=>{var E,b;const f=this.participants.joined.get(p.id),T=(b=(E=p.producers)==null?void 0:E.filter(_=>_.kind==="video"))!=null?b:[];f&&(T!=null&&T.length)&&T.forEach(_=>{var x,N,$,K;const M=((N=(x=f.manualProducerConfig)==null?void 0:x.video)!=null?N:!0)&&_.kind==="video"&&!_.screenShare,A=((K=($=f.manualProducerConfig)==null?void 0:$.screenshareVideo)!=null?K:!0)&&_.kind==="video"&&_.screenShare;(M||A)&&(_.pause||s.push(_))})}),this.participants.audioSubscribed.forEach(p=>{var E,b;const f=this.participants.joined.get(p.id),T=(b=(E=p.producers)==null?void 0:E.filter(_=>_.kind==="audio"))!=null?b:[];f&&(T!=null&&T.length)&&T.forEach(_=>{var x,N,$,K;const M=((N=(x=f.manualProducerConfig)==null?void 0:x.audio)!=null?N:!0)&&_.kind==="audio"&&!_.screenShare,A=((K=($=f.manualProducerConfig)==null?void 0:$.screenshareAudio)!=null?K:!0)&&_.kind==="audio"&&_.screenShare;(M||A)&&s.push(_)})}),s=o_(s,p=>p.producerId);const t=new Map;s.forEach(p=>{t.set(p.producerId,p)});const e=(l=this.roomNodeClient)==null?void 0:l.getConsumers(),r=s.filter(p=>!(e!=null&&e.has(p.producerId))),i=[];let a=Array.from((u=e==null?void 0:e.values())!=null?u:[]).map(p=>p.peerId);a=a_(a),a==null||a.forEach(p=>{var T;const f=this.participants.joined.get(p);if(!f){this.logger.warn(`Peer with ${p} doesn't exist in joined list but producers of it are being consumed.`);return}(T=f.producers)!=null&&T.length&&f.producers.forEach(E=>{const b=E.consumer&&e.has(E.consumer.id);!t.has(E.producerId)&&(e.has(E.producerId)||b)&&i.push(E)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(p=>p.producerId).join(", ")}], RemoveProducers: ${i.length} [${i.map(p=>p.producerId).join(", ")}]`.substring(0,5e3));try{r.length>0||i.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${i.length}.`),await this.updateConsumers(r,i),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(p){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:p})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),m(this,os,!1)}n(this,Wn)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,a)=>({peerId:i,priority:a+1})),r=t==null?void 0:t.map((i,a)=>({peerId:i,priority:-(a+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=vf.formatSocketPeerMessage(s);return new cr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onParticipantMediaJoined(s,t){if(!this.mediaJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{participant:{id:e.id,maskedName:[...(e==null?void 0:e.name)||""].map((r,i)=>i%2?"*":r).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(r=>{r.kind===ir.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===ir.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===ir.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType})}),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),i=new Set(t),a=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&a.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=a.shift();e[c]=o}),a.forEach(o=>{e.splice(o,1)}),Array.from(s.keys()).forEach(o=>{s.delete(o,!i.has(o))}),e.forEach(o=>{if(!this.participants.joined.get(o)){this.logger.warn("updateActiveParticipants::participant_not_in_joined_list",{participant:{id:o}});return}s.add(this.participants.joined.get(o),!r.get(o))}),s.emit("participantsUpdate")}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{s.get(r)||s.add(this.participants.joined.get(r),!0)}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}setupEventsGlobal(){this.roomSocketHandler.on(V.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info("Processing socket join",{peers:s.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info("Processed socket join",{peers:s.peerId}))}),this.roomSocketHandler.on(V.leaveRoom,s=>{const{peerId:t}=s.peer;this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(C.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),this.context.getValue("peerSessionStore").on(C.SOCKET_SERVICE_DISCONNECTED,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),this.context.getValue("peerSessionStore").on(C.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(C.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(C.NEW_CONSUMER,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(C.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(C.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(C.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(C.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),this.context.getValue("peerSessionStore").on(C.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const a=t==="video"&&((c=e==null?void 0:e.screenShare)!=null?c:!1),o=this.participants.joined.get(r);o&&(o.emit("mediaScoreUpdate",{kind:t,isScreenshare:a,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:a,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(C.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),this.context.getValue("peerSessionStore").on(C.UPDATE_ACTIVE,async({viewMode:s,page:t,createAllConsumers:e}={viewMode:"ACTIVE_GRID",page:0,createAllConsumers:!1})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${n(this,Wt).mode}, page: ${t}, CreateAllConsumers: ${e}`),e&&(this.logger.info(`UPDATE_ACTIVE viewMode: ${s}, Page: ${t}, Removing existing subscriptions.`),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear()),this.updateMediaSubscribedMaps(s,{page:t}),this.scheduleSyncConsumers({source:"UPDATE_ACTIVE"})})}async onParticipantPinned(s){if(!s){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(s===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const t=this.participants.joined.get(s);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),t.setIsPinned(!0),this.participants.pinned.add(t)}async onParticipantSocketJoined(s){var t,e,r;this.logger.info(`onParticipantSocketJoined: peer ${s.id} has joined socket edge. Processing.`),this.self.id!==s.id&&!((t=s.flags)!=null&&t.recorder)&&!((e=s.flags)!=null&&e.hidden_participant)&&!((r=s.flags)!=null&&r.hiddenParticipant)&&(this.participants.videoSubscribed.delete(s.id),this.participants.audioSubscribed.delete(s.id),this.participants.joined.add(s),this.participants.waitlisted.delete(s.id),s.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(C.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(C.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),this.roomNodeClient&&this.roomNodeClient.closeConsumers(t==null?void 0:t.producers),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(C.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1});const{currentPage:e}=this.participants,r=this.maxPreferredStreams*(e-1),i=this.participants.videoSubscribed.get(s);this.participants.viewMode==="MANUAL"?this.context.getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e}):r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?e===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(e-1):i&&this.context.getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e})}processMedia(s){var p;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:i,track:a,producerId:o,rtpReceiver:c,paused:d,localId:l}=(p=t.get(s))!=null?p:{};if(!e)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:s,kind:r,peerId:e,appData:{supportsRemoteControl:!!(i!=null&&i.supportsRemoteControl),screenShare:!!(i!=null&&i.screenShare)},remotelyPaused:d,producerId:o}}),{};const u=i;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:d,producerId:o}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:a,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:a}=this.consumerPeerMap.get(s)||{},o=this.participants.joined.get(t);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:i,producerId:a}}),this.consumerPeerMap.delete(s),e==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!o)return;const c=o.producers.find(l=>l.producerId===a);c&&(c.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:a,rtpReceiver:void 0,localId:void 0});const d=[];r&&r.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}),o.screenShareTracks.video&&d.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&d.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):e==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&d.push(o.audioTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}),o.audioTrack=void 0):e==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&d.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1}),o.videoTrack=void 0),r.e2ee&&d.forEach(l=>{this.context.getValue("peerSessionStore").emit(C.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:l})})}processConsumerResumed(s){var f;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:a,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const p=u.producers.find(T=>T.producerId===c);if(p&&(p.consumer={id:s,peerId:e,kind:r,appData:i,paused:o,producerId:c,rtpReceiver:d,localId:l}),i.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:a}),i.screenShare){r==="video"?u.screenShareTracks.video=a:r==="audio"&&(u.screenShareTracks.audio=a),u.setScreenShareEnabled(!0),(f=this.context)==null||f.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=a,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=a,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:a,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:a,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(p=>p.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:a,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:a,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:a,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(p=>p.producerId===o);if(u&&(u.consumer={id:s,peerId:t,kind:e,appData:a,paused:r,producerId:o,rtpReceiver:c,localId:d}),a.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),a.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:a,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&a.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i})}static formatSocketPeerMessage(s){var e,r,i,a,o,c;if(!s)return;const t=ah(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=s.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(a=s.flags)==null?void 0:a.hiddenParticipant,recorder:((o=s.flags)==null?void 0:o.recorderType)!==void 0&&((c=s.flags)==null?void 0:c.recorderType)!=="NONE"}}}async onSelectedPeers(s,t){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(s,t)}updateActiveParticipantsWithPriorities(s,t=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority,this.context)});const e=this.selectedPeers.activeSpeakerPeers.at(0);e!==void 0&&e!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=e,this.participants.emit("activeSpeaker",{peerId:e,volume:1})),t&&this.context.getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},Wt=new WeakMap,os=new WeakMap,Wn=new WeakMap,dg);let pr=vf;Xi([y.trace("ParticipantController.setupEvents")],pr.prototype,"setupEvents",1);Xi([y.trace("ParticipantController.setupEvents")],pr.prototype,"setupEventsGlobal",1);Xi([y.trace("ParticipantController.processMedia")],pr.prototype,"processMedia",1);Xi([y.trace("ParticipantController.processConsumerClosed")],pr.prototype,"processConsumerClosed",1);Xi([y.trace("ParticipantController.processConsumerResumed")],pr.prototype,"processConsumerResumed",1);Xi([y.trace("ParticipantController.processConsumerPaused")],pr.prototype,"processConsumerPaused",1);Xi([y.trace("ParticipantController.processNewConsumer")],pr.prototype,"processNewConsumer",1);const le=ks(sh().permissions);var B,Jn,Kn,wd,ot,bt;const dn=class extends Lt{constructor(e,r,i,a=!1){const o=e.getValue("logger");super(o);g(this,ot);g(this,B,void 0);g(this,Jn,void 0);g(this,Kn,void 0);g(this,wd,e=>{var l,u,p;const{chat:r,connectedMeetings:i,plugins:a,polls:o,media:c,...d}=e;if(r&&(r.private&&mr(n(this,B).chat.private,r.private),r.public&&mr(n(this,B).chat.public,r.public),this.emit("chatUpdate")),i&&mr(n(this,B).connectedMeetings,i),c){const f=E=>{switch(E){case $r.NONE:return H.Allowed;case $r.ALLOWED:return H.Allowed;case $r.NOT_ALLOWED:return H.NotAllowed;case $r.CAN_REQUEST:return H.CanRequest;default:return}},T={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(T.audio={canProduce:f(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(T.video={canProduce:f(c.video.canProduce)}),(p=c.screenshare)!=null&&p.canProduce&&(T.screenshare={canProduce:f(c.screenshare.canProduce)}),mr(n(this,B).media,T)}a&&(mr(n(this,B).plugins,a),this.emit("pluginsUpdate")),o&&(mr(n(this,B).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&mr(n(this,B),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new R("Could not load preset permissions.","0904");m(this,Kn,e),m(this,Jn,i),m(this,B,r),a&&this.setupEvents()}setupEvents(){n(this,Kn).getValue("peerSessionStore").on(C.UPDATE_PERMISSIONS,n(this,wd))}static fromResponse(e,r,i){return new dn(i,e,r,!0)}static default(e,r){return new dn(e,le,r)}static init(e,r,i){let a;return i?a=new dn(e,i,r,!0):a=new dn(e,le,r),a}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=n(this,B))==null?void 0:e.stageEnabled)||n(this,Jn)===rr.Webinar||n(this,Jn)===rr.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=n(this,B))==null?void 0:e.acceptStageRequests)||((r=n(this,B))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=n(this,B))==null?void 0:e.stageAccess)===H.NotAllowed?H.NotAllowed:((r=n(this,B))==null?void 0:r.stageAccess)===H.CanRequest?H.CanRequest:((i=n(this,B))==null?void 0:i.stageAccess)===H.Allowed||n(this,B).media.audio.canProduce===H.Allowed||n(this,B).media.video.canProduce===H.Allowed||n(this,B).media.screenshare.canProduce===H.Allowed?H.Allowed:n(this,B).media.audio.canProduce===H.CanRequest||n(this,B).media.video.canProduce===H.CanRequest||n(this,B).media.screenshare.canProduce===H.CanRequest?H.CanRequest:H.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=n(this,B))==null?void 0:e.acceptWaitingRequests)!=null?r:le.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=n(this,B))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=n(this,B))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=n(this,B))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===H.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=n(this,B))==null?void 0:e.disableParticipantAudio)!=null?r:le.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canAcceptProductionRequests)!=null?r:le.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=n(this,B))==null?void 0:e.disableParticipantVideo)!=null?r:le.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=n(this,B))==null?void 0:e.kickParticipant)!=null?r:le.kickParticipant}get pinParticipant(){var e,r;return(r=(e=n(this,B))==null?void 0:e.pinParticipant)!=null?r:le.pinParticipant}get canRecord(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canRecord)!=null?r:le.canRecord}get waitingRoomType(){var e,r;return(r=(e=n(this,B))==null?void 0:e.waitingRoomType)!=null?r:le.waitingRoomType}get waitingRoomBehaviour(){var e,r;return(r=(e=n(this,B))==null?void 0:e.waitingRoomType)!=null?r:le.waitingRoomType}get plugins(){var e,r;return(r=(e=n(this,B))==null?void 0:e.plugins)!=null?r:le.plugins}get polls(){var e,r;return(r=(e=n(this,B))==null?void 0:e.polls)!=null?r:le.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return n(this,B).media.audio.canProduce===H.CanRequest||n(this,B).media.video.canProduce===H.CanRequest||n(this,B).media.screenshare.canProduce===H.CanRequest}get canProduceVideo(){var r;const e=(r=n(this,B).media.video.canProduce)!=null?r:le.media.video.canProduce;return this.stageEnabled&&(n(this,ot,bt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,ot,bt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(n(this,ot,bt)==="OFF_STAGE"||n(this,ot,bt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var r;const e=(r=n(this,B).media.screenshare.canProduce)!=null?r:le.media.screenshare.canProduce;return this.stageEnabled&&(n(this,ot,bt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,ot,bt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(n(this,ot,bt)==="OFF_STAGE"||n(this,ot,bt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var r;const e=(r=n(this,B).media.audio.canProduce)!=null?r:le.media.audio.canProduce;return this.stageEnabled&&(n(this,ot,bt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,ot,bt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(n(this,ot,bt)==="OFF_STAGE"||n(this,ot,bt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=n(this,B))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:le.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=n(this,B))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:le.chat.private}get connectedMeetings(){var e,r;return(r=(e=n(this,B))==null?void 0:e.connectedMeetings)!=null?r:le==null?void 0:le.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=n(this,B))==null?void 0:e.hiddenParticipant)!=null?r:le.hiddenParticipant}get showParticipantList(){var e;return(e=n(this,B).showParticipantList)!=null?e:le.showParticipantList}get canChangeParticipantRole(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canChangeParticipantPermissions)!=null?r:le.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canChangeParticipantPermissions)!=null?r:le.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return n(this,B).media.audio.canProduce===H.Allowed||n(this,B).media.video.canProduce===H.Allowed||n(this,B).media.screenshare.canProduce===H.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var e;return(e=n(this,B).canEditDisplayName)!=null?e:!1}get maxScreenShareCount(){return 1}get isRecorder(){return n(this,B).isRecorder}get canSpotlight(){return n(this,B).canSpotlight}get canLivestream(){return n(this,B).canLivestream}get transcriptionEnabled(){return n(this,B).transcriptionEnabled}};let yu=dn;B=new WeakMap,Jn=new WeakMap,Kn=new WeakMap,wd=new WeakMap,ot=new WeakSet,bt=function(){return n(this,Kn).getValue("stageStatus")};var Mt;class yf extends Lt{constructor(e,r){super(r);h(this,"localMediaHandler");g(this,Mt,void 0);m(this,Mt,e)}async updatePermission(){var d,l;const e=(u,p)=>{this.mediaPermissions[u]=p;const f={message:this.mediaPermissions[u],kind:u};p==="DENIED"?n(this,Mt).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_ERROR,f):n(this,Mt).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,f)};if(ge.getName()==="firefox")return;const r="microphone",i="camera",a=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(u,p)=>{switch(p){case"granted":e(u,"ACCEPTED");break;case"denied":e(u,"DENIED");break;case"prompt":e(u,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};a&&(a.onchange=()=>c("audio",a.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,a,o,c;switch(r){case"audio":{(i=n(this,Mt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(a=n(this,Mt))==null||a.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=n(this,Mt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=n(this,Mt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=n(this,Mt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var a,o,c,d,l,u,p;if(ge.init(),i&&m(this,Mt,i),!this.localMediaHandler)try{let f=!0;if((a=i==null?void 0:i.getValue("defaults"))!=null&&a.mediaHandler)f=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:T}=navigator;this.localMediaHandler=await T.init(e)}else this.localMediaHandler=new Pt(i,e.constraints,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.isNonPreferredDevice,(c=i==null?void 0:i.getValue("defaults"))==null?void 0:c.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(C.MEDIA_PERMISSION_UPDATE,async T=>{if(this.populateMediaPermissionsInCallstats({message:T.message,kind:T.kind}),T.message==="NOT_REQUESTED")switch(T==null?void 0:T.kind){case"audio":this.rawAudioTrack&&(this.logger.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(this.logger.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",T)}),i==null||i.getValue("peerSessionStore").on(C.MEDIA_PERMISSION_ERROR,async T=>{const{kind:E,message:b,constraints:_}=T;this.populateMediaPermissionsInCallstats({message:b,kind:E}),E==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):E==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:b},constraints:_,mediaPermissionsErrors:{kind:E,message:b}}),this.emit("mediaPermissionError",T),this.emit("mediaPermissionUpdate",{message:b,kind:E})}),f){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const T=this.localMediaHandler.setupStreams({video:(u=e==null?void 0:e.video)!=null?u:!0,audio:(p=e==null?void 0:e.audio)!=null?p:!0});r||await T}}catch(f){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:f.name,message:f.message}})}}set context(e){m(this,Mt,e),this.localMediaHandler.context=e}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}async addAudioMiddleware(e){return this.localMediaHandler.addAudioMiddleware(e)}async removeAudioMiddleware(e){return this.localMediaHandler.removeAudioMiddleware(e)}async removeAllAudioMiddlewares(){return this.localMediaHandler.removeAllAudioMiddlewares()}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}async addVideoMiddleware(e){return this.localMediaHandler.addVideoMiddleware(e)}async setVideoMiddlewareGlobalConfig(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)}async removeVideoMiddleware(e){return this.localMediaHandler.removeVideoMiddleware(e)}async removeAllVideoMiddlewares(){return this.localMediaHandler.removeAllVideoMiddlewares()}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}async enableAudio(){await this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){await this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){await this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}async getAudioDevices(){return await this.localMediaHandler.getAudioDevices()}async getVideoDevices(){return await this.localMediaHandler.getVideoDevices()}async getSpeakerDevices(){return await this.localMediaHandler.getSpeakerDevices()}getDeviceById(e,r){let i;return r==="audio"?i="audioinput":r==="video"?i="videoinput":r==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}async setDevice(e){switch(e.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(e,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}Mt=new WeakMap;var B0=Object.defineProperty,H0=Object.getOwnPropertyDescriptor,gt=(s,t,e,r)=>{for(var i=r>1?void 0:r?H0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&B0(t,e,i),i},zn,ct,Yn,Fe,js,Qr,qe,ze,Qn,Jc,Ie,Ne,Xn,Zn,Vo,Eu,lg;let Je=(lg=class extends yf{constructor(t,e,r,i,a){var c;const o=t.getValue("logger");super(t,o);g(this,js);g(this,qe);g(this,Qn);g(this,Ie);g(this,Vo);h(this,"name");h(this,"picture");h(this,"customParticipantId");h(this,"waitlistStatus");g(this,zn,void 0);g(this,ct,void 0);g(this,Yn,void 0);h(this,"role");h(this,"userId");h(this,"organizationId");h(this,"supportsRemoteControl",!1);h(this,"device");g(this,Fe,void 0);h(this,"hidden",!1);h(this,"presetName");h(this,"roomState","init");g(this,Xn,new Set);g(this,Zn,new Set);m(this,Fe,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(c=e.customParticipantId)!=null?c:e.clientSpecificId,this.waitlistStatus="none",m(this,ct,r),m(this,zn,i),this.hidden=!1,m(this,Yn,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ge.isElectron(),this.device=ge.getDeviceInfo(),this.presetName=a,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),L(this,Vo,Eu).call(this)}get telemetry(){return n(this,Fe).getValue("telemetry")}get stageStatus(){return n(this,Fe).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=n(this,qe,ze).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return n(this,Fe).getValue("peerId")}static async __init__(t,e,r,i,a,o=!1){var f,T,E,b,_,M;let c=(T=(f=t.getValue("defaults"))==null?void 0:f.audio)!=null?T:!0,d=(b=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?b:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new Je(t,e,r,i,a),u=QA(i.mediaConstraints);mr(u,(_=t.getValue("defaults"))==null?void 0:_.mediaConfiguration);const p=(M=t.getValue("defaults"))==null?void 0:M.mediaHandler;return p&&(p.context=t),await l.init({audio:c,video:d,constraints:u},o,t),l.setupEvents(),l}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),n(this,ct).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",L(this,Vo,Eu));const t=n(this,Qn,Jc);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...ti(this)}),n(this,Ie,Ne)&&this.audioEnabled)try{await n(this,qe,ze).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::VIDEO_TRACK_CHANGE",{...ti(this)}),n(this,Ie,Ne)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&n(this,Ie,Ne))try{await n(this,qe,ze).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}),this.localMediaHandler.on("DEVICE_CHANGE",async({device:e})=>{var r;this.emit("deviceUpdate",{device:e}),e.kind==="audiooutput"&&typeof HTMLAudioElement.prototype.setSinkId=="function"&&((r=n(this,Qn,Jc))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!n(this,Ie,Ne)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await n(this,qe,ze).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::setupEvents::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...ti(this)}),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}),this.localMediaHandler.on("SCREENSHARE_ENDED",async()=>{this.logger.log("Disabling screenshare due to SCREENSHARE_ENDED"),await this.disableScreenShare(),this.logger.info("Self::setupEvents::SCREENSHARE_ENDED",{...ti(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=n(this,Fe))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;n(this,Ie,Ne)&&await n(this,qe,ze).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=n(this,Fe))==null||e.getValue("callstats").videoOff()}),n(this,ct).on("permissionsUpdate",e=>{var r,i,a;(r=e==null?void 0:e.media)!=null&&r.audio&&n(this,ct).canProduceAudio!==H.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&n(this,ct).canProduceVideo!==H.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(a=e==null?void 0:e.media)!=null&&a.screenshare&&n(this,ct).canProduceScreenshare!==H.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return n(this,ct)}get config(){return n(this,zn)}get roomJoined(){var t;return n(this,zn).viewType===rr.Livestream&&this.stageStatus!=="ON_STAGE"?((t=n(this,Fe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:n(this,Ie,Ne)}setName(t){if(!t)throw new R("Name cannot be empty.","1103");this.name=t}async setupTracks(t={}){t.forceReset,await this.disableAudio(),await this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&await this.enableAudio(),t.video&&await this.enableVideo()}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(t){var e;if(this.permissions.canProduceAudio!==H.NotAllowed&&!(n(this,ct).canProduceAudio===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=n(this,Fe))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),n(this,Ie,Ne)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await n(this,qe,ze).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(n(this,ct).canProduceVideo!==H.NotAllowed&&!(n(this,ct).canProduceVideo===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=n(this,Fe))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),n(this,Ie,Ne)&&this.stageStatus==="ON_STAGE")try{await n(this,qe,ze).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...ti(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new R("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!n(this,Ie,Ne))throw new R("Can`t enable screenshare without joining room","1105");if(n(this,ct).canProduceScreenshare!==H.NotAllowed&&!(n(this,ct).canProduceScreenshare===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await n(this,qe,ze).shareScreen(this.screenShareTracks)}catch(t){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new R("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),n(this,Ie,Ne)&&n(this,qe,ze).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=n(this,Fe))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),n(this,Ie,Ne)&&await n(this,qe,ze).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=n(this,Fe))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),n(this,Ie,Ne)&&await n(this,qe,ze).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;m(this,Yn,t);const r=t?"pinned":"unpinned";(i=n(this,js,Qr))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return n(this,Yn)}async pin(){if(!n(this,Ie,Ne))throw new R("Can`t pin participants without joining room","1105");return this.show(),n(this,qe,ze).pinPeer(this.id)}async unpin(){if(!n(this,Ie,Ne))throw new R("Can`t unpin participants without joining room","1105");return n(this,qe,ze).pinPeer(null)}async hide(){if(!n(this,Ie,Ne))throw new R("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!n(this,Ie,Ne))throw new R("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,a;if(!t)throw new R("No device selected","1104");const e=this.getCurrentDevices();switch(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((i=e==null?void 0:e.video)==null?void 0:i.deviceId)===t.deviceId||((a=e==null?void 0:e.speaker)==null?void 0:a.deviceId)===t.deviceId)&&this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){n(this,Ie,Ne)&&await n(this,qe,ze).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(t,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(t,{saveDevicePreference:!0})}catch(o){n(this,Ie,Ne)&&await n(this,qe,ze).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}}cleanUpTracks(){var t,e,r,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(i=this.rawVideoTrack)==null||i.stop()}playAudio(){var t;return(t=n(this,Qn,Jc))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?n(this,Xn).add(t):n(this,Zn).add(t),this.updateVideo(t),e||(i=n(this,js,Qr))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){n(this,js,Qr).removeSource(this.id);return}t.srcObject=void 0,e?n(this,Xn).delete(t):(n(this,Zn).delete(t),n(this,js,Qr).removeSource(this.id))}updateVideo(t,e=!1){var r,i,a;if(this.videoEnabled){if(this.videoTrack==null)return;const o=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((o==null?void 0:o.id)===this.videoTrack.id)return;const c=new MediaStream;c.addTrack(this.videoTrack),t.srcObject=c,e||(i=n(this,js,Qr))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(a=n(this,js,Qr))==null||a.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},zn=new WeakMap,ct=new WeakMap,Yn=new WeakMap,Fe=new WeakMap,js=new WeakSet,Qr=function(){return n(this,Fe).getValue("pip")},qe=new WeakSet,ze=function(){return n(this,Fe).getValue("roomNodeClient")},Qn=new WeakSet,Jc=function(){return n(this,Fe).getValue("audioPlayback")},Ie=new WeakSet,Ne=function(){var t;return((t=n(this,Fe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Xn=new WeakMap,Zn=new WeakMap,Vo=new WeakSet,Eu=function(){Array.from(n(this,Zn)).forEach(t=>this.updateVideo(t,!1)),Array.from(n(this,Xn)).forEach(t=>this.updateVideo(t,!0))},lg);gt([y.trace("Self.cleanupEvents")],Je.prototype,"cleanupEvents",1);gt([y.trace("Self.setupEvents")],Je.prototype,"setupEvents",1);gt([y.trace("Self.setupTracks")],Je.prototype,"setupTracks",1);gt([y.trace("Self.destructMediaHandler")],Je.prototype,"destructMediaHandler",1);gt([y.trace("Self.removeDocumentEventListeners")],Je.prototype,"removeDocumentEventListeners",1);gt([hr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.enableAudio")],Je.prototype,"enableAudio",1);gt([hr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.enableVideo")],Je.prototype,"enableVideo",1);gt([y.trace("Self.updateVideoConstraints")],Je.prototype,"updateVideoConstraints",1);gt([y.trace("Self.enableScreenShare"),hr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],Je.prototype,"enableScreenShare",1);gt([y.trace("Self.updateScreenshareConstraints")],Je.prototype,"updateScreenshareConstraints",1);gt([hr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.disableAudio")],Je.prototype,"disableAudio",1);gt([hr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.disableVideo")],Je.prototype,"disableVideo",1);gt([hr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),y.trace("Self.disableScreenShare")],Je.prototype,"disableScreenShare",1);gt([y.trace("Self.setDevice")],Je.prototype,"setDevice",1);Je=gt([rt("1100")],Je);class hh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,hh)}}class ph extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,ph)}}var xo;class Pu{constructor(t,e=!1){h(this,"pendingTasks",new Map);h(this,"nextTaskId",0);h(this,"stopping",!1);g(this,xo,void 0);this.log=e,m(this,xo,{info:e&&t?t.info:()=>{}})}get size(){return this.pendingTasks.size}async push(t,e,r){if(e=e!=null?e:t.name,typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(i){}return new Promise((i,a)=>{const o={id:this.nextTaskId++,task:t,metadata:r,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),i(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),a(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){this.stopping=!0;for(const t of this.pendingTasks.values())t.reject(new hh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new ph)}get(t){return Array.from(this.pendingTasks.values())[t]}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=this.pendingTasks.size,r=await t.task(),i=Date.now();n(this,xo).info(`AwaitQueue.push(${t.name})_timings`,{awaitQueueTask:{id:t.id,metadata:t.metadata,queueSizeAtStart:e,execTime:(i-t.executedAt)/1e3,taskStartTime:(t.executedAt-t.enqueuedAt)/1e3}}),t.resolve(r)}catch(e){t.reject(e)}}}xo=new WeakMap;function F0(s,t){const e=new Error(t);return e.name=s,e}class go extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,go):this.stack=new Error(t).stack}}class yt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,yt):this.stack=new Error(t).stack}}class si extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,yt):this.stack=new Error(t).stack}}const $p=s=>new Promise(t=>setTimeout(t,s));async function Ef(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:a,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=p=>{l=!0,r(p)};for(;c<a;){try{const p=await s(c,u);return e(p)}catch(p){if(d=p,l)break;if(c<a)i==="linear"?await $p(o*(c+1)):i==="exponential"&&await $p(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function q0(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function j0(s){return s.map(t=>({uri:t.uri}))}function Vc(s){return{codecs:q0(s.codecs),headerExtensions:j0(s.headerExtensions?s.headerExtensions:[])}}function G0(s){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");s&&(e.codecs=e.codecs.filter(({mimeType:d})=>s===d),i.codecs=i.codecs.filter(({mimeType:d})=>s===d));const a={audio:Vc(t),video:Vc(e)};return{sender:{audio:Vc(r),video:Vc(i)},receiver:a}}var je;class W0{constructor(t){g(this,je,void 0);h(this,"events");m(this,je,t),this.events=gs}async joinRoom(t,e,r,i=!1){const a={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await n(this,je).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:mC.toBinary(a),timeout:5e3})).payload}async connectTransport(t){const e=(await n(this,je).sendMessagePromise(this.events.createWebRTCTransport,q_.toBinary(t))).payload,{transportId:r,description:i,producerIds:a}=Om.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:a}}async produce(t){var a,o;const e=(await n(this,je).sendMessagePromise(this.events.produce,IC.toBinary(t))).payload,r=hw.fromBinary(e);return{answer:{sdp:(a=r==null?void 0:r.description)==null?void 0:a.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await n(this,je).sendMessagePromise(this.events.consume,_C.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=lw.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await n(this,je).sendMessagePromise(this.events.closeProducer,xC.toBinary(t))).payload,{description:r}=vw.fromBinary(e);return r}async closeConsumer(t){return(await n(this,je).sendMessagePromise(this.events.closeConsumer,$C.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await n(this,je).sendMessagePromise(this.events.updateConsumersSimulcastConfig,kC.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await n(this,je).sendMessagePromise(this.events.hostControlPeer,GC.toBinary(r))).payload;if(!i)return!1;const{status:a}=ww.fromBinary(i);return a==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await n(this,je).sendMessagePromise(this.events.hostControlAllPeers,JC.toBinary(e))).payload;if(!r)return!1;const{status:i}=kw.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};n(this,je).sendMessagePromise(V.kickAll,xm.toBinary(t))}async kickPeer(t){n(this,je).sendMessagePromise(V.kick,Fm.toBinary(t))}async changeDisplayName(t){const e=(await n(this,je).sendMessagePromise(this.events.changeDisplayName,qC.toBinary(t))).payload;if(!e)return!1;const{status:r}=Iw.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await n(this,je).sendMessagePromise(this.events.selfJoinComplete,TC.toBinary(t))).payload;return su.fromBinary(e)}async audioActivity(t){n(this,je).sendMessage(this.events.audioActivity,G_.toBinary(t))}}je=new WeakMap;var mn=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(mn||{}),Uo;class Cl extends st.EventEmitter{constructor(e){super();g(this,Uo,void 0);m(this,Uo,e),this.setMaxListeners(1/0)}get logger(){return n(this,Uo).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(a){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:a}),Boolean(i)}}async safeEmitAsPromise(e,...r){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)}async safeEmitAsPromiseWithTimeout(e,r,...i){return new Promise((a,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,a,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}Uo=new WeakMap;class gh extends Cl{constructor(){super(...arguments);h(this,"_sendWebStream",new MediaStream);h(this,"_sendScreenShareStream",new MediaStream);h(this,"_direction");h(this,"pc");h(this,"_transportReady",!1);h(this,"_mapMidTransceiver",new Map);h(this,"enableHighBitrate",!1);h(this,"enableStereo",!1);h(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}async restartIce(){this.logger.debug(`${this.name}::restartIce()`);const e=await this.pc.createOffer({iceRestart:!0});return this.logger.debug(`[SDP] ${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`[SDP] ${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:a,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly",...this._direction==="send"?{sendEncodings:[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]}:{}});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`[SDP] connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`[SDP] ${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}async getTransportStats(){return this.pc.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}async stopSending(e){this._assertSendDirection(),this.logger.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this.pc.removeTrack(r.sender),r.direction="inactive";const i=await this.pc.createOffer();return this.logger.debug(`[SDP] stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`[SDP] stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(o)}]`),await this.pc.setRemoteDescription(o),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");await i.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters();a.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(a)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters();a.encodings.forEach((o,c)=>{a.encodings[c]={...o,...r}}),await i.sender.setParameters(a)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{this.logger.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{this.logger.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{this.logger.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{this.logger.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class mh extends gh{static createFactory(t){return()=>new mh(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},a),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(u=>{var f;const p=d.codecs.find(T=>T.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const T=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];T.push(...u.parameters);const E=Array.from(new Set(T).values());p.sdpFmtpLine=E.join(";")}l.push(p)}),this.logger.info(`selected codecs: ${JSON.stringify(l)}`),a.setCodecPreferences(l)}const o=await this.pc.createOffer();if(await this.pc.setLocalDescription(o),r&&r.findIndex(({name:d})=>d==="opus")>=0){const{enableDtx:d,enableStereo:l}=this,u=this.enableHighBitrate?l?128e3:64e3:l?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${d?"usedtx=1;":""}${l?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${u}`),o.sdp+=`a=rtcp-fb:111 nack\r
|
|
9
|
-
`}this.midTransceiverMap.set(a.mid,a);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),a.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:a.sender,mid:a.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}class cd extends gh{constructor(e,r){super(e);h(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new cd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:a}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[a?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const p=c.sender.getParameters();p.encodings=r,await c.sender.setParameters(p)}const d=(p,f)=>{var x;const T=rs.parse(p),E=T.media[T.media.length-1],b=E.rtp.filter(N=>f.some($=>$.name===N.codec)),_=E.fmtp.filter(N=>b.some($=>$.payload===N.payload)),M=(x=E.rtcpFb)==null?void 0:x.filter(N=>b.some($=>$.payload===N.payload)),A=b.map(N=>N.payload);return T.media[T.media.length-1].rtp=b,T.media[T.media.length-1].fmtp=_,T.media[T.media.length-1].rtcpFb=M,T.media[T.media.length-1].payloads=A.join(" "),rs.write(T)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:p,enableStereo:f}=this,T=this.enableHighBitrate?f?128e3:64e3:f?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${f?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${T}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async p=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(p)}]`),await this.pc.setRemoteDescription(p),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters(),o=a.encodings.length-1-r;a.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(a)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const a=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(a)))}})}}class fh extends gh{static createFactory(t){return()=>new fh(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var f;const p=o.codecs.find(T=>T.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const T=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];T.push(...u.parameters);const E=[...new Set(T).values()];p.sdpFmtpLine=E.join(";")}c.push(p)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),a.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:p}=this,f=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${f}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),a.mid),sender:a.sender,mid:a.mid}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function J0(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}var $o,bi,bs,Rd,_s,Tr,Bo,bu,kd,Pf,Md,bf;class K0 extends Cl{constructor(e,r){var i;super(e);g(this,_s);g(this,Bo);g(this,kd);g(this,Md);h(this,"rtpReceiver");h(this,"id");h(this,"localId");h(this,"producerId");h(this,"producingTransportId");h(this,"mimeType");h(this,"track");h(this,"peerId");h(this,"appData");h(this,"transceiver");g(this,$o,void 0);g(this,bi,void 0);g(this,bs,void 0);g(this,Rd,void 0);this.id=r.id,this.localId=r.localId,m(this,$o,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,m(this,bs,!1),this.producerId=r.producerId,this.track=r.track,m(this,bi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,L(this,kd,Pf).call(this),m(this,Rd,e)}get closed(){return n(this,bs)}get kind(){return this.track.kind}get paused(){return n(this,bi)}close(e,r){n(this,bs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,n(this,_s,Tr)),m(this,bs,!0),r&&(L(this,Md,bf).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(n(this,bs))throw new yt("closed");return n(this,$o).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",n(this,_s,Tr)),n(this,bs)){this.logger.error("consumer::pause() | Consumer closed",n(this,_s,Tr));return}m(this,bi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",n(this,_s,Tr)),n(this,bs)){this.logger.error("Consumer::resume() | Consumer closed",n(this,_s,Tr));return}m(this,bi,!1),this.track.enabled=!0,this.safeEmit("resume")}}$o=new WeakMap,bi=new WeakMap,bs=new WeakMap,Rd=new WeakMap,_s=new WeakSet,Tr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Bo=new WeakSet,bu=function(){this.logger.debug('Consumer::track "ended" event',n(this,_s,Tr)),this.safeEmit("trackended")},kd=new WeakSet,Pf=function(){this.track.addEventListener("ended",L(this,Bo,bu).bind(this))},Md=new WeakSet,bf=function(){try{this.track.removeEventListener("ended",L(this,Bo,bu)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...n(this,_s,Tr),error:e})}};var cs,ea,ta,_i,Jt,Ke,Dr,sa,Id,It,ss;class z0 extends Cl{constructor(e,r){var i,a;super(e);g(this,It);h(this,"id");h(this,"localId");g(this,cs,void 0);h(this,"kind");h(this,"appData");h(this,"rtpSender");g(this,ea,void 0);g(this,ta,void 0);g(this,_i,void 0);g(this,Jt,!1);g(this,Ke,void 0);g(this,Dr,void 0);g(this,sa,void 0);g(this,Id,void 0);this.id=r.id,this.localId=r.localId,m(this,Ke,r.track),this.kind=(i=r.track)==null?void 0:i.kind,m(this,Dr,r.disableTrackOnPause?!((a=r.track)!=null&&a.enabled):!1),m(this,sa,void 0),m(this,ea,r.stopTracks),m(this,ta,r.disableTrackOnPause),m(this,_i,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),m(this,cs,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),m(this,Id,e)}get closed(){return n(this,Jt)}get track(){return n(this,Ke)}get paused(){return n(this,Dr)}get maxSpatialLayer(){return n(this,sa)}async close(e){if(n(this,Jt))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,n(this,It,ss)),m(this,Jt,!0),this._destroyTrack(),e===dd){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await n(this,cs).stopSending(this.localId),{answer:a}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(a)}async getStats(){if(n(this,Jt))throw new yt("closed");return n(this,cs).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",n(this,It,ss)),n(this,Jt)&&this.logger.error("Producer::pause() | Producer closed",n(this,It,ss)),m(this,Dr,!0),n(this,Ke)&&n(this,ta)&&(n(this,Ke).enabled=!1),n(this,_i)&&n(this,cs).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",n(this,It,ss)),n(this,Jt)){this.logger.error("Producer::resume() | Producer closed",n(this,It,ss));return}m(this,Dr,!1),n(this,Ke)&&n(this,ta)&&(n(this,Ke).enabled=!0),n(this,_i)&&n(this,cs).replaceTrack(this.localId,n(this,Ke)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,n(this,It,ss)),n(this,Jt)){if(e&&n(this,ea))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...n(this,It,ss),error:r})}throw new yt("closed")}else if(e&&e.readyState==="ended")throw new yt("track ended");if(e===n(this,Ke)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,n(this,It,ss));return}(!n(this,_i)||!n(this,Dr))&&await n(this,cs).replaceTrack(this.localId,e),this._destroyTrack(),m(this,Ke,e),this._handleTrack()}async setMaxSpatialLayer(e){if(n(this,Jt))throw new yt("closed");if(this.kind!=="video")throw new go("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await n(this,cs).setMaxSpatialLayer(this.localId,e),m(this,sa,e)}async setRtpEncodingParameters(e){if(n(this,Jt))throw new yt("closed");if(typeof e!="object")throw new TypeError("invalid params");await n(this,cs).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,n(this,It,ss)),this.safeEmit("trackended",this.track.id)}_handleTrack(){n(this,Ke)&&n(this,Ke).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(n(this,Ke))try{n(this,Ke).removeEventListener("ended",this._onTrackEnded),n(this,ea)&&n(this,Ke).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...n(this,It,ss),error:r})}}}cs=new WeakMap,ea=new WeakMap,ta=new WeakMap,_i=new WeakMap,Jt=new WeakMap,Ke=new WeakMap,Dr=new WeakMap,sa=new WeakMap,Id=new WeakMap,It=new WeakSet,ss=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function _f(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Jl(s){return Math.random().toString(36).substring(2,2+s)}const xc=1;function Bp(s){const t=s;return delete t.payload._bolt,t}function Y0(s){return s.payload&&_f(s.payload)}function Q0(s){var t,e;return Y0(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}var Or,Ad,Ci;const ln=class extends st.EventEmitter{constructor(e,r,i,a){super();h(this,"channel");h(this,"queue");h(this,"serverProtocolVersion");g(this,Or,new Map);g(this,Ad,void 0);g(this,Ci,void 0);h(this,"respond",(e,r,i=!1)=>{let a;i?a=ln.createErrorResponse(e,r):a=ln.createResponse(e,r),this.channel.send(JSON.stringify(a))});h(this,"notify",e=>{const r=ln.createNotification(e);this.channel.send(JSON.stringify(r))});h(this,"request",async e=>{const r=ln.createRequest(e),i=new Promise((a,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),a(u))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(u))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});h(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const a=i-200,o=Math.ceil(r.length/a),c=[];for(let l=0;l<o;l+=1){const u=l*a,p=(l+1)*a;c.push(r.slice(u,p))}const d=nr.v4();for(let l=0;l<o;l+=1){const u=c[l],f=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});n(this,Ci).debug(`Sending message chunk over dc: ${f}`),this.channel.send(f)}}else n(this,Ci).debug(`Sending message over dc: ${r}`),this.channel.send(r)});h(this,"processMessage",e=>{var i;n(this,Or).has(e.id)||n(this,Or).set(e.id,[]);const r=n(this,Or).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(a=>a===void 0)){const a=n(this,Or).get(e.id),o=a==null?void 0:a.reduce((d,l)=>d+l.chunk,"");n(this,Or).delete(e.id);const c=JSON.parse(o);if(!c.payload||!_f(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});h(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(n(this,Ci).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(Bp(e)):i.resolve(Bp(e)),!0):!1});h(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:Jl(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=a,m(this,Ad,e),m(this,Ci,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Xr=ln;Or=new WeakMap,Ad=new WeakMap,Ci=new WeakMap,h(Xr,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:Jl(8),type:"REQUEST",version:xc}}}}),h(Xr,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:xc}}}}),h(Xr,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:Jl(8),type:"NOTIFY",version:xc}}}}),h(Xr,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:xc}}}));const dd="transport closed";var wi;const un=class extends Cl{constructor(e,{id:r,direction:i,handlerFactory:a,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:p}){var b,_,M;super(e);h(this,"awaitQueue");h(this,"observer");h(this,"id");h(this,"serverId");h(this,"direction");h(this,"maxSctpMessageSize");h(this,"handler");h(this,"connectionState","new");h(this,"producers");h(this,"consumers");h(this,"datachannels");h(this,"connected",!1);h(this,"eventsDCReadyPromise");h(this,"eventsDCReadyPromiseResolver");h(this,"eventsDCFailureTimer");h(this,"transportConnectionPromise");h(this,"consumerTrackEvents");h(this,"unknownTracksMap");h(this,"appData");g(this,wi,void 0);m(this,wi,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const T=J0(l,{});delete T.iceServers,delete T.iceTransportPolicy,delete T.bundlePolicy,delete T.rtcpMuxPolicy,delete T.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Pu(f,!0),this.handler=a(),this.handler.enableHighBitrate=(b=p==null?void 0:p.enableHighBitrate)!=null?b:!1,this.handler.enableStereo=(_=p==null?void 0:p.enableStereo)!=null?_:!1,this.handler.enableDtx=(M=p==null?void 0:p.enableDtx)!=null?M:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const E=3e4;this.transportConnectionPromise=new Promise(A=>{const x=setTimeout(()=>{f.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),A(!1)},E);this.once("connected",()=>{clearTimeout(x),A(!0)}),this.once("disconnect",()=>{clearTimeout(x),A(!1)}),this.once("close",()=>{clearTimeout(x),A(!1)})}),this.eventsDCReadyPromise=new Promise(A=>{this.eventsDCReadyPromiseResolver=A}),this.handler.on("@connectionstatechange",A=>{A!==this.connectionState&&(this.logger.debug(`connection state changed to ${A}`),this.connectionState=A,A==="connected"&&(this.connected=!0,this.emit("connected")),A==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(A==="failed"||A==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",A))}),this.handler.on("@icecandidate",({candidate:A})=>{this.closed||this.safeEmit("icecandidate",A)}),this.handler.on("dc_open",A=>{let x=this.datachannels.get(A.label);x||(x||(x=new Xr(n(this,wi),A,A.label,this.serverId),this.datachannels.set(A.label,x)),this.eventsDCFailureTimer=setTimeout(()=>{A.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",A.label))},5e3))}),this.handler.on("datachannel",(A,x)=>{A.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const N=this.datachannels.get(A.label);if(!N){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:A.label,message:x}});return}try{const $=JSON.parse(x);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:$.id,count:$.count,chunkIndex:$.chunkIndex,chunk:$.chunk,transprtId:this.serverId}});const K=N.processMessage($);if(!K)return;this.logger.debug(`datachannel message with id:${$.id} on transport:${this.serverId}complete - ${JSON.stringify(K)}`),this.emit(`datachannel:${A.label}`,N.label,K)}catch($){this.logger.error("error parsing message",{error:$})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(dd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(dd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new yt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:a,answer:o}=await e(r);this.setServerId(a),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new yt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new go("not a sending Transport");if(r.readyState==="ended")throw new yt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new si("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:a,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:p={}}=e;this.logger.debug(`produce() [track:${a.id}]`);const{producerId:f,localId:T,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:b,callback:_,sender:M,mid:A}=await this.handler.send({track:a,encodings:o,codecOptions:c,screenShare:p==null?void 0:p.screenShare}),{answer:x,producerId:N}=await r({offer:b,kind:a.kind,paused:l?!a.enabled||Object.hasOwn(a,"fakeTracks"):!1,appData:{...p||{},mid:A},codecOptions:c,producingTransportId:this.serverId}),$=await _(x);return{producerId:N,localId:$,rtpSender:M}},"Transport.produce");return this.createProducerObject({id:f,localId:T,track:a,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:p,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new z0(n(this,wi),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new yt("closed");if(this.direction!=="recv")throw new go("not a receiving transport");if(!await this.transportConnectionPromise)throw new si("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const a={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,p)=>{a[p]=this.createConsumerObjectAndWaitForTrack({...u,producerId:p})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(a).map(([u,p])=>p.then(f=>l.push(f)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=rs.parse(e.sdp),a={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(a[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),a}static setCodecAndFmtpMappings(e,r,i){const a=rs.parse(e.sdp);return a.media=a.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:rs.write(a)}}static parseHeaderExtensionMappings(e){const r=rs.parse(e.sdp),i={};return r.media.forEach(a=>{i[a.mid]=a.ext}),i}static setHeaderExtensionMappings(e,r){const i=rs.parse(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:rs.write(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),a=un.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=un.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=un.setCodecAndFmtpMappings(c,i,a),c=un.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=rs.parse(r.sdp);return i.media=i.media.map(a=>{if(a.type==="audio"){const o={...a},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return a}),r.sdp=rs.write(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const a=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(a)});const o=this.consumerTrackEvents.get(a);o?(o(r,i),this.consumerTrackEvents.delete(a)):(this.logger.warn(`track event handler not found ${a}`),this.unknownTracksMap.set(a,e))}sendErrorOverDC(e,r,i){const a=this.getDatachannel(e);if(!a)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});a.respond(r,i,!0)}sendResponseOverDC(e,r,i){const a=this.getDatachannel(e);if(!a)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});a.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:a,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:p,mimeType:f}=e,T=`${c}:${p}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(b,_)=>{const M=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${T} producingPeerId: ${a}`),this.consumerTrackEvents.delete(T),E.isTimedout=!0,_(E)},5e3),A=(N,$)=>{try{if(N.readyState==="ended")clearTimeout(M),_(E);else{const K=N;K.enabled=!0,this.handler.midTransceiverMap.set($.mid,$);const Z=new K0(n(this,wi),{id:r,localId:$.mid,transceiver:$,track:K,paused:d,producerId:i,producingPeerId:a,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:a},rtpReceiver:$.receiver,mimeType:f});this.consumers.set(r,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete($.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:p,appData:{screenShare:l},peerId:a,producerId:i}}),this.emit("newconsumer",Z),clearTimeout(M),b(Z)}}catch(K){this.logger.warn("error while creating consumer:",K),clearTimeout(M),_(E)}},x=this.unknownTracksMap.get(T);x?(this.logger.info(`track event already received [trackId: ${x.track.id}] [mid: ${x.transceiver.mid}]`),this.unknownTracksMap.delete(T),A(x.track,x.transceiver)):(this.logger.info(`Registering onTrack handler for key ${T} [producingPeerId: ${a}]`),this.consumerTrackEvents.set(T,A))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw F0("DC_NOT_READY",`${e} datachannel not ready`);const a=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(a)}`),a}};let _u=un;wi=new WeakMap;function X0(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=mg.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}var Gs,Ri;class Z0{constructor(t,{handlerName:e,handlerFactory:r}={}){h(this,"handlerFactory");g(this,Gs,void 0);g(this,Ri,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),m(this,Gs,t),m(this,Ri,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)n(this,Ri).debug(`Device::constructor() | handler given: ${e}`);else if(e=X0(n(this,Ri)),e)n(this,Ri).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=mh.createFactory(n(this,Gs));break;case"Safari12":this.handlerFactory=fh.createFactory(n(this,Gs));break;case"Firefox60":this.handlerFactory=cd.createFactory(n(this,Gs),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=cd.createFactory(n(this,Gs),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=nr.v4();return new _u(n(this,Gs),{id:e,...t,handlerFactory:this.handlerFactory})}}Gs=new WeakMap,Ri=new WeakMap;const eD=2e3;var ra,Ze,et,Ho,Fo,ki,ia,qo,na,Mi,Cs,aa,Kc,jo,Cu,Dd,Cf,Go,wu,Od,wf,Nd,Rf,Ld,kf,Vd,Mf,xd,If,Wo,Ru,Jo,ku;class tD extends st.EventEmitter{constructor(e,r){super();g(this,aa);g(this,jo);g(this,Dd);g(this,Go);g(this,Od);g(this,Nd);g(this,Ld);g(this,Vd);g(this,xd);g(this,Wo);g(this,Jo);h(this,"context");g(this,ra,void 0);g(this,Ze,void 0);g(this,et,void 0);g(this,Ho,void 0);g(this,Fo,void 0);g(this,ki,void 0);g(this,ia,void 0);g(this,qo,void 0);g(this,na,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,Mi,void 0);g(this,Cs,"all");this.context=e,m(this,ki,r),m(this,ra,new Z0(e)),m(this,ia,new W0(r)),m(this,qo,gs),n(this,aa,Kc).mediaState={send:{state:mn.NEW},recv:{state:mn.NEW}},ya(this.context,"forceRelay")&&m(this,Cs,"relay"),this.logger.info(`ICE Transport Policy initially set to ${n(this,Cs)}`),L(this,jo,Cu).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return n(this,ki)}get socketHandler(){return n(this,ia)}get sendTransport(){return n(this,Ze)}get recvTransport(){return n(this,et)}get events(){return n(this,qo)}set sendTransportConnectedCallback(e){m(this,Ho,e)}set recvTransportConnectedCallback(e){m(this,Fo,e)}async setupTransports(e){await L(this,Dd,Cf).call(this,e);let r,i;e.send&&(r=L(this,Go,wu).call(this,n(this,Ze)).then(a=>{try{n(this,Ho).call(this,a)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=L(this,Go,wu).call(this,n(this,et)).then(a=>{try{n(this,Fo).call(this,a)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,Ze);this.logger.info("Closing send transport",{transport:{id:a,serverId:o,type:c}}),n(this,Ze).close(),n(this,Ze).removeAllListeners(),m(this,Ze,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,et);this.logger.info("Closing recv transport",{transport:{id:a,serverId:o,type:c}}),(r=n(this,et))==null||r.close(),(i=n(this,et))==null||i.removeAllListeners(),m(this,et,void 0)}L(this,jo,Cu).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}ra=new WeakMap,Ze=new WeakMap,et=new WeakMap,Ho=new WeakMap,Fo=new WeakMap,ki=new WeakMap,ia=new WeakMap,qo=new WeakMap,na=new WeakMap,Mi=new WeakMap,Cs=new WeakMap,aa=new WeakSet,Kc=function(){return this.context.getValue("connectionHandler")},jo=new WeakSet,Cu=function(){m(this,Mi,{send:void 0,recv:void 0})},Dd=new WeakSet,Cf=async function(e){var o,c,d,l,u,p,f,T;ya(this.context,"forceRelay")&&m(this,Cs,"relay"),this.logger.info(`ICE Transport Policy set to ${n(this,Cs)}`);const a=await ht().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&L(this,Nd,Rf).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(f=(p=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:p.enableStereo)!=null?f:!1,enableDtx:!1},iceTransportPolicy:n(this,Cs)}),e.recv&&L(this,Ld,kf).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(T=this.context.getValue("modules").e2ee)==null?void 0:T.enabled},iceTransportPolicy:n(this,Cs)})},Go=new WeakSet,wu=async function(e){const{id:r,serverId:i,direction:a}=e;L(this,Vd,Mf).call(this,e);try{return await Ef(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:a}});try{if(e.closed)throw new si("Cannot reconnect closed transport");await L(this,Od,wf).call(this,e)}catch(l){if(l instanceof si){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:a}}),e.close(),e.removeAllListeners(),o}},Od=new WeakSet,wf=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!n(this,ki).isConnected)throw new si("Socket is not connected");if(e.connectionState==="closed")throw new si("Transport is closed");try{await e.connect(a=>L(this,xd,If).call(this,i,a)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(a){throw n(this,na).transportFailureCount[i]+=1,a.message==="ice connection failed"?new si(a.message):a}},Nd=new WeakSet,Rf=function(e){var r,i;if(n(this,Ze)&&n(this,Ze).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=n(this,Ze))==null?void 0:r.id,serverId:(i=n(this,Ze))==null?void 0:i.serverId,type:"send"}});return}m(this,Ze,n(this,ra).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(n(this,Ze))},Ld=new WeakSet,kf=function(e){var r,i;if(n(this,et)&&n(this,et).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=n(this,et))==null?void 0:r.id,serverId:(i=n(this,et))==null?void 0:i.serverId,type:"recv"}});return}m(this,et,n(this,ra).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(n(this,et))},Vd=new WeakSet,Mf=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async a=>{L(this,Jo,ku).call(this,{state:a,direction:r}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:a}});const o=()=>{const c=n(this,Mi)[r];c!==void 0&&(clearTimeout(c),n(this,Mi)[r]=void 0)};switch(a){case"connected":o(),n(this,na).lastConnectionTime=performance.now();break;case"disconnected":n(this,Mi)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await L(this,Wo,Ru).call(this,e.direction)},eD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await L(this,Wo,Ru).call(this,e.direction);break}}),e.on("icecandidate",async a=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:a})}),e.on("datachannel:events",async(a,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:a,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(a,Q0(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${a}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},xd=new WeakSet,If=async function(e,r){const i=e==="recv";try{const{sdp:a,type:o}=r,c={consuming:i,description:{sdp:a,type:o,target:i?or.SUBSCRIBER:or.PUBLISHER},producers:[]};return n(this,ia).connectTransport(c)}catch(a){throw this.logger.error(`Error in ${e} transport connection:`,{error:a}),a}},Wo=new WeakSet,Ru=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),n(this,ki).isConnected&&n(this,na).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),m(this,Cs,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:n(this,Ze)}),this.context.getValue("peerSessionStore").emit(C.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:n(this,et)}),this.context.getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}L(this,Jo,ku).call(this,{state:mn.CONNECTED,direction:e})},Jo=new WeakSet,ku=function(e){const{state:r,direction:i}=e;n(this,aa,Kc).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(C.TRANSPORT_STATE_UPDATE,{transport:i,...n(this,aa,Kc).mediaState[i]})};var Ud,Kt;class sD{constructor(t,e,r,i,a){g(this,Ud,void 0);g(this,Kt,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=a,m(this,Ud,t),m(this,Kt,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:p}=d,f={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:p,...f})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),a=new Map;t.forEach(d=>a.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=a.get(d);if(!u)return;if(l.errorCode){n(this,Kt).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let p={};try{p=JSON.parse(l.producerState.appData)}catch(f){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:p})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{n(this,Kt).info("Negotiating socket consumer",{transport:this.recvTransport}),n(this,Kt).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:or.SUBSCRIBER}};return n(this,Kt).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,K_.toBinary(r)),n(this,Kt).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){n(this,Kt).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const a=r.map(l=>l.localId);n(this,Kt).info(`Closing consumers: ${JSON.stringify(a)}`);const o={description:{sdp:i.sdp,type:i.type,target:or.SUBSCRIBER},consumerIds:a,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=Ew.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(a=>a&&a.id);i.forEach(({id:a,producingTransportId:o,localId:c})=>{r.requests.push({producerId:a,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),n(this,Kt).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:a})=>a)})}}Ud=new WeakMap,Kt=new WeakMap;class Th{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return rs.parse(t).media.filter(a=>e==="video"?a.type==="video":a.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:a,producingTransportId:o}){var p,f;const c=Th.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:or.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(p=i.screenShare)!=null?p:!1,mimeType:`${e}/${(f=a[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}var Ii,Nr,oa,Ko,ws,$d,Ws,ca,zo,Mu,Bd,Af,Hd,Df,Fd,Of,qd,Nf;class rD extends tD{constructor(e,r){super(e,r);g(this,zo);g(this,Bd);g(this,Hd);g(this,Fd);g(this,qd);g(this,Ii,void 0);g(this,Nr,void 0);g(this,oa,void 0);g(this,Ko,void 0);g(this,ws,void 0);g(this,$d,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,Ws,[]);g(this,ca,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{m(this,Ko,new Th(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{n(this,oa).clear(),m(this,ws,new sD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return n(this,Ii)}get consumers(){return n(this,Nr)}get producerIdToConsumerIdMap(){return n(this,oa)}get logger(){return this.context.getValue("logger")}reset(){m(this,Ii,new Map),m(this,Nr,new Map),m(this,oa,new Map)}async createProducer(e,r){var i,a;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,L(this,Bd,Af).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_ACTIVE_PRODUCER,o),L(this,Hd,Df).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((a=e==null?void 0:e.track)==null?void 0:a.kind)||"unknown"} producer`,{error:o}),n(this,$d).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var a;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),(a=this.context.getValue("modules").e2ee)!=null&&a.enabled&&this.context.getValue("peerSessionStore").emit(C.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(n(this,Ii).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){n(this,ca)||clearTimeout(n(this,ca)),m(this,Ws,n(this,Ws).concat(e)),await L(this,zo,Mu).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!n(this,ws))return;const r=e.map(a=>this.consumers.get(a)).filter(a=>a!==void 0);if(r.length===0)return;const{failedConsumers:i}=await n(this,ws).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(n(this,Nr).keys()))}async switchConsumersToLayer(e,r){n(this,ws).switchConsumersToLayer(e,r)}}Ii=new WeakMap,Nr=new WeakMap,oa=new WeakMap,Ko=new WeakMap,ws=new WeakMap,$d=new WeakMap,Ws=new WeakMap,ca=new WeakMap,zo=new WeakSet,Mu=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=n(this,Ws).splice(0,n(this,Ws).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),a=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(a.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(a,L(this,Fd,Of).bind(this),n(this,ws).negotiate.bind(n(this,ws)));if(o.forEach(L(this,qd,Nf).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);m(this,Ws,n(this,Ws).concat(d)),m(this,ca,setTimeout(L(this,zo,Mu).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(a){}await this.setupTransports({recv:!0})}}},Bd=new WeakSet,Af=function(e){return n(this,Ko).create(e)},Hd=new WeakSet,Df=function(e,r){e.on("close",async(i,a)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==dd){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:or.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),a({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),n(this,Ii).set(e.id,e)},Fd=new WeakSet,Of=async function(e){try{return await this.recvTransport.canConsume(),await n(this,ws).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},qd=new WeakSet,Nf=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),n(this,Nr).delete(e.id),this.context.getValue("peerSessionStore").emit(C.CONSUMER_CLOSED,{id:e.id})}),n(this,Nr).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(C.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};var Yo,Qo,Xo,da,la,ua,Zo,ec,ha,ft,ds,ls,Ai,Di,Js,tc,jd,Lf,Gd,Vf,Wd,xf,Jd,Uf;const Kd=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:a=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,jd);g(this,Gd);g(this,Yo,void 0);g(this,Qo,void 0);g(this,Xo,void 0);g(this,da,void 0);g(this,la,void 0);g(this,ua,void 0);g(this,Zo,void 0);g(this,ec,void 0);g(this,ha,void 0);g(this,ft,void 0);g(this,ds,void 0);g(this,ls,!1);g(this,Ai,0);g(this,Di,0);g(this,Js,[]);g(this,tc,void 0);m(this,da,t),m(this,ft,t),m(this,Yo,e),m(this,Qo,r),m(this,Xo,i),m(this,la,a),m(this,ua,o),m(this,Zo,c),m(this,ec,d),m(this,ha,l),m(this,tc,u),m(this,ds,t/2)}get voiceDetected(){return n(this,ls)}processAudioChunk(t){var o,c;const e=L(o=Kd,Wd,xf).call(o,t),r=L(c=Kd,Jd,Uf).call(c,t);return L(this,jd,Lf).call(this,e),e/n(this,ds)>n(this,ha)&&e>n(this,ft)&&r>n(this,Yo)?(m(this,Ai,n(this,Ai)+1),m(this,Di,n(this,Xo)),n(this,Ai)>=n(this,Qo)&&m(this,ls,!0)):(m(this,Ai,0),n(this,Di)>0?m(this,Di,n(this,Di)-1):n(this,ls)&&m(this,ls,!1),n(this,ls)||L(this,Gd,Vf).call(this,e)),{energy:e,isVoice:n(this,ls)}}reset(){m(this,ls,!1),m(this,Ai,0),m(this,Di,0),m(this,ft,n(this,da)),m(this,ds,n(this,da)/2),m(this,Js,[])}getThresholdInfo(){return{currentEnergyThreshold:n(this,ft),backgroundNoiseEnergy:n(this,ds),energyRatioThreshold:n(this,ha)}}};let Ya=Kd;Yo=new WeakMap,Qo=new WeakMap,Xo=new WeakMap,da=new WeakMap,la=new WeakMap,ua=new WeakMap,Zo=new WeakMap,ec=new WeakMap,ha=new WeakMap,ft=new WeakMap,ds=new WeakMap,ls=new WeakMap,Ai=new WeakMap,Di=new WeakMap,Js=new WeakMap,tc=new WeakMap,jd=new WeakSet,Lf=function(t){n(this,ls)?m(this,ft,n(this,ua)*n(this,ft)+(1-n(this,ua))*t):m(this,ft,n(this,la)*n(this,ft)+(1-n(this,la))*n(this,ds)),m(this,ft,Math.max(n(this,Zo),Math.min(n(this,ec),n(this,ft))))},Gd=new WeakSet,Vf=function(t){if(t<n(this,ft)*1.2)if(n(this,Js).push(t),n(this,Js).length>n(this,tc)&&n(this,Js).shift(),n(this,Js).length>=10){const e=[...n(this,Js)].sort((i,a)=>i-a),r=Math.floor(e.length/2);m(this,ds,e[r])}else m(this,ds,.95*n(this,ds)+.05*t)},Wd=new WeakSet,xf=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Jd=new WeakSet,Uf=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(Ya,Wd),g(Ya,Jd);var sc;class Hp{constructor(t){h(this,"RNAudioSampleHandler");g(this,sc,void 0);m(this,sc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return n(this,sc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}sc=new WeakMap;var rc;class Fp{constructor(t){h(this,"audioContext");h(this,"analyser");g(this,rc,void 0);m(this,rc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return n(this,rc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}rc=new WeakMap;class iD{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const nD=60,aD=400;var Ks,zs,Ys,ic,pa,ga,Lr,Oi,ma,Ni,Qs,Rs,zd,$f,nc,Iu,Yd,Bf,Qd,Hf;const oo=class{constructor(t,e){g(this,zd);g(this,Yd);g(this,Ks,void 0);g(this,zs,void 0);g(this,Ys,void 0);g(this,ic,void 0);g(this,pa,void 0);g(this,ga,void 0);g(this,Lr,void 0);g(this,Oi,void 0);g(this,ma,void 0);g(this,Ni,void 0);g(this,Qs,void 0);g(this,Rs,void 0);this.reportRequest=e,m(this,Ni,t),m(this,ga,new Ya);const{isReactNative:r}=navigator;m(this,Qs,r?new Hp(n(this,Ni)):new Fp(n(this,Ni))),m(this,Rs,r?iD:Uc)}get logger(){return n(this,Ni).getValue("logger")}set producerId(t){m(this,Ys,t)}set audioTrack(t){m(this,ic,t),n(this,Qs)instanceof Fp&&(n(this,Qs).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${n(this,Ys)}`),n(this,Ks)&&n(this,Rs).clearInterval(n(this,Ks)),m(this,Ks,n(this,Rs).setInterval(async()=>{var i;if(!n(this,ic)||!n(this,Ys))return;const{energy:t}=L(this,zd,$f).call(this),e=L(i=oo,nc,Iu).call(i,t);let r=.9;n(this,ma)!==e&&n(this,ma)?r=.9:e?r=.3:r=.5,m(this,pa,(n(this,pa)||0)*(1-r)+t*r)},nD)),n(this,zs)&&n(this,Rs).clearInterval(n(this,zs)),m(this,zs,n(this,Rs).setInterval(L(this,Yd,Bf).bind(this),aD))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${n(this,Ys)}`),n(this,Ks)&&(n(this,Rs).clearInterval(n(this,Ks)),m(this,Ks,void 0)),n(this,zs)&&(n(this,Rs).clearInterval(n(this,zs)),m(this,zs,void 0))}catch(t){}n(this,ga).reset(),n(this,Qs)instanceof Hp&&n(this,Qs).stop()}};let Qa=oo;Ks=new WeakMap,zs=new WeakMap,Ys=new WeakMap,ic=new WeakMap,pa=new WeakMap,ga=new WeakMap,Lr=new WeakMap,Oi=new WeakMap,ma=new WeakMap,Ni=new WeakMap,Qs=new WeakMap,Rs=new WeakMap,zd=new WeakSet,$f=function(){var o;const{samples:t}=n(this,Qs),{energy:e,isVoice:r}=n(this,ga).processAudioChunk(t),i=L(o=oo,Qd,Hf).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,Lr)||i<n(this,Lr))&&m(this,Lr,i),(!n(this,Oi)||i>n(this,Oi))&&m(this,Oi,i),{energy:(i-n(this,Lr))/(n(this,Oi)-n(this,Lr))*10||0,isVoice:r})},nc=new WeakSet,Iu=function(t){return t<5},Yd=new WeakSet,Bf=function(t=n(this,pa)){var r;if(!n(this,Ys)||!t)return;const e={producerId:n(this,Ys),energy:Math.round(t),silent:L(r=oo,nc,Iu).call(r,t)};m(this,ma,e.silent),this.reportRequest(e)},Qd=new WeakSet,Hf=function(t){const e=Math.log10(t);return Math.round(e)},g(Qa,nc),g(Qa,Qd);var oD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,ne=(s,t,e,r)=>{for(var i=r>1?void 0:r?cD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&oD(t,e,i),i},ac,oc,tt,q,Xd,dt,Li,Vi,xi,cc,zt,Xs,lt,Tt,Vr,nn,Zd,Ff,el,qf,tl,jf,dc,Au,sl,Gf,rl,Wf,ut,_t,Ui,Xa,il,Jf,nl,Kf,al,zf;class se{constructor(t,e){g(this,Vr);g(this,Zd);g(this,el);g(this,tl);g(this,dc);g(this,sl);g(this,rl);g(this,ut);g(this,Ui);g(this,il);g(this,nl);g(this,al);h(this,"context");h(this,"authToken");h(this,"e2ee");g(this,ac,void 0);g(this,oc,void 0);g(this,tt,void 0);g(this,q,void 0);g(this,Xd,void 0);g(this,dt,void 0);g(this,Li,void 0);g(this,Vi,void 0);g(this,xi,void 0);g(this,cc,void 0);g(this,zt,null);g(this,Xs,void 0);g(this,lt,void 0);g(this,Tt,void 0);var i,a;this.context=t;const{socket:r}=e;this.mediaJoined=!1,m(this,tt,r),m(this,Li,!1),m(this,q,new rD(t,r)),m(this,dt,n(this,q).events),m(this,Xs,new Set),m(this,lt,new Map),m(this,Vi,!1),m(this,xi,new Pu(t.getValue("logger"))),m(this,Tt,new Qa(this.context,n(this,q).socketHandler.audioActivity.bind(n(this,q).socketHandler))),this.e2ee=(a=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?a:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,cc,th(async()=>{if(!n(this,Vr,nn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(n(this,oc),n(this,ac),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(C.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return n(this,Vr,nn).mediaJoined}set mediaJoined(t){n(this,Vr,nn).mediaJoined=t}reset(){n(this,q).closeAllProducers(),n(this,q).closeAllConsumers(),n(this,lt).clear(),n(this,Xs).clear(),m(this,zt,null),n(this,xi).stop(),n(this,q).stopAllTransports(),n(this,q).reset(),m(this,xi,new Pu)}async joinRoom(t,e,r=!1,i=!1,a={}){n(this,Vr,nn).mediaJoinAttempted=!0,m(this,Li,!0),r&&this.reset();try{return await n(this,xi).push(()=>L(this,Zd,Ff).call(this,t,e,i,a),"joinRoom")}catch(o){return this.logger.error("Error in room joining process",{error:o}),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return n(this,zt)?n(this,zt):(m(this,zt,(async()=>{try{await L(this,dc,Au).call(this,t,e,r,i)}catch(a){throw m(this,zt,null),a}})()),n(this,zt))}getConsumers(){return n(this,q).consumers}getProducers(){return n(this,q).producers}async leaveRoom(){n(this,q).stopAllTransports(),m(this,Vi,!1),n(this,Vr,nn).mediaJoinAttempted=!1;const t={closeRoom:!1};n(this,tt).sendMessagePromise(n(this,dt).leaveRoom,vC.toBinary(t)).then(r=>{var i;(i=ow.fromBinary(r.payload))!=null&&i.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(r=>{this.logger.error("error on sending leave room request",{error:r})}),this.context.getValue("callstats").callEnded(),await this.context.getValue("telemetry").destruct()}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():n(this,q).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const a=n(this,q).producerIdToConsumerIdMap.get(i.producerId);return a?(r.push(a),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await n(this,q).closeConsumers(e)}async _shareWebcam(t){var u,p,f,T;const e=Ee.WEBCAM,r=L(this,ut,_t).call(this,e);if(r){const E=await r;if(n(this,q).producers.has(E)){const b=n(this,q).producers.get(E);if(!b.closed)return await b.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=L(this,al,zf).call(this,t),a=ya(this.context,"disableSimulcast"),o=(p=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:p.simulcastConfig;a||o&&o.disable||!((T=(f=this.context)==null?void 0:f.getValue("theme"))!=null&&T.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=zA(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,lt).delete(e)},l=n(this,q).createProducer(i,d);return L(this,Ui,Xa).call(this,e,l.then(E=>E.id)),l.then(E=>E.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ge.isElectron()},stopTracks:!1},a=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,lt).delete(Ee.SCREENSHARE_VIDEO),n(this,lt).delete(Ee.SCREENSHARE_AUDIO)},o=n(this,q).createProducer(i,a);L(this,Ui,Xa).call(this,Ee.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ge.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=n(this,q).createProducer(d,l),L(this,Ui,Xa).call(this,Ee.SCREENSHARE_AUDIO,c.then(u=>u.id))}await Promise.all([o,c||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new yt("track undefined");const e=L(this,ut,_t).call(this,Ee.MIC);if(e){const o=await e;if(n(this,q).producers.has(o)){const c=n(this,q).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),n(this,Tt)&&(n(this,Tt).audioTrack=t,n(this,Tt).producerId=o,n(this,Tt).start());return}await n(this,q).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=L(this,nl,Kf).call(this,t),i=()=>{n(this,lt).delete(Ee.MIC)},a=n(this,q).createProducer(r,i);L(this,Ui,Xa).call(this,Ee.MIC,a.then(o=>o.id)),await a.then(o=>{n(this,Tt)&&(n(this,Tt).audioTrack=o.track,n(this,Tt).producerId=o.id,n(this,Tt).start())})}catch(e){throw new R(e)}}async pauseMic(){var i;const t=await L(this,ut,_t).call(this,Ee.MIC),e=n(this,q).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=n(this,Tt))==null||i.stop();const r={producerId:e.id,pause:!0};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(r))}async pauseWebcam(){const t=await L(this,ut,_t).call(this,Ee.WEBCAM),e=n(this,q).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(r))}async resumeMic(){const t=await L(this,ut,_t).call(this,Ee.MIC),e=n(this,q).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(r))}async resumeWebcam(t=Ee.WEBCAM){const e=await L(this,ut,_t).call(this,t),r=n(this,q).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(i))}async disableWebcam(){const t=Ee.WEBCAM,e=await L(this,ut,_t).call(this,t);L(this,il,Jf).call(this,t),e&&await n(this,q).closeProducer(e)}async disableMic(){var e;const t=await L(this,ut,_t).call(this,Ee.MIC);t&&await n(this,q).closeProducer(t),(e=n(this,Tt))==null||e.stop(),n(this,lt).delete(Ee.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await L(this,ut,_t).call(this,Ee.SCREENSHARE_VIDEO),e=await L(this,ut,_t).call(this,Ee.SCREENSHARE_AUDIO);t&&await n(this,q).closeProducer(t),e&&await n(this,q).closeProducer(e),n(this,Xs).clear(),n(this,lt).delete(Ee.SCREENSHARE_VIDEO),n(this,lt).delete(Ee.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await L(this,ut,_t).call(this,Ee.WEBCAM);await n(this,q).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await L(this,ut,_t).call(this,Ee.SCREENSHARE_VIDEO);await n(this,q).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await n(this,q).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};n(this,q).socketHandler.kickPeer(e)}kickAll(){n(this,q).socketHandler.kickAll()}async muteAll(t){if(!await n(this,q).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,q).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await n(this,q).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await n(this,q).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await n(this,tt).sendMessagePromise(n(this,dt).globalPinPeer,OC.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&n(this,q).producers.get(t.producerId)&&n(this,Xs).add(t.consumerPeerId),n(this,Xs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));n(this,q).switchConsumersToLayer(r,e)}async handleSocketEvents(){n(this,tt).on(n(this,dt).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=xw.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===ir.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(C.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===ir.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),n(this,tt).on(n(this,dt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:a,producerId:o,screenShare:c}}=fp.fromBinary(t);if(c)return;const d=i===ir.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${a} payload: ${JSON.stringify(fp.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&a&&this.context.getValue("peerSessionStore").emit(d==="audio"?C.MUTE_SELF:C.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(C.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:a,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&a||u.paused!==a&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${a}`),a?(u.pause(),this.context.getValue("peerSessionStore").emit(C.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(C.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),n(this,tt).on(n(this,dt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=ru.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),n(this,Xs).delete(e),n(this,q).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(C.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),n(this,tt).on(n(this,dt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=Bw.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(C.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=n(this,q).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),n(this,q).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),n(this,q).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(C.CONSUMER_CLOSED,{id:i})}).catch(a=>{this.logger.error("error closing consumer",{error:a})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),n(this,tt).on(n(this,dt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,Li)&&!n(this,Vi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_DISCONNECTED),n(this,cc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=n(this,q).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(C.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(n(this,q).producers.values()).find(a=>a.id===r);i&&this.context.getValue("peerSessionStore").emit(C.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}ac=new WeakMap,oc=new WeakMap,tt=new WeakMap,q=new WeakMap,Xd=new WeakMap,dt=new WeakMap,Li=new WeakMap,Vi=new WeakMap,xi=new WeakMap,cc=new WeakMap,zt=new WeakMap,Xs=new WeakMap,lt=new WeakMap,Tt=new WeakMap,Vr=new WeakSet,nn=function(){return this.context.getValue("connectionHandler")},Zd=new WeakSet,Ff=async function(t,e,r,i){m(this,oc,t);try{n(this,zt)?await n(this,zt):await L(this,dc,Au).call(this,t,e,r,i),L(this,tl,jf).call(this,e);const{joined:a,error:o}=await L(this,el,qf).call(this);return{roomJoined:a,error:o}}catch(a){return this.logger.error("Failed to complete room join",{error:a}),{roomJoined:!1,error:a}}finally{m(this,zt,null)}},el=new WeakSet,qf=async function(){try{this.mediaJoined=!0;const{roomState:t}=await n(this,q).socketHandler.notifySelfJoinComplete();return m(this,ac,t.roomUuid),m(this,Vi,!0),m(this,Li,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},tl=new WeakSet,jf=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...ge.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},dc=new WeakSet,Au=async function(t,e,r,i){try{const a=L(this,sl,Gf).call(this);await L(this,rl,Wf).call(this,t,e,r,a),await n(this,q).setupTransports({send:!0,recv:!0})}catch(a){throw this.logger.error("Failed to initialize connection",{error:a}),a}},sl=new WeakSet,Gf=function(){const t=G0("video/VP8");return m(this,Xd,t),t},rl=new WeakSet,Wf=async function(t,e,r,i){await Ef(async(a,o)=>{if(!n(this,tt).isConnected){o(new Error("Socket is not connected"));return}a>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${a}`});try{await n(this,q).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},ut=new WeakSet,_t=function(t){return n(this,lt).get(t)},Ui=new WeakSet,Xa=function(t,e){return n(this,lt).set(t,e)},il=new WeakSet,Jf=function(t){return n(this,lt).delete(t)},nl=new WeakSet,Kf=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},al=new WeakSet,zf=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};ne([y.trace("MediaNodeClient.reset")],se.prototype,"reset",1);ne([y.trace("MediaNodeClient.joinRoom")],se.prototype,"joinRoom",1);ne([y.trace("MediaNodeClient.leaveRoom")],se.prototype,"leaveRoom",1);ne([y.trace("MediaNodeClient.activatePeers")],se.prototype,"activatePeers",1);ne([y.trace("MediaNodeClient.createConsumers")],se.prototype,"createConsumers",1);ne([y.trace("MediaNodeClient.closeConsumers")],se.prototype,"closeConsumers",1);ne([y.trace("MediaNodeClient._shareWebcam")],se.prototype,"_shareWebcam",1);ne([y.trace("MediaNodeClient.shareWebcam")],se.prototype,"shareWebcam",1);ne([y.trace("MediaNodeClient.shareScreen")],se.prototype,"shareScreen",1);ne([y.trace("MediaNodeClient.shareMic")],se.prototype,"shareMic",1);ne([y.trace("MediaNodeClient.pauseMic")],se.prototype,"pauseMic",1);ne([y.trace("MediaNodeClient.pauseWebcam")],se.prototype,"pauseWebcam",1);ne([y.trace("MediaNodeClient.resumeMic")],se.prototype,"resumeMic",1);ne([y.trace("MediaNodeClient.resumeWebcam")],se.prototype,"resumeWebcam",1);ne([y.trace("MediaNodeClient.disableWebcam")],se.prototype,"disableWebcam",1);ne([y.trace("MediaNodeClient.disableMic")],se.prototype,"disableMic",1);ne([y.trace("MediaNodeClient.disableScreenShare")],se.prototype,"disableScreenShare",1);ne([y.trace("MediaNodeClient.muteSelf")],se.prototype,"muteSelf",1);ne([y.trace("MediaNodeClient.resetVideoProducers")],se.prototype,"resetVideoProducers",1);ne([y.trace("MediaNodeClient.changeDisplayName")],se.prototype,"changeDisplayName",1);ne([y.trace("MediaNodeClient.kickPeer")],se.prototype,"kick",1);ne([y.trace("MediaNodeClient.kickAllPeers")],se.prototype,"kickAll",1);ne([y.trace("MediaNodeClient.muteAll")],se.prototype,"muteAll",1);ne([y.trace("MediaNodeClient.muteAllVideo")],se.prototype,"muteAllVideo",1);ne([y.trace("MediaNodeClient.disableAudio")],se.prototype,"disableAudio",1);ne([y.trace("MediaNodeClient.disableVideo")],se.prototype,"disableVideo",1);ne([y.trace("MediaNodeClient.pinPeer")],se.prototype,"pinPeer",1);ne([y.trace("MediaNodeClient.validateScreenShare")],se.prototype,"validateScreenShare",1);function Yf(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new se(s,t);return s.setValue("roomNodeClient",r),r}function Qf(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var dD=Object.defineProperty,lD=Object.getOwnPropertyDescriptor,Zi=(s,t,e,r)=>{for(var i=r>1?void 0:r?lD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dD(t,e,i),i},$i,us,Q,St,Ut,ug;const Xf=(ug=class{constructor(s,t,e,r){g(this,St);h(this,"self");h(this,"authToken");g(this,$i,void 0);h(this,"viewType");g(this,us,void 0);g(this,Q,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,Q,s),this.viewType=r,this.authToken=a,m(this,$i,i),m(this,us,e),this.setupEvents()}get peerId(){return n(this,Q).getValue("peerId")}get telemetry(){return n(this,Q).getValue("telemetry")}get logger(){return n(this,Q).getValue("logger")}get mediaJoined(){return n(this,Q).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=ht(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Je.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const p=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),s.getValue("callstats").devices("AUDIO",p==null?void 0:p.filter(f=>f.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",p==null?void 0:p.filter(f=>f.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",p==null?void 0:p.filter(f=>f.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:ge.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:u_(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(f){l.error("Callstats:: initialization failed",{error:f})}},0):l.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new Xf(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===H.Allowed&&r)try{await n(this,St,Ut).shareMic(s),this.self.audioEnabled||n(this,St,Ut).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{await n(this,St,Ut).shareWebcam(t),this.self.videoEnabled||n(this,St,Ut).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&a)try{await((c=n(this,St,Ut))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){n(this,Q).getValue("callstats").callEnded(),n(this,St,Ut).reset(),s&&await this.joinRoom(s)}setupEvents(){n(this,Q).getValue("peerSessionStore").on(C.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),n(this,Q).getValue("peerSessionStore").on(C.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,Q).getValue("peerSessionStore").on(C.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,Q).getValue("peerSessionStore").on(C.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Q).getValue("peerSessionStore").on(C.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,Q).getValue("peerSessionStore").on(C.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&(t=nr.v4()),n(this,$i).updateURL(t),n(this,Q).getValue("telemetry").resetPeerId(t),ht().setHeader("tracing-id",t),Fr.remapContext(t,n(this,Q)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,Q).getValue("peerSessionStore").on(C.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,us).on(V.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,us).on(Fc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,Q).getValue("peerSessionStore").emit(C.UPDATE_PERMISSIONS,t.patch)})}),n(this,us).on(V.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,us).on(V.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,us).on(V.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,Q).getValue("peerSessionStore").onAsync(C.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,Q).getValue("peerSessionStore").on(C.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,Q).getValue("peerSessionStore").on(C.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,Q).getValue("callstats").audioOff())}),n(this,Q).getValue("peerSessionStore").on(C.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,Q).getValue("callstats").videoOff())}),n(this,Q).getValue("peerSessionStore").onAsync(C.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,Q).getValue("peerSessionStore").on(C.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await n(this,us).joinRoom(this.self);n(this,us).socket.flush();const e=ah(t.stageType);if(n(this,Q).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new R("Could not connect to the room.","0002")}try{await this.joinMediaRoom(s),n(this,Q).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),new R("Could not establish media connection.","0002")}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=n(this,Q).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,Q).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,Q).notify("stageStatus");try{(e=n(this,$i))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}Qf(n(this,Q)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,Q).getAllValues();try{if(e===rr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}Yf(n(this,Q),{socket:n(this,$i),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:p}=(o=await((a=n(this,St,Ut))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw p!=null?p:new Error("Could not connect to media server");i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=n(this,Q).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===rr.Webinar)&&n(this,St,Ut)&&(n(this,St,Ut).mediaJoined&&s!=="disconnected"&&await n(this,St,Ut).leaveRoom(),!(s==="stageLeft"&&t===rr.Livestream)&&(n(this,St,Ut).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},$i=new WeakMap,us=new WeakMap,Q=new WeakMap,St=new WeakSet,Ut=function(){return n(this,Q).getValue("roomNodeClient")},ug);let Kr=Xf;Zi([y.trace("SelfController.resetSelf")],Kr.prototype,"resetSelf",1);Zi([y.trace("SelfController.setupEvents")],Kr.prototype,"setupEvents",1);Zi([y.trace("SelfController.joinRoom")],Kr.prototype,"joinRoom",1);Zi([y.trace("SelfController.leaveRoom")],Kr.prototype,"leaveRoom",1);Zi([y.trace("SelfController.joinMediaRoom")],Kr.prototype,"joinMediaRoom",1);Zi([y.trace("SelfController.leaveMediaRoom")],Kr.prototype,"leaveMediaRoom",1);Zi([y.trace("SelfController.init")],Kr,"init",1);var lc;class uD{constructor(t){g(this,lc,void 0);m(this,lc,t)}on(t,e){let r;t===V.roomPeerCount?r=vp.fromBinary.bind(vp):r=Ip.fromBinary.bind(Ip),n(this,lc).on(t,({payload:i})=>{if(t===V.roomPeerCount&&!i)return;const a=r(i);e(a)})}}lc=new WeakMap;var uc,hc;class hD{constructor(t,e){g(this,uc,void 0);g(this,hc,void 0);m(this,uc,e),m(this,hc,t)}get logger(){return n(this,hc).getValue("logger")}on(t,e){let r,i;switch(t){case V.transcript:{r=Ul.fromBinary.bind(Ul),i=Ul.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,uc).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}uc=new WeakMap,hc=new WeakMap;var pD=Object.defineProperty,gD=Object.getOwnPropertyDescriptor,Sh=(s,t,e,r)=>{for(var i=r>1?void 0:r?gD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&pD(t,e,i),i},Zs,fa;class wl{constructor(t,e){g(this,Zs,void 0);g(this,fa,void 0);m(this,Zs,e),m(this,fa,t)}get logger(){return n(this,fa).getValue("logger")}get telemetry(){return n(this,fa).getValue("telemetry")}getPolls(){return n(this,Zs).sendMessagePromise(Ns.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,Zs).sendMessage(Ns.createPoll,bI.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,Zs).sendMessage(Ns.votePoll,CI.toBinary(r))}on(t,e){let r,i;switch(t){case Ns.updatePoll:case Ns.createPoll:case Ns.votePoll:{r=jl.fromBinary.bind(jl),i=jl.create();break}}n(this,Zs).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){n(this,Zs).removeListeners(t)}}Zs=new WeakMap,fa=new WeakMap;Sh([y.trace("PollSocketHandler.getPolls")],wl.prototype,"getPolls",1);Sh([y.trace("PollSocketHandler.createPoll")],wl.prototype,"createPoll",1);Sh([y.trace("PollSocketHandler.votePoll")],wl.prototype,"votePoll",1);var mD=Object.defineProperty,fD=Object.getOwnPropertyDescriptor,TD=(s,t,e,r)=>{for(var i=r>1?void 0:r?fD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mD(t,e,i),i},At;class Zf{constructor(t,e){h(this,"socket");g(this,At,void 0);m(this,At,t),this.socket=e,this.handleSocketEvents(),n(this,At).setValue("roomSocketHandler",this)}get telemetry(){return n(this,At).getValue("telemetry")}get logger(){return n(this,At).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(V.joinRoom,mR.toBinary(e));try{const{peer:a}=tn.fromBinary((await r).payload);n(this,At).getValue("connectionHandler").socketJoined=!0,n(this,At).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return n(this,At).getValue("peerSessionStore").emit(C.ROOM_STATE,d),n(this,At).getValue("peerSessionStore").emit(C.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),a}}async getAllAddedParticipants(){try{return ZR.fromBinary((await this.socket.sendMessagePromise(V.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const a={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(V.getRoomPeersInfo,nR.toBinary(a));i=$l.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(V.getRoomPeersInfo);t=$l.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(V.getRoomPeersInfo);t=$l.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(V.getPeerInfo,Bm.toBinary({peerId:t}));e=tn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=yp.create();try{const e=await this.socket.sendMessagePromise(V.getRoomInfo);t=yp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=_p.create();try{const e=await this.socket.sendMessagePromise(V.getRoomStageState);t=_p.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(V.broadcastMessage,qa.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(V.broadcastToEntity,qa.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(V.broadcastToEntity,qa.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(V.leaveRoom,TR.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(V.kick,Fm.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(V.kickAll,xm.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(V.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(V.acceptWaitingRoomRequests,nk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(V.denyWaitingRoomRequests,ok.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Fc.updateUserPreset,Vk.toBinary(r))}handleSocketEvents(){this.socket.on(V.broadcastMessage,({payload:t})=>{try{const e=qa.fromBinary(t);n(this,At).getValue("peerSessionStore").emit(C.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(V.broadcastToEntity,({payload:t})=>{try{const e=qa.fromBinary(t);n(this,At).getValue("peerSessionStore").emit(C.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case V.joinRoom:case V.leaveRoom:case V.kick:case V.kickAll:{r=tn.fromBinary.bind(tn),i=tn.create();break}case V.getWaitingRoomRequests:{r=(a,o)=>a?bp.fromBinary(a,o):{requests:[]},i=bp.create();break}case V.recordingPaused:case V.recordingStarted:case V.recordingStopped:{r=Op.fromBinary.bind(Op);break}case Fc.updateUserPreset:{r=Cp.fromBinary.bind(Cp);break}case gs.peerJoinedBroadcast:case yr.peerJoinedBroadcast:{r=gp.fromBinary.bind(gp);break}case gs.selfJoinComplete:case yr.selfJoinComplete:{r=su.fromBinary.bind(su);break}case gs.globalPeerPinBroadcast:case yr.globalPeerPinBroadcast:{r=Tp.fromBinary.bind(Tp);break}case gs.selectedPeer:case yr.selectedPeer:{r=tu.fromBinary.bind(tu);break}case gs.selectedPeerDiff:case yr.selectedPeerDiff:{r=pp.fromBinary.bind(pp);break}case gs.leaveRoom:case yr.leaveRoom:{r=ru.fromBinary.bind(ru);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Fc.getUserPresets,Mk.toBinary(e)),i=Ok.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}At=new WeakMap;TD([y.trace("RoomSocketHandler.joinRoom")],Zf.prototype,"joinRoom",1);var vt;class SD{constructor(t){g(this,vt,void 0);m(this,vt,t)}async getStageRequests(){const{payload:t}=await n(this,vt).sendMessagePromise(V.getStageRequests);return t?ql.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,vt).sendMessage(V.requestStageAccess)}cancelRequestAccess(){n(this,vt).sendMessage(V.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,vt).sendMessage(V.grantStageAccess,pI.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,vt).sendMessage(V.denyStageAccess,mI.toBinary(e))}joinStage(){return n(this,vt).sendMessagePromise(V.joinStage,void 0,void 0,V.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,vt).sendMessagePromise(V.leaveStage,Dp.toBinary(e),void 0,V.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,vt).sendMessagePromise(V.leaveStage,Dp.toBinary(e))}on(t,e){let r;switch(t){case V.grantStageAccess:case V.denyStageAccess:{r=void 0;break}case V.getStagePeers:{r=Ap.fromBinary.bind(Ap);break}case V.getStageRequests:case V.requestStageAccess:case V.cancelStageRequest:{r=ql.fromBinary.bind(ql);break}case V.peerStageStatusUpdate:{r=Sp.fromBinary.bind(Sp);break}}n(this,vt).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}async getPeerInfo(t){const e=await n(this,vt).sendMessagePromise(V.getPeerInfo,Bm.toBinary({peerId:t}));return tn.fromBinary(e.payload)}}vt=new WeakMap;var Ve,pc;class vD{constructor(t,e){g(this,Ve,void 0);g(this,pc,void 0);m(this,Ve,e),m(this,pc,t)}get logger(){return n(this,pc).getValue("logger")}addPlugin(t,e){n(this,Ve).sendMessage(F.addPlugin,IM.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,Ve).sendMessage(F.removePlugin,DM.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await n(this,Ve).sendMessagePromise(F.getPlugins);return t?tI.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,Ve).sendMessage(F.customPluginEventToRoom,FM.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,Ve).sendMessage(F.customPluginEventToPeers,jM.toBinary(a),i)}enablePluginForRoom(t,e){n(this,Ve).sendMessage(F.enablePluginForRoom,NM.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,Ve).sendMessage(F.enablePluginForPeers,UM.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,Ve).sendMessage(F.disablePluginForRoom,VM.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,Ve).sendMessage(F.disablePluginForPeers,BM.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,Ve).sendMessage(F.storeInsertKeys,wp.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Ve).sendMessage(F.storeGetKeys,KM.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Ve).sendMessage(F.storeDeleteKeys,YM.toBinary(a),i)}storeDelete(t,e,r){n(this,Ve).sendMessage(F.storeDelete,XM.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};n(this,Ve).sendMessage(F.storeInsertKeys,wp.toBinary(i))}on(t,e){let r;switch(t){case F.addPlugin:case F.enablePluginForPeers:case F.enablePluginForRoom:{r=ou.fromBinary.bind(ou);break}case F.removePlugin:case F.disablePluginForPeers:case F.disablePluginForRoom:{r=Rp.fromBinary.bind(Rp);break}case F.customPluginEventToPeers:case F.customPluginEventToRoom:{r=Mp.fromBinary.bind(Mp);break}case F.storeInsertKeys:case F.storeGetKeys:case F.storeDeleteKeys:case F.storeDelete:{r=kp.fromBinary.bind(kp);break}}n(this,Ve).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Ve=new WeakMap,pc=new WeakMap;var yD=Object.defineProperty,ED=(s,t,e)=>t in s?yD(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,PD=(s,t,e)=>(ED(s,typeof t!="symbol"?t+"":t,e),e),vh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},I=(s,t,e)=>(vh(s,t,"read from private field"),e?e.call(s):t.get(s)),ue=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},te=(s,t,e,r)=>(vh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Te=(s,t,e)=>(vh(s,t,"access private method"),e),ld={},bD={get exports(){return ld},set exports(s){ld=s}},fn=typeof Reflect=="object"?Reflect:null,qp=fn&&typeof fn.apply=="function"?fn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},zc;fn&&typeof fn.ownKeys=="function"?zc=fn.ownKeys:Object.getOwnPropertySymbols?zc=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:zc=function(s){return Object.getOwnPropertyNames(s)};function _D(s){console&&console.warn&&console.warn(s)}var eT=Number.isNaN||function(s){return s!==s};function ie(){ie.init.call(this)}bD.exports=ie;ld.once=kD;ie.EventEmitter=ie;ie.prototype._events=void 0;ie.prototype._eventsCount=0;ie.prototype._maxListeners=void 0;var jp=10;function Rl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ie,"defaultMaxListeners",{enumerable:!0,get:function(){return jp},set:function(s){if(typeof s!="number"||s<0||eT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");jp=s}});ie.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ie.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||eT(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function tT(s){return s._maxListeners===void 0?ie.defaultMaxListeners:s._maxListeners}ie.prototype.getMaxListeners=function(){return tT(this)};ie.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")qp(c,this,t);else for(var d=c.length,l=aT(c,d),e=0;e<d;++e)qp(l[e],this,t);return!0};function sT(s,t,e,r){var i,a,o;if(Rl(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=tT(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,_D(c)}return s}ie.prototype.addListener=function(s,t){return sT(this,s,t,!1)};ie.prototype.on=ie.prototype.addListener;ie.prototype.prependListener=function(s,t){return sT(this,s,t,!0)};function CD(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function rT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=CD.bind(r);return i.listener=e,r.wrapFn=i,i}ie.prototype.once=function(s,t){return Rl(t),this.on(s,rT(this,s,t)),this};ie.prototype.prependOnceListener=function(s,t){return Rl(t),this.prependListener(s,rT(this,s,t)),this};ie.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Rl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():wD(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ie.prototype.off=ie.prototype.removeListener;ie.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function iT(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?RD(i):aT(i,i.length)}ie.prototype.listeners=function(s){return iT(this,s,!0)};ie.prototype.rawListeners=function(s){return iT(this,s,!1)};ie.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):nT.call(s,t)};ie.prototype.listenerCount=nT;function nT(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ie.prototype.eventNames=function(){return this._eventsCount>0?zc(this._events):[]};function aT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function wD(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function RD(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function kD(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}oT(s,t,a,{once:!0}),t!=="error"&&MD(s,i,{once:!0})})}function MD(s,t,e){typeof s.on=="function"&&oT(s,"error",t,e)}function oT(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class ID extends S.MessageType{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const Gp=new ID;class cT{static encode(t){return Gp.toBinary(t)}static decode(t){return Gp.fromBinary(new Uint8Array(t))}}function AD(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Sr;class DD{constructor(t={}){PD(this,"opts"),ue(this,Sr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},te(this,Sr,0)}async wait(){te(this,Sr,I(this,Sr)+1);const t=AD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**I(this,Sr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return I(this,Sr)}reset(){te(this,Sr,0)}}Sr=new WeakMap;const gr={debug:0,info:1,warn:2,error:3};var Zr,ei;class OD{constructor(t){ue(this,Zr,void 0),ue(this,ei,void 0),te(this,Zr,console),te(this,ei,t)}debug(...t){gr[I(this,ei)]>gr.debug||I(this,Zr).debug("[Sockrates]:",...t)}info(...t){gr[I(this,ei)]>gr.info||I(this,Zr).info("[Sockrates]:",...t)}warn(...t){gr[I(this,ei)]>gr.warn||I(this,Zr).warn("[Sockrates]:",...t)}error(...t){gr[I(this,ei)]>gr.error||I(this,Zr).error("[Sockrates]:",...t)}}Zr=new WeakMap,ei=new WeakMap;var dT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(dT||{});const ND="2",LD="3";var Ce,an,fe,Ae,vr,We,tr,Br,ps,on,Os,Du,lT,Za,Yc,Ou,uT,Nu,Wp,ud,Lu,Vu,hT,ro,Qc,io,hd,pd,xu,Tn,no,ao,gd;class VD{constructor(t,e){var f,T,E,b,_,M,A,x,N,$;ue(this,Du),ue(this,Za),ue(this,Ou),ue(this,Nu),ue(this,ud),ue(this,Vu),ue(this,ro),ue(this,io),ue(this,pd),ue(this,Tn),ue(this,ao),ue(this,Ce,void 0),ue(this,an,void 0),ue(this,fe,void 0),ue(this,Ae,void 0),ue(this,vr,void 0),ue(this,We,void 0),ue(this,tr,void 0),ue(this,Br,void 0),ue(this,ps,void 0),ue(this,on,void 0),ue(this,Os,void 0);var r,i,a,o,c,d,l,u,p;te(this,an,t),te(this,vr,[]),te(this,We,new ld),te(this,tr,!0),te(this,ps,!1),te(this,fe,e!=null?e:{}),(f=(r=I(this,fe)).autoReconnect)!=null||(r.autoReconnect=!0),(T=(i=I(this,fe)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(a=I(this,fe)).pingTimeout)!=null||(a.pingTimeout=3e4),(b=(o=I(this,fe)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(_=(c=I(this,fe)).debug)!=null||(c.debug=!0),(M=(d=I(this,fe)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(A=(l=I(this,fe)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(x=(u=I(this,fe)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(N=(p=I(this,fe)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),te(this,Br,{code:void 0,reason:void 0}),te(this,Ae,($=I(this,fe).logger)!=null?$:new OD(I(this,fe).debug?"debug":"info")),te(this,Os,new DD)}get readyState(){var t;return(t=I(this,Ce))==null?void 0:t.readyState}get url(){return I(this,an)}updateURL(t){te(this,an,t),Te(this,Vu,hT).call(this)}get config(){return I(this,fe)}get sendQueue(){return I(this,vr)}flush(){if(!I(this,fe).queueOnDisconnect)return!1;const t=[];return I(this,vr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),te(this,vr,t),I(this,vr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){I(this,Ae).debug("Websocket was already connecting or connected.");return}if(I(this,tr)!==!1)return new Promise((e,r)=>{Te(this,Tn,no).call(this),Te(this,ao,gd).call(this);try{te(this,Ce,new WebSocket(Te(this,Du,lT).call(this,I(this,an)))),I(this,Ce).binaryType="arraybuffer",I(this,Ae).debug("Connecting");const i=setTimeout(()=>{I(this,Ae).debug("Connection timeout. Closing socket"),te(this,tr,!0),Te(this,ao,gd).call(this),I(this,Ce).close(3001,"Connection Timeout"),I(this,fe).autoReconnect&&!I(this,ps)&&(I(this,We).emit("reconnecting"),Te(this,ro,Qc).call(this)),r(new Error("Connection timed out!"))},I(this,fe).connectionTimeout);I(this,Ce).onopen=()=>{I(this,Ae).debug(`Ready State: ${dT[I(this,Ce).readyState]}`),i&&clearTimeout(i),Te(this,pd,xu).call(this),te(this,Br,{code:void 0,reason:void 0}),I(this,We).emit("connected"),I(this,fe).flushOnReconnect&&this.flush(),e()},I(this,Ce).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),I(this,Ae).debug("Socket closed. Close event:",{event:a}),I(this,Ae).debug(`Connection closed code: ${o}`),I(this,Ae).debug(`Connection closed reason: ${c}`),I(this,ps)||Te(this,ud,Lu).call(this,o,c)}catch(o){Te(this,Za,Yc).call(this,o)}},I(this,Ce).onerror=a=>{Te(this,Za,Yc).call(this,a)},I(this,Ce).onmessage=a=>Te(this,Ou,uT).call(this,a)}catch(i){Te(this,Za,Yc).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(I(this,fe).queueOnDisconnect&&(!I(this,Ce)||I(this,Ce).readyState!==1))return I(this,Ae).debug("Queuing message since socket is not connected!",a),I(this,vr).push(a),!1;const o=cT.encode(a);return Te(this,io,hd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Te(this,io,hd).call(this,t)}receive(t,e){return I(this,We).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){I(this,We).on(t,e);return}this.receive(t,e)}removeAllListeners(){I(this,We).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){I(this,We).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){I(this,We).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){te(this,tr,!1),Te(this,Tn,no).call(this),this.removeAllListeners(),te(this,Br,{code:1e3,reason:"Sockrates disconnect method called"}),I(this,Ce).close(1e3,"Sockrates disconnect method called.")}}Ce=new WeakMap,an=new WeakMap,fe=new WeakMap,Ae=new WeakMap,vr=new WeakMap,We=new WeakMap,tr=new WeakMap,Br=new WeakMap,ps=new WeakMap,on=new WeakMap,Os=new WeakMap,Du=new WeakSet,lT=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Za=new WeakSet,Yc=function(s,t){I(this,Ae).error("Error:",{error:s}),I(this,We).emit("errored",{error:s}),t==null||t(s)},Ou=new WeakSet,uT=function(s){if(Te(this,pd,xu).call(this),s.data===ND){I(this,Ae).debug("Received ping from server"),Te(this,io,hd).call(this,LD);return}const t=cT.decode(s.data),{id:e,payload:r}=t;I(this,Ae).debug("Received message",{event:t.event,messageID:e}),I(this,We).emit(t.event.toString(),{id:e,payload:r})},Nu=new WeakSet,Wp=function(){return I(this,Ce).readyState===1},ud=new WeakSet,Lu=function(s,t){te(this,Br,{reason:t,code:s}),I(this,We).emit("disconnected",{code:s,reason:t})},Vu=new WeakSet,hT=function(){const{reason:s,code:t}=I(this,Br);t&&t!==1e3&&I(this,tr)&&I(this,fe).autoReconnect&&!I(this,ps)&&(I(this,Ae).debug(`Triggering reconnection due to ${s}.`),I(this,We).emit("reconnecting"),Te(this,ro,Qc).call(this))},ro=new WeakSet,Qc=async function(s=!0){if(s&&I(this,ps)){I(this,Ae).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(I(this,ps)||I(this,Os).reset(),I(this,fe).maxReconnectionAttempts!==null&&I(this,Os).getAttempts()>=I(this,fe).maxReconnectionAttempts){I(this,We).emit("failed"),te(this,ps,!1);return}te(this,ps,!0),Te(this,ao,gd).call(this),Te(this,Tn,no).call(this);try{if(await I(this,Os).wait(),I(this,tr)===!1)return;if(I(this,Ae).debug(`Reconnection attempt ${I(this,Os).getAttempts()}`),I(this,We).emit("reconnectAttempt",{attempt:I(this,Os).getAttempts()}),await this.connect(),!Te(this,Nu,Wp).call(this))throw Error("Reconnect Failed");te(this,ps,!1),te(this,Br,{code:void 0,reason:void 0}),I(this,We).emit("reconnected")}catch(t){I(this,Ae).debug("Failed to reconnect."),I(this,We).emit("reconnectFailure",{attempt:I(this,Os).getAttempts()}),Te(this,ro,Qc).call(this,!1)}},io=new WeakSet,hd=function(s){try{return I(this,Ce).send(s),!0}catch(t){return I(this,Ae).error(t.message),!1}},pd=new WeakSet,xu=function(){this.config.disconnectOnPingTimeout&&(I(this,Ae).debug("Resetting ping timeout"),Te(this,Tn,no).call(this),te(this,on,setTimeout(()=>{var s;I(this,Ae).debug("Disconnecting the socket due to ping timeout"),te(this,tr,!0);const t=3002,e="Ping timeout";(s=I(this,Ce))==null||s.close(t,e),Te(this,ud,Lu).call(this,t,e)},I(this,fe).pingTimeout)))},Tn=new WeakSet,no=function(){I(this,on)&&(clearTimeout(I(this,on)),te(this,on,void 0))},ao=new WeakSet,gd=function(){I(this,Ce)&&(I(this,Ce).onopen=void 0,I(this,Ce).onerror=void 0,I(this,Ce).onmessage=void 0,I(this,Ce).onclose=void 0)};var xD=Object.defineProperty,UD=Object.getOwnPropertyDescriptor,kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?UD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xD(t,e,i),i};const Jp=65535,$D=3e3;var xr,ve,ye,Re,Yt,Ge,gc,Uu,mc,$u,hg;const pT=(hg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,ye);g(this,gc);g(this,mc);g(this,xr,void 0);g(this,ve,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");g(this,Yt,void 0);g(this,Ge,void 0);var a;if(!t||!e||!r)throw new R("peerId, meetingId, or authToken can not be empty","0404");m(this,Yt,void 0),m(this,Ge,s),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,xr,L(this,gc,Uu).call(this,t)),m(this,ve,new VD(n(this,xr),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,ye,Re).socketJoinAttempted}set joinAttempted(s){n(this,ye,Re).socketJoinAttempted=s}get telemetry(){return n(this,Ge).getValue("telemetry")}get logger(){return n(this,Ge).getValue("logger")}get peerId(){return n(this,Ge).getValue("peerId")}updateURL(s){s!==this.peerId&&(m(this,xr,L(this,gc,Uu).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,ve).updateURL(n(this,xr))}static getSocketEdgeDomain(s){return gn({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,xr)}async connect(){n(this,ye,Re).socketJoinAttempted=!0,await n(this,ve).connect(),n(this,ye,Re).socketJoinAttempted=!0,n(this,ye,Re).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){n(this,ye,Re).socketJoinAttempted=!1,n(this,ve).disconnect(),n(this,ye,Re).socketJoinAttempted=!0,n(this,ye,Re).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,ve).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return n(this,Ge).getValue("telemetry").injectContext(r),n(this,ve).send(s,e!=null?e:L(this,mc,$u).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const a=i!=null?i:s;return new Promise((o,c)=>{const d=(E,b)=>{n(this,ve).removeListener(a,E),n(this,ve).removeListener(Jp,b),n(this,ve).removeListener(yr.errorResponse,b),n(this,ve).removeListener(gs.errorResponse,b)},l=r!=null?r:L(this,mc,$u).call(this),u={};n(this,Ge).getValue("telemetry").injectContext(u);const f=({id:E,payload:b})=>{if(l===E){let _;try{const M=QC.fromBinary(b);_=new Error(M.errorMessage)}catch(M){_=new Error("failed to parse error message",{cause:M});try{const A=Xw.fromBinary(b);_=new Error(A.message)}catch(A){_=new Error("failed to parse error message",{cause:A})}}c(_),d(T,f)}},T=({id:E,payload:b})=>{l===E&&(o({id:E,payload:b}),d(T,f))};n(this,ve).on(a,T),n(this,ve).on(Jp,f),n(this,ve).on(yr.errorResponse,f),n(this,ve).on(gs.errorResponse,f),setTimeout(()=>{d(T,f),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,ve).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){n(this,ve).on(s,t)}onStateEvent(s,t){n(this,ve).on(s,t)}removeListener(s,t){n(this,ve).removeListener(s,t)}removeListeners(s){n(this,ve).removeListeners(s)}flush(){return n(this,ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),n(this,Yt)&&(clearTimeout(n(this,Yt)),m(this,Yt,void 0)),n(this,ye,Re).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{recv:e,send:r}=(i=n(this,ye,Re).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==mn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==mn.CONNECTED?n(this,Ge).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,ye,Re).joinAttempted}):m(this,Yt,setTimeout(()=>{n(this,Ge).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,ye,Re).joinAttempted}),m(this,Yt,void 0)},$D)),n(this,ye,Re).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),n(this,ye,Re).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),n(this,ye,Re).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,ye,Re).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,ye,Re).mediaJoinAttempted}}),n(this,Yt)&&(clearTimeout(n(this,Yt)),m(this,Yt,void 0)),n(this,Ge).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,ye,Re).mediaJoinAttempted}),n(this,ye,Re).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),n(this,Ge).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_FAILED),n(this,ye,Re).updateSocketConnectionState("failed")})}},xr=new WeakMap,ve=new WeakMap,ye=new WeakSet,Re=function(){return n(this,Ge).getValue("connectionHandler")},Yt=new WeakMap,Ge=new WeakMap,gc=new WeakSet,Uu=function(s){const t=n(this,Ge).getValue("socketBaseURI")||n(this,Ge).getValue("baseURI");let e=pT.getSocketEdgeDomain(t);typeof ya(n(this,Ge),"socket_server_base")=="string"&&(e=ya(n(this,Ge),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),a=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...a!==s&&{oldPeerID:a},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>id[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},mc=new WeakSet,$u=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},hg);let Rc=pT;kl([y.trace("SocketService.connect")],Rc.prototype,"connect",1);kl([y.trace("SocketService.disconnect")],Rc.prototype,"disconnect",1);kl([y.trace("SocketService.sendMessagePromise")],Rc.prototype,"sendMessagePromise",1);kl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Rc.prototype,"sendMessagePromiseWithTimeout",1);class BD{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=CR.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(a=e.parentMeeting.participants)!=null?a:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=QR.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Hm.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Pp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return HR.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(V.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(V.createConnectedRooms,MR.toBinary({payloads:t}));return Pp.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(V.deleteConnectedRooms,$R.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(V.movePeers,JR.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}}}var HD=Object.defineProperty,FD=Object.getOwnPropertyDescriptor,qD=(s,t,e,r)=>{for(var i=r>1?void 0:r?FD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&HD(t,e,i),i},hs;class gT extends Lt{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);g(this,hs,void 0);m(this,hs,e)}get supportsConnectedMeetings(){return n(this,hs).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
10
|
-
Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await n(this,hs).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await n(this,hs).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await n(this,hs).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await n(this,hs).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,hs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,hs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),a}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>a.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}hs=new WeakMap;
|
|
11
|
-
Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:n(this,ce).getValue("self").videoEnabled,audio:n(this,ce).getValue("self").audioEnabled};try{n(this,ce).getValue("self").cleanupEvents(),await n(this,ce).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,ce).getValue("meeting"))==null?void 0:i.meta)==null?void 0:a.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await TT.init({...n(this,ce).getValue("options"),cachedUserDetails:null,defaults:{...n(this,ce).getValue("options").defaults,...e,mediaHandler:n(this,ce).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=n(this,ce).getValue("self");r.self.setName(n(this,ce).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=n(this,ce).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return n(this,ce).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,ce).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,ce).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},ce=new WeakMap,pg);let Ml=mT;yh([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Ml.prototype,"getConnectedMeetings",1);yh([y.trace("ConnectedMeetingsController.setupEvents")],Ml.prototype,"setupEvents",1);yh([y.trace("ConnectedMeetingsController.switchMeeting")],Ml.prototype,"switchMeeting",1);var WD=Object.defineProperty,JD=Object.getOwnPropertyDescriptor,Eh=(s,t,e,r)=>{for(var i=r>1?void 0:r?JD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&WD(t,e,i),i};const eo=class{constructor(s,t,e){h(this,"apiBase");h(this,"selfController");h(this,"pollController");h(this,"chatController");h(this,"metaController");h(this,"storesManager");h(this,"stageController");h(this,"pluginController");h(this,"internalsController");h(this,"recordingController");h(this,"livestreamController");h(this,"participantController");h(this,"connectedMeetingsController");h(this,"telemetry");h(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var N,$,K;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(Qf(s),ge.isSupported()===!1)throw new R("Browser not supported","0010",c,!0);const d=eA(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(a),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new LA(s);s.setValue("connectionHandler",l);let u="",p="",f=null;c.info("CF SFU is being used.");try{f=await d.getUserDetails(),u=((N=f.meeting)==null?void 0:N.title)||"",p=(($=f.socket)==null?void 0:$.baseUri)||s.getValue("baseURI"),s.setValue("presetName",f.preset.name),s.setValue("socketBaseURI",p),c.info(`Socket Base URI ${p} is being used`)}catch(Z){throw c.error("Failed to get user details",{error:Z}),new R("SDK initialization failed: /participant-details API request failed","0001")}const T=eo.createSocketService(s),E=T.connect(),b=d.getPlugins();try{await E}catch(Z){c.error("[Controller]: Failed to connect to socket server:",{error:Z})}const _=fu.init(f.preset,!s.getValue("modules").theme);s.setValue("theme",_);const M=yu.init(s,_.viewType,f.preset.permissions),A=eo.setupControllers(T,s,f,b,u,_,M);_A(_)&&((K=eo.createRoomNodeClient(s,T).initializeConnection(f.participant.name,i,!1,M))==null||K.catch(Ue=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Ue})}));const{controllers:x}=await A;return D_(),new eo(e,x,s)}static async setupControllers(s,t,e,r,i,a,o){var O,w,De;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:p,mediaConstraints:{audio:f}}=a;t.setValue("viewType",p),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(O=f.enableHighBitrate)!=null?O:!1,enableStereo:(w=f.enableStereo)!=null?w:!1}},...l}),t.setValue("maxPreferredStreams",ge.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let T,E,b,_,M,A,x,N,$;const K=new hD(t,s),Z=new BD(s);t.setValue("connectedMeetingsSocketHandler",Z);const Ue=new wl(t,s),es=new ur(t,s),zr=new SD(s),ts=new Zf(t,s),k=new vD(t,s),v=new uD(s),P=await Kr.init(t,ts,d,o,a);t.setValue("selfController",P);const U=await sf.init(t,P.self,ts,K,i);if(c.participant&&(N=new pr(t,P.self,ts)),(De=c.e2ee)!=null&&De.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(E=await Xt.init(t,es,P.self,N.participants)),c.internals&&(M=await ch.init(t)),c.livestream&&a.viewType===rr.Livestream&&(x=new hf(t,P.self,v)),c.poll&&(T=await Xm.init(t,P.self,Ue)),c.recording&&(A=new of(t,P.self,ts)),c.stage&&(b=new rf(t,zr,ts,P.self,N.participants)),c.plugin){if(!N)throw new R("The plugin module cannot be initialized without the `participant` module","0102");const Ds=await r;_=await bc.init(t,Ds,k,es,E==null?void 0:E.chat,P.self,N.participants,i)}if(c.connectedMeetings&&($=await Ml.init(t)),c.pip){const Ds=await eu._init(t,P.self);t.setValue("pip",Ds)}const we={storesManager:new R0(t,k),pollController:T,selfController:P,metaController:U,chatController:E,stageController:b,pluginController:_,recordingController:A,internalsController:M,livestreamController:x,participantController:N,connectedMeetingsController:$};return{theme:a,permissions:o,controllers:we}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return Yf(s,{socket:t,peerId:e})}static createSocketService(s){var d;const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),o=((d=s.getValue("socketBaseURI"))!=null?d:"").includes("realtime.cloudflare.com")?[]:["PING"];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(o)}`),new Rc(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let Il=eo;Eh([y.trace("Controller.init")],Il,"init",1);Eh([y.trace("Controller.createRoomNodeClient")],Il,"createRoomNodeClient",1);Eh([y.trace("Controller.createSocketService")],Il,"createSocketService",1);class KD{constructor(){h(this,"battery");h(this,"logger");h(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});h(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});h(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});h(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const Kp=new KD;function zD(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let a=ri.baseURI.prod;t&&(a=t);const o=`https://${gn({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new R("Invalid auth token","0004")}}var Ur,Bi,Hi,fc,ol,fT;class YD{constructor(){g(this,ol);g(this,Ur,new Audio);g(this,Bi,new MediaStream);g(this,Hi,new Map);g(this,fc,void 0);n(this,Ur).srcObject=n(this,Bi),n(this,Ur).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,Hi).has(e.id)||(n(this,Bi).addTrack(e),n(this,Hi).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,Ur).setSinkId(t)}removeTrack(t){const e=n(this,Hi).get(t);e&&(n(this,Bi).removeTrack(e),n(this,Hi).delete(t))}async play(){return n(this,Ur).srcObject=n(this,Bi),n(this,Ur).play().catch(t=>{L(this,ol,fT).call(this,t)})}onError(t){m(this,fc,t)}}Ur=new WeakMap,Bi=new WeakMap,Hi=new WeakMap,fc=new WeakMap,ol=new WeakSet,fT=function(t){var e;(e=n(this,fc))==null||e.call(this,t)};var Fi;class QD extends YD{constructor(){super();g(this,Fi,void 0);m(this,Fi,new Map)}addParticipantTrack(e,r){n(this,Fi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,Fi).get(e);r&&this.removeTrack(r),n(this,Fi).delete(e)}}Fi=new WeakMap;var XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,Al=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&XD(t,e,i),i},xe,qi,gg;let jr=(gg=class{constructor(t,e){g(this,xe,void 0);g(this,qi,void 0);m(this,qi,t),m(this,xe,e)}get peerId(){return n(this,qi).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:nr.v4(),a=Fr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new yf(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,T,E,b,_,M,A,x,N;ge.init();const e=(T=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?T:nr.v4(),{authToken:r,baseURI:i}=t,{meetingId:a,...o}=zD(r,i);if((E=o.baseURI)!=null&&E.includes("dyte.io"))throw new R("Dyte Base URIs are no longer supported. Please use RealtimeKit Base URIs. Eg: realtime.cloudflare.com","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=jr.setupContext(e,t,a,o),d=c.getValue("telemetry"),l=c.getValue("logger");_T(l),Kp.init(l),d.init(c,{roomName:a,userId:o.participantId,organizationId:o.orgId,peerId:e},(_=(b=t.modules)==null?void 0:b.tracing)!=null?_:!0,(A=(M=t==null?void 0:t.modules)==null?void 0:M.devTools)==null?void 0:A.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(x=t.authToken)==null?void 0:x.slice(0,10)}...
|
|
12
|
-
${(N=t.authToken)==null?void 0:N.slice(-10)}`}});const u=await Il.init(c),p=new
|
|
4
|
+
`)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,i;if(t.forEach(a=>{a.type==="candidate-pair"&&a.nominated===!0&&a.bytesSent>0&&(r=a)}),e.forEach(a=>{a.type==="candidate-pair"&&a.nominated===!0&&a.bytesReceived>0&&(i=a)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const a=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:a,backendRTT:a}}catch(a){return}}close(){this.pc1.close(),this.pc2.close()}}class Gg extends st{constructor(e){super();h(this,"call");h(this,"timeOut");this.call=new ar(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const zT=8,YT=1/1e3;class QT extends Gg{constructor(e){super(e);h(this,"senderChannel");h(this,"recieveChannel");h(this,"startTime");h(this,"lastBitrateMeasureTime");h(this,"sentPayloadBytes",0);h(this,"recievedPayloadBytes",0);h(this,"lastReceivedPayloadBytes",0);h(this,"stopSending",!1);h(this,"testProgress",0);h(this,"samplePacket","");h(this,"finalBitrateSum",0);h(this,"bitRateSampels",0);h(this,"maxNumberOfPacketsToSend",0);h(this,"bytesToKeepBuffered",0);h(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(ar.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<1024*256;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(a){}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,i=r.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const o=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*zT/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const a=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(a*YT)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:i})=>super.testComplete({RTT:r,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Fu extends Gg{constructor(e,r=ar.noFilter){super(e);h(this,"ch1");h(this,"ch2");this.call.setIceCandidateFilter(r);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class XT extends Fu{constructor(t){super(t,ar.isHost)}}class ZT extends Fu{constructor(t){super(t,ar.isRelay)}}class eS extends Fu{constructor(t){super(t,ar.isReflexive)}}class tS{constructor(){h(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,a,o;if(!this.ipInformation){try{const c=`https://${e.location}`,l=await(await fetch(c)).json();if(((i=l.loc)==null?void 0:i.length)>5)return this.ipInformation=l,(a=this.ipInformation)!=null&&a.ip&&(this.ipInformation.ip=Fr(this.ipInformation.ip)),l;throw Error("Insufficient data")}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using location service",{error:c})}try{const c=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await c.json(),(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=Fr(this.ipInformation.ip))}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:c})}}return this.ipInformation}resetCache(){this.ipInformation=null}}const Wg=new tS,kh=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function Mh(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class Jg{constructor(){h(this,"transport");h(this,"candidatePair");h(this,"outboundVideoRtp",new Map);h(this,"inboundVideoRtp",new Map);h(this,"outboundAudioRtp",new Map);h(this,"inboundAudioRtp",new Map);h(this,"remoteInboundRtp",new Map);h(this,"producerStreamMap",new Map);h(this,"consumerStreamMap",new Map);h(this,"staleProducerStreamMap",!1);h(this,"staleConsumerStreamMap",!1)}}class Kg extends st{constructor(){super();h(this,"observer");h(this,"outboundProducerMap",new Map);h(this,"inboundConsumerMap",new Map);h(this,"consumerPeerIdMap",new Map);h(this,"pausedConsumerMap",new Map);h(this,"pausedProducerMap",new Map);h(this,"overallProducingTransportsStatsMap",{});h(this,"overallConsumingTransportsStatsMap",{});h(this,"overallConsumersStatsMap",{});h(this,"overallProducersStatsMap",{});h(this,"videoProducerToStatsMap",new Map);h(this,"audioProducerToStatsMap",new Map);h(this,"videoConsumerToStatsMap",new Map);h(this,"audioConsumerToStatsMap",new Map);h(this,"consumerIdsWithFreezedVideo",new Set);h(this,"consumerIdsWithFreezedAudio",new Set);h(this,"producerIdsWithFreezedVideo",new Set);h(this,"producerIdsWithFreezedAudio",new Set);h(this,"freezedProducingTransportIds",new Set);h(this,"freezedConsumingTransportIds",new Set);h(this,"screenShareProducers",new Set);h(this,"screenShareConsumers",new Set);h(this,"ipDetails");h(this,"callStatsInstance");this.observer=new st}async registerProducer(e){await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,i){var o,c;const a=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,i){var o,c;const a=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,i){var o;const a=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,i){var o;const a=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,i){var u;const a=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=a,l=o||c||d;r.totalPacketsSent===i.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=i.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,i){var c,d;const o=!!Array.from(((d=(c=this==null?void 0:this.callStatsInstance)==null?void 0:c.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((l,u)=>l||u.audio||u.video||u.screen,!1);r.totalPacketsReceived===i.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=i.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const i=await e.getStats(),a=r?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"outbound-rtp":{this.outboundProducerMap.set(o.id,e.id);break}}return a}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),a=r?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"inbound-rtp":{this.inboundConsumerMap.set(o.id,e.id);break}}return a}deregisterProducer(e){this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(i=>{const a=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return a&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,a=void 0,o=void 0){var b,_,k,A,x,N,$,K,Y,Ue,es,Yr,ts;const c=e,d=new Jg,l=r.length?new Set(r):void 0,u=[],p=[],f=[],T=new Map,E=new Map;for(const M of c.values()){if(l){if(l.size===0)break;if(l.has(M.type))i&&l.delete(M.type);else continue}switch(M.type){case"local-candidate":{u.push(this.getIceCandidateStats(M));break}case"remote-candidate":{p.push(this.getIceCandidateStats(M));break}case"candidate-pair":{const{nominated:v}=M,{selected:P}=M,U=M,me={nominated:v!=null?v:P,currentRoundTripTime:U.currentRoundTripTime,totalRoundTripTime:U.totalRoundTripTime,bytesReceived:U.bytesReceived,bytesSent:U.bytesSent,availableOutgoingBitrate:U.availableOutgoingBitrate,availableIncomingBitrate:U.availableIncomingBitrate,lastPacketReceivedTimestamp:U.lastPacketReceivedTimestamp,lastPacketSentTimestamp:U.lastPacketSentTimestamp,localCandidateId:U.localCandidateId,remoteCandidateId:U.remoteCandidateId,bytesDiscardedOnSend:U.bytesDiscardedOnSend,packetsSent:U.packetsSent,packetsReceived:U.packetsReceived,packetsDiscardedOnSend:U.packetsDiscardedOnSend};f.push(me),(M.nominated===!0||M.selected===!0)&&(d.candidatePair=me);break}case"transport":{const v=M;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:v.bytesReceived,bytesSent:v.bytesSent,packetsSent:v.packetsSent,packetsReceived:v.packetsReceived,dtlsCipher:v.dtlsCipher,dtlsState:v.dtlsState,iceRole:v.iceRole};if(d.transport=P,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,P)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,P)}}break}case"remote-inbound-rtp":{const v=M,P={jitter:v.jitter,fractionLost:v.fractionLost,roundTripTime:v.roundTripTime,roundTripTimeMeasurements:v.roundTripTimeMeasurements,totalRoundTripTime:v.totalRoundTripTime,packetsLost:v.packetsLost};d.remoteInboundRtp.set(v.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(M.id))break;const v=M,P=a||this.outboundProducerMap.get(M.id),U=this.pausedProducerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const me=this.overallProducersStatsMap[P];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.outboundProducerMap.has(M.id)){d.staleProducerStreamMap=!0;break}const Ce=this.callStatsInstance.producers.get(P);if(((b=Ce==null?void 0:Ce.track)==null?void 0:b.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const O={bytesSent:v.bytesSent,packetsSent:v.packetsSent,nackCount:v.nackCount,ssrc:v.ssrc,mid:v.mid,active:v.active,codecId:v.codecId,headerBytesSent:v.headerBytesSent||0,totalPacketSendDelay:v.totalPacketSendDelay||0};if(v.mediaType==="video"||v.kind==="video"){const R=v,De={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped,framesPerSecond:R.framesPerSecond,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.targetBitrate,totalPacketSendDelay:R.totalPacketSendDelay,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...O};d.outboundVideoRtp.set(M.id,De),d.producerStreamMap.get(P).outboundVideoRtpId.push(M.id),this.processOutboundProducerVideoStats(P,me,De)}else if(v.mediaType==="audio"||v.kind==="audio"){const R=v,De={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...O};d.outboundAudioRtp.set(M.id,De),d.producerStreamMap.get(P).outboundAudioRtpId.push(M.id),this.processOutboundProducerAudioStats(P,me,De)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(M.id))break;const v=M,P=a||this.inboundConsumerMap.get(M.id),U=this.pausedConsumerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(v.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const me=this.overallConsumersStatsMap[P];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.inboundConsumerMap.has(M.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Ce={bytesReceived:v.bytesReceived,packetsReceived:v.packetsReceived,packetsLost:v.packetsLost>=0?v.packetsLost:0,jitter:v.jitter,nackCount:v.nackCount,jitterBufferDelay:v.jitterBufferDelay,jitterBufferEmittedCount:v.jitterBufferEmittedCount,lastPacketReceivedTimestamp:v.lastPacketReceivedTimestamp,ssrc:v.ssrc,mid:v.mid,codecId:v.codecId,headerBytesReceived:v.headerBytesReceived||0,packetsDiscarded:v.packetsDiscarded||0,jitterBufferMinimumDelay:v.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:v.jitterBufferTargetDelay||0};if(v.mediaType==="video"||v.kind==="video"){const O=v,R={frameHeight:O.frameHeight,frameWidth:O.frameWidth,framesDecoded:O.framesDecoded,framesDropped:O.framesDropped,framesPerSecond:O.framesPerSecond,framesReceived:O.framesReceived,keyFramesDecoded:O.keyFramesDecoded,firCount:O.firCount,decoderImplementation:O.decoderImplementation,pliCount:O.pliCount,totalProcessingDelay:O.totalProcessingDelay,qpSum:O.qpSum||0,totalAssemblyTime:O.totalAssemblyTime||0,totalDecodeTime:O.totalDecodeTime||0,totalFreezesDuration:O.totalFreezesDuration||0,totalInterFrameDelay:O.totalInterFrameDelay||0,totalPausesDuration:O.totalPausesDuration||0,totalSquaredInterFrameDelay:O.totalSquaredInterFrameDelay||0,freezeCount:O.freezeCount||0,pauseCount:O.pauseCount||0,powerEfficientDecoder:O.powerEfficientDecoder,...Ce};R.score=jg({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((k=this.videoConsumerToStatsMap.get(P))==null?void 0:k.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((A=this.videoConsumerToStatsMap.get(P))==null?void 0:A.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:ed({packetsLost:(R.packetsLost||0)-(((x=this.videoConsumerToStatsMap.get(P))==null?void 0:x.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,R),d.inboundVideoRtp.set(M.id,R),d.consumerStreamMap.get(P).inboundVideoRtpId.push(M.id),this.processInboundConsumerVideoStats(P,me,R)}else if(v.mediaType==="audio"||v.kind==="audio"){const O=v,R={audioLevel:O.audioLevel,concealedSamples:O.concealedSamples,concealmentEvents:O.concealmentEvents,totalAudioEnergy:O.totalAudioEnergy,totalSamplesDuration:O.totalSamplesDuration,totalSamplesReceived:O.totalSamplesReceived,fecPacketsDiscarded:O.fecPacketsDiscarded||0,fecPacketsReceived:O.fecPacketsReceived||0,insertedSamplesForDeceleration:O.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:O.removedSamplesForAcceleration||0,silentConcealedSamples:O.silentConcealedSamples||0,playoutId:O.playoutId,...Ce};R.score=qg({concealmentEvents:(R.concealmentEvents||0)-(((K=this.audioConsumerToStatsMap.get(P))==null?void 0:K.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((Y=this.audioConsumerToStatsMap.get(P))==null?void 0:Y.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((Ue=this.audioConsumerToStatsMap.get(P))==null?void 0:Ue.packetsReceived)||0),jitter:R.jitter||0}),E.set(P,{score:+(R.score*10).toFixed(),packetsLostPercentage:ed({packetsLost:(R.packetsLost||0)-(((es=this.audioConsumerToStatsMap.get(P))==null?void 0:es.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((Yr=this.audioConsumerToStatsMap.get(P))==null?void 0:Yr.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((ts=this.audioConsumerToStatsMap.get(P))==null?void 0:ts.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,R),d.inboundAudioRtp.set(M.id,R),d.consumerStreamMap.get(P).inboundAudioRtpId.push(M.id),this.processInboundConsumerAudioStats(P,me,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}}}if(d.producerStreamMap.forEach((M,v)=>{var P,U,me,Ce,O,R,De,Ds,Ca,Ra,ka,Ma,Ia,Aa,Da,Oa,Na,La,Va,xa,Ua,$a,Ba;if(M.outboundVideoRtpId.length>0){const ae=[];M.outboundVideoRtpId.forEach(Dl=>{ae.push(d.outboundVideoRtp.get(Dl))});const Q=this.getWorkingSimulcastVideoStats(ae);Q.score=Hg({frameWidth:Q.frameWidth||0,framesPerSecond:Q.framesPerSecond||0,jitter:((P=Q.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsSent:(Q.packetsSent||0)-(((U=this.videoProducerToStatsMap.get(v))==null?void 0:U.packetsSent)||0),packetsLost:(((me=Q.remoteData)==null?void 0:me.packetsLost)||0)-(((O=(Ce=this.videoProducerToStatsMap.get(v))==null?void 0:Ce.remoteData)==null?void 0:O.packetsLost)||0),framesEncoded:(Q.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(v))==null?void 0:R.framesEncoded)||0)}),T.set(v,{score:+(Q.score*10).toFixed(),frameWidth:Q.frameWidth||0,frameHeight:Q.frameHeight||0,framesPerSecond:Q.framesPerSecond||0,jitter:((De=Q.remoteData)==null?void 0:De.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsLostPercentage:Zc({packetsSent:(Q.packetsSent||0)-(((Ds=this.videoProducerToStatsMap.get(v))==null?void 0:Ds.packetsSent)||0),packetsLost:(((Ca=Q.remoteData)==null?void 0:Ca.packetsLost)||0)-(((ka=(Ra=this.videoProducerToStatsMap.get(v))==null?void 0:Ra.remoteData)==null?void 0:ka.packetsLost)||0)}),bitrate:((Q.bytesSent||0)-(((Ma=this.videoProducerToStatsMap.get(v))==null?void 0:Ma.bytesSent)||0))*8/7,cpuLimitations:Q.qualityLimitationReason==="cpu",bandwidthLimitations:Q.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(v,Q)}else if(M.outboundAudioRtpId.length>0){const ae=d.outboundAudioRtp.get(M.outboundAudioRtpId[0]);ae.score=Bg({packetsSent:(ae.packetsSent||0)-(((Ia=this.audioProducerToStatsMap.get(v))==null?void 0:Ia.packetsSent)||0),packetsLost:(((Aa=ae.remoteData)==null?void 0:Aa.packetsLost)||0)-(((Oa=(Da=this.audioProducerToStatsMap.get(v))==null?void 0:Da.remoteData)==null?void 0:Oa.packetsLost)||0),jitter:((Na=ae.remoteData)==null?void 0:Na.jitter)||0}),T.set(v,{score:+(ae.score*10).toFixed(),bitrate:((ae.bytesSent||0)-(((La=this.audioProducerToStatsMap.get(v))==null?void 0:La.bytesSent)||0))*8/7,packetsLostPercentage:Zc({packetsSent:(ae.packetsSent||0)-(((Va=this.audioProducerToStatsMap.get(v))==null?void 0:Va.packetsSent)||0),packetsLost:(((xa=ae.remoteData)==null?void 0:xa.packetsLost)||0)-((($a=(Ua=this.audioProducerToStatsMap.get(v))==null?void 0:Ua.remoteData)==null?void 0:$a.packetsLost)||0)}),jitter:((Ba=ae.remoteData)==null?void 0:Ba.jitter)||0,isScreenShare:this.screenShareProducers.has(v)}),this.audioProducerToStatsMap.set(v,ae)}}),f.forEach(M=>{const v=u.find(U=>U.id===M.localCandidateId?(M.localCandidateId=U.id,U):null),P=p.find(U=>U.id===M.remoteCandidateId?(M.remoteCandidateId=U.id,U):null);v&&(M.localCandidateType=v.type,M.localCandidateAddress=Fr(v.address),M.localCandidatePort=v.port,M.localCandidateProtocol=v.protocol,M.localCandidateUrl=v.url,M.localCandidateNetworkType=v.networkType,M.localCandidateRelatedAddress=Fr(v.relatedAddress),M.localCandidateRelatedPort=v.relatedPort),P&&(M.remoteCandidateType=P.type,M.remoteCandidateAddress=Fr(P.address),M.remoteCandidatePort=P.port,M.remoteCandidateProtocol=P.protocol,M.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let M=0,v=0;d.remoteInboundRtp.forEach((P,U)=>{P.roundTripTime&&P.roundTripTime>M&&(M=P.roundTripTime,v=P.totalRoundTripTime)}),d.transport.roundTripTime=M,d.transport.totalRoundTripTime=v}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(M){}if(T.size>0)try{this.observer.emit("producer_score",T)}catch(M){}return d}async getProducersReport(e){const r=e.map(i=>this.generateProducerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(i=>this.generateConsumerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,i){const a=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=a,d=this.parseRTCReport(c,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,o);if(!d)return;const l={stats:d.transport,transportId:e.id,consuming:r,producing:i},u=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),p=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:u,consumerReport:p}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,a)=>{var o,c;r.push({producerId:a,videoStats:i.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:i.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((c=(o=this.callStatsInstance.producers)==null?void 0:o.get(a))==null?void 0:c.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,a)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(a);r.push({consumerId:a,peerId:o,producerId:c,appData:d,videoStats:i.inboundVideoRtpId.map(l=>e.inboundVideoRtp.get(l)),audioStats:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))})})}catch(i){console.error("getConsumersReport: ",i,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):r()}catch(i){r(i)}})}async getConnectivity(e){try{const r={iceServers:e||kh},i=new Promise((u,p)=>{try{const f=new XT(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),a=new Promise((u,p)=>{try{const f=new ZT(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),o=new Promise((u,p)=>{try{const f=new eS(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),[c,d,l]=await Promise.all([i,a,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((a,o)=>{try{const c={iceServers:e||kh},d=new QT(c);d.addListener("done",a),d.addListener("failed",o),d.start(1e4)}catch(c){o(c)}});return{throughput:i.throughput,fractionalLoss:0,RTT:i.RTT,jitter:0,backendRTT:i.backendRTT}}catch(r){return}}async getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Wg.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){return}}async getNetworkQuality(e){const[r,i]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}async getNetworkInfo(e,r=!1){var c,d;if(r){const l=await this.getIPDetails();return{ipDetails:l,effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,location:l!=null&&l.loc?Mh(l==null?void 0:l.loc):void 0}}const[i,a,o]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:o,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:o!=null&&o.loc?Mh(o==null?void 0:o.loc):void 0,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,throughput:a==null?void 0:a.throughput,fractionalLoss:a==null?void 0:a.fractionalLoss,RTT:a==null?void 0:a.RTT,jitter:a==null?void 0:a.jitter,backendRTT:a==null?void 0:a.backendRTT}}}class sS extends Kg{}class zg extends Kg{constructor(){super(...arguments);h(this,"producerMap",new Map);h(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),a=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...a.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(a,o,e.id):void 0;for(const d of i.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return c}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],i=!1,a=void 0,o=void 0){var b,_,k,A,x,N,$,K,Y,Ue,es,Yr,ts;const c=e,d=new Jg,l=r.length?new Set(r):void 0,u=[],p=[],f=[],T=new Map,E=new Map;for(const M of c.values()){if(l){if(l.size===0)break;if(l.has(M.type))i&&l.delete(M.type);else continue}switch(M.type){case"local-candidate":{u.push(this.getIceCandidateStats(M));break}case"remote-candidate":{p.push(this.getIceCandidateStats(M));break}case"candidate-pair":{const{nominated:v}=M,{selected:P}=M,U=M,me={nominated:v!=null?v:P,currentRoundTripTime:U.currentRoundTripTime,totalRoundTripTime:U.totalRoundTripTime,bytesReceived:U.bytesReceived,bytesSent:U.bytesSent,availableOutgoingBitrate:U.availableOutgoingBitrate,availableIncomingBitrate:U.availableIncomingBitrate,lastPacketReceivedTimestamp:U.lastPacketReceivedTimestamp,lastPacketSentTimestamp:U.lastPacketSentTimestamp,localCandidateId:U.localCandidateId,remoteCandidateId:U.remoteCandidateId,bytesDiscardedOnSend:U.bytesDiscardedOnSend,packetsSent:U.packetsSent,packetsReceived:U.packetsReceived,packetsDiscardedOnSend:U.packetsDiscardedOnSend};f.push(me),(M.nominated===!0||M.selected===!0)&&(d.candidatePair=me);break}case"transport":{const v=M;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:v.bytesReceived,bytesSent:v.bytesSent,packetsSent:v.packetsSent,packetsReceived:v.packetsReceived,dtlsCipher:v.dtlsCipher,dtlsState:v.dtlsState,iceRole:v.iceRole};if(d.transport=P,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,P)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,P)}}break}case"remote-inbound-rtp":{const v=M,P={jitter:v.jitter,fractionLost:v.fractionLost,roundTripTime:v.roundTripTime,roundTripTimeMeasurements:v.roundTripTimeMeasurements,totalRoundTripTime:v.totalRoundTripTime,packetsLost:v.packetsLost};d.remoteInboundRtp.set(v.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(M.id))break;const v=M,P=a||this.outboundProducerMap.get(M.id),U=this.pausedProducerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const me=this.overallProducersStatsMap[P];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.outboundProducerMap.has(M.id)){d.staleProducerStreamMap=!0;break}const Ce=this.callStatsInstance.producers.get(P);if(((b=Ce==null?void 0:Ce.track)==null?void 0:b.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const O={bytesSent:v.bytesSent,packetsSent:v.packetsSent,nackCount:v.nackCount,ssrc:v.ssrc,mid:v.mid,active:v.active,codecId:v.codecId,headerBytesSent:v.headerBytesSent||0,totalPacketSendDelay:v.totalPacketSendDelay||0};if(v.mediaType==="video"||v.kind==="video"){const R=v,De={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped?R.framesDropped:R.droppedFrames,framesPerSecond:R.framesPerSecond?R.framesPerSecond:R.framerateMean,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.totalEncodeTime,totalPacketSendDelay:R.totalEncodeTime,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...O};d.outboundVideoRtp.set(M.id,De),d.producerStreamMap.get(P).outboundVideoRtpId.push(M.id),this.processOutboundProducerVideoStats(P,me,De)}else if(v.mediaType==="audio"||v.kind==="audio"){const R=v,De={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...O};d.outboundAudioRtp.set(M.id,De),d.producerStreamMap.get(P).outboundAudioRtpId.push(M.id),this.processOutboundProducerAudioStats(P,me,De)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(M.id))break;const v=M,P=a||this.inboundConsumerMap.get(M.id),U=this.pausedConsumerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(v.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const me=this.overallConsumersStatsMap[P];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.inboundConsumerMap.has(M.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Ce={bytesReceived:v.bytesReceived,packetsReceived:v.packetsReceived,packetsLost:v.packetsLost>=0?v.packetsLost:0,jitter:v.jitter,nackCount:v.nackCount,jitterBufferDelay:v.jitterBufferDelay,jitterBufferEmittedCount:v.jitterBufferEmittedCount,lastPacketReceivedTimestamp:v.lastPacketReceivedTimestamp,ssrc:v.ssrc,mid:v.mid,codecId:v.codecId,headerBytesReceived:v.headerBytesReceived||0,packetsDiscarded:v.packetsDiscarded||0,jitterBufferMinimumDelay:v.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:v.jitterBufferTargetDelay||0};if(v.mediaType==="video"||v.kind==="video"){const O=v,R={frameHeight:O.frameHeight,frameWidth:O.frameWidth,framesDecoded:O.framesDecoded,framesDropped:O.framesDropped?O.framesDropped:O.droppedFrames,framesPerSecond:O.framesPerSecond?O.framesPerSecond:O.framerateMean,framesReceived:O.framesReceived,keyFramesDecoded:O.keyFramesDecoded,firCount:O.firCount,decoderImplementation:O.decoderImplementation,pliCount:O.pliCount,totalProcessingDelay:O.totalProcessingDelay,qpSum:O.qpSum||0,totalAssemblyTime:O.totalAssemblyTime||0,totalDecodeTime:O.totalDecodeTime||0,totalFreezesDuration:O.totalFreezesDuration||0,totalInterFrameDelay:O.totalInterFrameDelay||0,totalPausesDuration:O.totalPausesDuration||0,totalSquaredInterFrameDelay:O.totalSquaredInterFrameDelay||0,freezeCount:O.freezeCount||0,pauseCount:O.pauseCount||0,powerEfficientDecoder:O.powerEfficientDecoder,...Ce};R.score=jg({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((k=this.videoConsumerToStatsMap.get(P))==null?void 0:k.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((A=this.videoConsumerToStatsMap.get(P))==null?void 0:A.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:ed({packetsLost:(R.packetsLost||0)-(((x=this.videoConsumerToStatsMap.get(P))==null?void 0:x.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,R),d.inboundVideoRtp.set(M.id,R),d.consumerStreamMap.get(P).inboundVideoRtpId.push(M.id),this.processInboundConsumerVideoStats(P,me,R)}else if(v.mediaType==="audio"||v.kind==="audio"){const O=v,R={audioLevel:O.audioLevel,concealedSamples:O.concealedSamples,concealmentEvents:O.concealmentEvents,totalAudioEnergy:O.totalAudioEnergy,totalSamplesDuration:O.totalSamplesDuration,totalSamplesReceived:O.totalSamplesReceived,fecPacketsDiscarded:O.fecPacketsDiscarded||0,fecPacketsReceived:O.fecPacketsReceived||0,insertedSamplesForDeceleration:O.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:O.removedSamplesForAcceleration||0,silentConcealedSamples:O.silentConcealedSamples||0,playoutId:O.playoutId,...Ce};R.score=qg({concealmentEvents:(R.concealmentEvents||0)-(((K=this.audioConsumerToStatsMap.get(P))==null?void 0:K.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((Y=this.audioConsumerToStatsMap.get(P))==null?void 0:Y.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((Ue=this.audioConsumerToStatsMap.get(P))==null?void 0:Ue.packetsReceived)||0),jitter:R.jitter||0}),E.set(P,{score:+(R.score*10).toFixed(),packetsLostPercentage:ed({packetsLost:(R.packetsLost||0)-(((es=this.audioConsumerToStatsMap.get(P))==null?void 0:es.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((Yr=this.audioConsumerToStatsMap.get(P))==null?void 0:Yr.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((ts=this.audioConsumerToStatsMap.get(P))==null?void 0:ts.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,R),d.inboundAudioRtp.set(M.id,R),d.consumerStreamMap.get(P).inboundAudioRtpId.push(M.id),this.processInboundConsumerAudioStats(P,me,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}}}if(d.producerStreamMap.forEach((M,v)=>{var P,U,me,Ce,O,R,De,Ds,Ca,Ra,ka,Ma,Ia,Aa,Da,Oa,Na,La,Va,xa,Ua,$a,Ba;if(M.outboundVideoRtpId.length>0){const ae=[];M.outboundVideoRtpId.forEach(Dl=>{ae.push(d.outboundVideoRtp.get(Dl))});const Q=this.getWorkingSimulcastVideoStats(ae);Q.score=Hg({frameWidth:Q.frameWidth||0,framesPerSecond:Q.framesPerSecond||0,jitter:((P=Q.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsSent:(Q.packetsSent||0)-(((U=this.videoProducerToStatsMap.get(v))==null?void 0:U.packetsSent)||0),packetsLost:(((me=Q.remoteData)==null?void 0:me.packetsLost)||0)-(((O=(Ce=this.videoProducerToStatsMap.get(v))==null?void 0:Ce.remoteData)==null?void 0:O.packetsLost)||0),framesEncoded:(Q.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(v))==null?void 0:R.framesEncoded)||0)}),T.set(v,{score:+(Q.score*10).toFixed(),frameWidth:Q.frameWidth||0,frameHeight:Q.frameHeight||0,framesPerSecond:Q.framesPerSecond||0,jitter:((De=Q.remoteData)==null?void 0:De.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsLostPercentage:Zc({packetsSent:(Q.packetsSent||0)-(((Ds=this.videoProducerToStatsMap.get(v))==null?void 0:Ds.packetsSent)||0),packetsLost:(((Ca=Q.remoteData)==null?void 0:Ca.packetsLost)||0)-(((ka=(Ra=this.videoProducerToStatsMap.get(v))==null?void 0:Ra.remoteData)==null?void 0:ka.packetsLost)||0)}),bitrate:((Q.bytesSent||0)-(((Ma=this.videoProducerToStatsMap.get(v))==null?void 0:Ma.bytesSent)||0))*8/7,cpuLimitations:Q.qualityLimitationReason==="cpu",bandwidthLimitations:Q.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(v,Q)}else if(M.outboundAudioRtpId.length>0){const ae=d.outboundAudioRtp.get(M.outboundAudioRtpId[0]);ae.score=Bg({packetsSent:(ae.packetsSent||0)-(((Ia=this.audioProducerToStatsMap.get(v))==null?void 0:Ia.packetsSent)||0),packetsLost:(((Aa=ae.remoteData)==null?void 0:Aa.packetsLost)||0)-(((Oa=(Da=this.audioProducerToStatsMap.get(v))==null?void 0:Da.remoteData)==null?void 0:Oa.packetsLost)||0),jitter:((Na=ae.remoteData)==null?void 0:Na.jitter)||0}),T.set(v,{score:+(ae.score*10).toFixed(),bitrate:((ae.bytesSent||0)-(((La=this.audioProducerToStatsMap.get(v))==null?void 0:La.bytesSent)||0))*8/7,packetsLostPercentage:Zc({packetsSent:(ae.packetsSent||0)-(((Va=this.audioProducerToStatsMap.get(v))==null?void 0:Va.packetsSent)||0),packetsLost:(((xa=ae.remoteData)==null?void 0:xa.packetsLost)||0)-((($a=(Ua=this.audioProducerToStatsMap.get(v))==null?void 0:Ua.remoteData)==null?void 0:$a.packetsLost)||0)}),jitter:((Ba=ae.remoteData)==null?void 0:Ba.jitter)||0,isScreenShare:this.screenShareProducers.has(v)}),this.audioProducerToStatsMap.set(v,ae)}}),f.forEach(M=>{const v=u.find(U=>U.id===M.localCandidateId?(M.localCandidateId=U.id,U):null),P=p.find(U=>U.id===M.remoteCandidateId?(M.remoteCandidateId=U.id,U):null);v&&(M.localCandidateType=v.type,M.localCandidateAddress=Fr(v.address),M.localCandidatePort=v.port,M.localCandidateProtocol=v.protocol,M.localCandidateUrl=v.url,M.localCandidateNetworkType=v.networkType,M.localCandidateRelatedAddress=Fr(v.relatedAddress),M.localCandidateRelatedPort=v.relatedPort),P&&(M.remoteCandidateType=P.type,M.remoteCandidateAddress=Fr(P.address),M.remoteCandidatePort=P.port,M.remoteCandidateProtocol=P.protocol,M.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let M=0,v=0;d.remoteInboundRtp.forEach((P,U)=>{P.roundTripTime&&P.roundTripTime>M&&(M=P.roundTripTime,v=P.totalRoundTripTime)}),d.transport.roundTripTime=M,d.transport.totalRoundTripTime=v}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(M){}if(T.size>0)try{this.observer.emit("producer_score",T)}catch(M){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,a)=>{const o=this.producerMap.get(a),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(u=>{const p=e.outboundVideoRtp.get(u);return p.frameHeight||(p.frameHeight=c.height,p.frameWidth=c.width,p.framesPerSecond=c.frameRate),p}),l={producerId:a,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(u=>e.outboundAudioRtp.get(u))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let a;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(u=>{const f=this.consumerMap.get(i).track.getSettings(),T=e.inboundVideoRtp.get(u);return T.frameHeight||(T.frameHeight=f.height,T.frameWidth=f.width,T.framesPerSecond=f.frameRate),T});a={consumerId:i,peerId:o,producerId:c,appData:d,videoStats:l,audioStats:r==null?void 0:r.inboundAudioRtpId.map(u=>e.inboundAudioRtp.get(u))}}catch(o){console.error("getConsumerStatsFromParsedConsumerStats: ",o,e)}return a}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,a)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,a))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class rS extends zg{}function td(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function Ih(s,t,e){const r=s.value;return s.value=function(...i){try{const a=r.apply(this,i);return a&&a instanceof Promise?a.catch(o=>{td(this,t,e,o)}):a}catch(a){td(this,t,e,a)}return null},s}const z=(s,t)=>(e,r,i)=>{const a=i.value;return i.value=function(...o){try{const c=a.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{td(this,s,t,d)}):c}catch(c){td(this,s,t,c)}return null},i},iS=(s,t)=>(e,r,i)=>{if(i)return Ih(i,s,t);for(const a of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,a);o.value instanceof Function&&Object.defineProperty(e.prototype,a,Ih(o,s,t))}};var W=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(a=(i<3?o(a):i>3?o(t,e,a):o(t,e))||a);return i>3&&a&&Object.defineProperty(t,e,a),a};const J=console;let j=class extends st{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Og.PROD,a,o,c,d,l){super();h(this,"observer");h(this,"eventHandler");h(this,"measurements");h(this,"producingTransport");h(this,"consumingTransport");h(this,"producers",new Map);h(this,"consumers",new Map);h(this,"iceServers");h(this,"connectionInfoPromise");h(this,"pingStatsTimeout");h(this,"logger");h(this,"env");h(this,"apiHostnames");h(this,"peerId");h(this,"consumerSharedMediaStatesMap",new Map);h(this,"currentUserMediaStates",{});if(!l)throw Error("authToken is missing but required to initialize CallStats!");switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new FT({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new sS;break;case"Gecko":this.measurements=new zg;break;case"WebKit":this.measurements=new rS;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new st,this.measurements.observer.on("consumer_score",u=>{o.debug(`callStats::consumer_score ${[...u.entries()]}`),this.eventHandler.emit("consumer_score",u)}),this.measurements.observer.on("producer_score",u=>{o.debug(`callStats::producer_score ${[...u.entries()]}`),this.eventHandler.emit("producer_score",u)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const i=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(i,r))}registerProducingTransport(e){var i;this.producingTransport=e,e.on("close",this.disconnectProducingTransport.bind(this,e)),e.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((i=e._producers)==null?void 0:i.values())||[]).forEach(a=>{this.registerProducer(a)}),e.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var i;this.consumingTransport=e,e.on("close",this.disconnectConsumingTransport.bind(this,e)),e.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((i=e._consumers)==null?void 0:i.values())||[]).forEach(a=>{this.registerConsumer(a)}),e.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1,r){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:D.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:D.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?D.SCREENSHARE_STARTED:D.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:D.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:D.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===$t.AUDIO&&D.AUDIO_DEVICES_UPDATES||e===$t.VIDEO&&D.VIDEO_DEVICES_UPDATES||e===$t.SPEAKER&&D.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===$t.AUDIO&&D.SELECTED_MICROHPONE_UPDATE||e===$t.VIDEO&&D.SELECTED_CAMERA_UPDATE||e===$t.SPEAKER&&D.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:D.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===$t.AUDIO&&D.AUDIO_PLAY_FAILED||e===$t.VIDEO&&D.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===$t.AUDIO&&D.AUDIO_TRACK_MUTED||e===$t.VIDEO&&D.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:D.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:D.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:D.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:D.LEGACY_SWITCH,metadata:{on:e},timestamp:r})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e,r){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:D.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_BEGIN,timestamp:r}),new Promise(async(a,o)=>{const c=[];try{for(const d of e)try{if(d.iceServers&&d.iceServers.length>0){const l=await this.measurements.getNetworkQuality(d.iceServers);c.push({...d,networkResults:l})}}catch(l){console.warn("Error handling ",l)}a({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(a=>{this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_END,timestamp:r,metaData:a})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:D.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:D.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=D.AUDIO_ON:i=D.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=D.VIDEO_ON:i=D.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:D.PARTICIPANT_ROLE,timestamp:r,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0,r){var c,d;let i,a;if(this.producingTransport&&(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!i||!((c=i==null?void 0:i.producerReport)!=null&&c.length))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const l=await this.measurements.getProducersReport([...this.producers.values()]);i&&l?i.producerReport=l:(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!i||!(i!=null&&i.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(a=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!a||!((d=a.consumerReport)!=null&&d.length))){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const l=await this.measurements.getConsumersReport([...this.consumers.values()]);a&&l?a.consumerReport=l:(a=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!a||!a.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const o={producingTransportStats:i?i==null?void 0:i.transportReport:void 0,consumingTransportStats:a?a==null?void 0:a.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((a==null?void 0:a.producerReport)||[]),consumerStats:[].concat((a==null?void 0:a.consumerReport)||[]).concat((i==null?void 0:i.consumerReport)||[])};if(e&&o.producerStats.length===0&&o.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:D.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:D.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:D.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:D.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"registerIceServers",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"registerConsumer",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"registerProducer",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendConsumerSharedMediaStateEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"registerProducingTransport",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"registerConsumingTransport",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"deRegisterConsumer",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"deRegisterProducer",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"disconnectConsumingTransport",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"disconnectProducingTransport",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendPreCallTestBeginEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendScreenShareToggleEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendScreenShareRequestedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendActiveSpeakerEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"devices",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"selectedDevice",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"mediaPermission",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"mediaPlaybackFailed",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"mediaTrackMuted",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"tabChanged",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"browserBackgrounded",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"browserForegrounded",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"legacySwitch",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"getPreCallTestResults",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendCallJoinBeginEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendNetworkQualityTestBeginEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendWebSocketConnectedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendTransportConnectedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendAudioToggleEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendVideoToggleEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendParticipantRoleToggleEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"startPingStats",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"stopPingStats",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendPingStatsEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerRebufferEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerAudioBlockEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerInitializedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerWorkerErrorEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerErrorEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerRecoverableErrorEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerAnalyticsEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendIVSPlayerQualityChanged",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendPlayerLiveLatency",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendDisconnectEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"sendReconnectEvent",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"expectedVideoResolution",null);W([z(TypeError,(s,t)=>J.error(t,s))],j.prototype,"expectedScreenshareResolution",null);j=W([iS(TypeError,(s,t)=>J.error(t,s))],j);const nS=j;class Yg extends st{constructor(){super(...arguments);h(this,"stats");h(this,"peerId");h(this,"backend");h(this,"iceServers");h(this,"initialized",!1);h(this,"stalled",!1);h(this,"ipInformation");h(this,"logger")}async initialize({peerId:e,engineName:r,env:i=Og.PROD,iceServers:a,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:p}){var f,T,E;try{if(this.peerId=e,this.logger=d,!p){this.logger.error("callStats::initialize",{event:"auth_token_missing",peerId:this.peerId}),this.stallCallStats();return}this.ipInformation=await Wg.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new nS(o,r,i,c,d,e,l,p),this.iceServers=a,(f=this.backend)==null||f.registerIceServers(this.iceServers),this.initialized=!0,(E=(T=this.backend)==null?void 0:T.eventHandler)==null||E.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(b){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:b instanceof Error?b.message:String(b),stack:b instanceof Error?b.stack:void 0}),this.stallCallStats()}}configureSendTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerConsumingTransport(e)})}async candidateRegionalNetworkQualityTest(e){const r=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,r)}catch(a){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:a.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,a;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(a=this.backend)==null||a.startPingStats()})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var r,i;(r=this.backend)==null||r.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!1,e,r)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,r)})}devices(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.mediaPermission(e,r,i)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.tabChanged(e,r)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserForegrounded(e)})}legacySwitch(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.legacySwitch(e,r)})}async startPreCallTest(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,r)})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=i=>{e(i,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){const i=new Date;this.onSafeInitialization(()=>{var a,o,c,d,l,u,p,f,T,E,b;switch(e){case"PlayerRebuffering":(a=this.backend)==null||a.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(p=this.backend)==null||p.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(f=this.backend)==null||f.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(T=this.backend)==null||T.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(E=this.backend)==null||E.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(b=this.backend)==null||b.sendIVSPlayerQualityChanged(r,i);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.expectedScreenshareResolution(e,r,i)})}}const aS=new Yg;aS.setMaxListeners(30);var mo;class oS{constructor(){g(this,mo,void 0)}get telemetry(){var t;return(t=n(this,mo))==null?void 0:t.getValue("telemetry")}init(t){m(this,mo,t)}info(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("info",t,e,r)}error(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("error",t,e,r)}debug(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("debug",t,e,r)}log(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("log",t,e,r)}warn(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("warn",t,e,r)}}mo=new WeakMap;var Ls,Vs;class cS extends st.EventEmitter{constructor(e){super();g(this,Ls,void 0);g(this,Vs,void 0);h(this,"asyncPromiseTimeout");h(this,"logger");this.logger=e,m(this,Ls,new Map),m(this,Vs,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){n(this,Ls).set(e,[]);const i=n(this,Vs).get(e).map(()=>new Promise(a=>{n(this,Ls).get(e).push(a)}));super.emit(e,...r),await Promise.race([Promise.all(i),new Promise((a,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),n(this,Ls).delete(e)}onAsync(e,r){const i=n(this,Ls),a=async(...o)=>{var d;try{await r(...o)}catch(l){this.logger.error("[onAsync]",{error:l})}const c=(d=i.get(e))==null?void 0:d.shift();c==null||c()};return n(this,Vs).get(e)||n(this,Vs).set(e,[]),n(this,Vs).get(e).push(a),super.on(e,a)}reset(){m(this,Ls,new Map),m(this,Vs,new Map),super.removeAllListeners()}}Ls=new WeakMap,Vs=new WeakMap;var dS=typeof global=="object"&&global&&global.Object===Object&&global;const Qg=dS;var lS=typeof self=="object"&&self&&self.Object===Object&&self,uS=Qg||lS||Function("return this")();const fs=uS;var hS=fs.Symbol;const Ms=hS;var Xg=Object.prototype,pS=Xg.hasOwnProperty,gS=Xg.toString,Ha=Ms?Ms.toStringTag:void 0;function mS(s){var t=pS.call(s,Ha),e=s[Ha];try{s[Ha]=void 0;var r=!0}catch(a){}var i=gS.call(s);return r&&(t?s[Ha]=e:delete s[Ha]),i}var fS=Object.prototype,TS=fS.toString;function SS(s){return TS.call(s)}var vS="[object Null]",yS="[object Undefined]",Ah=Ms?Ms.toStringTag:void 0;function Ki(s){return s==null?s===void 0?yS:vS:Ah&&Ah in Object(s)?mS(s):SS(s)}function Is(s){return s!=null&&typeof s=="object"}var ES="[object Symbol]";function hl(s){return typeof s=="symbol"||Is(s)&&Ki(s)==ES}function PS(s,t){for(var e=-1,r=s==null?0:s.length,i=Array(r);++e<r;)i[e]=t(s[e],e,s);return i}var bS=Array.isArray;const Dt=bS;var _S=1/0,Dh=Ms?Ms.prototype:void 0,Oh=Dh?Dh.toString:void 0;function Zg(s){if(typeof s=="string")return s;if(Dt(s))return PS(s,Zg)+"";if(hl(s))return Oh?Oh.call(s):"";var t=s+"";return t=="0"&&1/s==-_S?"-0":t}var wS=/\s/;function CS(s){for(var t=s.length;t--&&wS.test(s.charAt(t)););return t}var RS=/^\s+/;function kS(s){return s&&s.slice(0,CS(s)+1).replace(RS,"")}function Zt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var Nh=0/0,MS=/^[-+]0x[0-9a-f]+$/i,IS=/^0b[01]+$/i,AS=/^0o[0-7]+$/i,DS=parseInt;function Lh(s){if(typeof s=="number")return s;if(hl(s))return Nh;if(Zt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Zt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=kS(s);var e=IS.test(s);return e||AS.test(s)?DS(s.slice(2),e?2:8):MS.test(s)?Nh:+s}function qu(s){return s}var OS="[object AsyncFunction]",NS="[object Function]",LS="[object GeneratorFunction]",VS="[object Proxy]";function ju(s){if(!Zt(s))return!1;var t=Ki(s);return t==NS||t==LS||t==OS||t==VS}var xS=fs["__core-js_shared__"];const Nl=xS;var Vh=function(){var s=/[^.]+$/.exec(Nl&&Nl.keys&&Nl.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function US(s){return!!Vh&&Vh in s}var $S=Function.prototype,BS=$S.toString;function zi(s){if(s!=null){try{return BS.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var HS=/[\\^$.*+?()[\]{}|]/g,FS=/^\[object .+?Constructor\]$/,qS=Function.prototype,jS=Object.prototype,GS=qS.toString,WS=jS.hasOwnProperty,JS=RegExp("^"+GS.call(WS).replace(HS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function KS(s){if(!Zt(s)||US(s))return!1;var t=ju(s)?JS:FS;return t.test(zi(s))}function zS(s,t){return s==null?void 0:s[t]}function Yi(s,t){var e=zS(s,t);return KS(e)?e:void 0}var YS=Yi(fs,"WeakMap");const Kl=YS;var xh=Object.create,QS=function(){function s(){}return function(t){if(!Zt(t))return{};if(xh)return xh(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const XS=QS;function ZS(s,t,e){switch(e.length){case 0:return s.call(t);case 1:return s.call(t,e[0]);case 2:return s.call(t,e[0],e[1]);case 3:return s.call(t,e[0],e[1],e[2])}return s.apply(t,e)}function ev(){}function em(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var tv=800,sv=16,rv=Date.now;function iv(s){var t=0,e=0;return function(){var r=rv(),i=sv-(r-e);if(e=r,i>0){if(++t>=tv)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function nv(s){return function(){return s}}var av=function(){try{var s=Yi(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const sd=av;var ov=sd?function(s,t){return sd(s,"toString",{configurable:!0,enumerable:!1,value:nv(t),writable:!0})}:qu;const cv=ov;var dv=iv(cv);const lv=dv;function uv(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function hv(s,t,e,r){for(var i=s.length,a=e+(r?1:-1);r?a--:++a<i;)if(t(s[a],a,s))return a;return-1}function pv(s){return s!==s}function gv(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function mv(s,t,e){return t===t?gv(s,t,e):hv(s,pv,e)}function fv(s,t){var e=s==null?0:s.length;return!!e&&mv(s,t,0)>-1}var Tv=9007199254740991,Sv=/^(?:0|[1-9]\d*)$/;function Gu(s,t){var e=typeof s;return t=t==null?Tv:t,!!t&&(e=="number"||e!="symbol"&&Sv.test(s))&&s>-1&&s%1==0&&s<t}function Wu(s,t,e){t=="__proto__"&&sd?sd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function Tc(s,t){return s===t||s!==s&&t!==t}var vv=Object.prototype,yv=vv.hasOwnProperty;function tm(s,t,e){var r=s[t];(!(yv.call(s,t)&&Tc(r,e))||e===void 0&&!(t in s))&&Wu(s,t,e)}function Sc(s,t,e,r){var i=!e;e||(e={});for(var a=-1,o=t.length;++a<o;){var c=t[a],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?Wu(e,c,d):tm(e,c,d)}return e}var Uh=Math.max;function Ev(s,t,e){return t=Uh(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,a=Uh(r.length-t,0),o=Array(a);++i<a;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),ZS(s,this,c)}}function Pv(s,t){return lv(Ev(s,t,qu),s+"")}var bv=9007199254740991;function Ju(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=bv}function vc(s){return s!=null&&Ju(s.length)&&!ju(s)}function _v(s,t,e){if(!Zt(e))return!1;var r=typeof t;return(r=="number"?vc(e)&&Gu(t,e.length):r=="string"&&t in e)?Tc(e[t],s):!1}function wv(s){return Pv(function(t,e){var r=-1,i=e.length,a=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(a=s.length>3&&typeof a=="function"?(i--,a):void 0,o&&_v(e[0],e[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,a)}return t})}var Cv=Object.prototype;function pl(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||Cv;return s===e}function Rv(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var kv="[object Arguments]";function $h(s){return Is(s)&&Ki(s)==kv}var sm=Object.prototype,Mv=sm.hasOwnProperty,Iv=sm.propertyIsEnumerable,Av=$h(function(){return arguments}())?$h:function(s){return Is(s)&&Mv.call(s,"callee")&&!Iv.call(s,"callee")};const lo=Av;function Dv(){return!1}var rm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Bh=rm&&typeof module=="object"&&module&&!module.nodeType&&module,Ov=Bh&&Bh.exports===rm,Hh=Ov?fs.Buffer:void 0,Nv=Hh?Hh.isBuffer:void 0,Lv=Nv||Dv;const Ta=Lv;var Vv="[object Arguments]",xv="[object Array]",Uv="[object Boolean]",$v="[object Date]",Bv="[object Error]",Hv="[object Function]",Fv="[object Map]",qv="[object Number]",jv="[object Object]",Gv="[object RegExp]",Wv="[object Set]",Jv="[object String]",Kv="[object WeakMap]",zv="[object ArrayBuffer]",Yv="[object DataView]",Qv="[object Float32Array]",Xv="[object Float64Array]",Zv="[object Int8Array]",ey="[object Int16Array]",ty="[object Int32Array]",sy="[object Uint8Array]",ry="[object Uint8ClampedArray]",iy="[object Uint16Array]",ny="[object Uint32Array]",pe={};pe[Qv]=pe[Xv]=pe[Zv]=pe[ey]=pe[ty]=pe[sy]=pe[ry]=pe[iy]=pe[ny]=!0;pe[Vv]=pe[xv]=pe[zv]=pe[Uv]=pe[Yv]=pe[$v]=pe[Bv]=pe[Hv]=pe[Fv]=pe[qv]=pe[jv]=pe[Gv]=pe[Wv]=pe[Jv]=pe[Kv]=!1;function ay(s){return Is(s)&&Ju(s.length)&&!!pe[Ki(s)]}function Ku(s){return function(t){return s(t)}}var im=typeof exports=="object"&&exports&&!exports.nodeType&&exports,to=im&&typeof module=="object"&&module&&!module.nodeType&&module,oy=to&&to.exports===im,Ll=oy&&Qg.process,cy=function(){try{var s=to&&to.require&&to.require("util").types;return s||Ll&&Ll.binding&&Ll.binding("util")}catch(t){}}();const Sa=cy;var Fh=Sa&&Sa.isTypedArray,dy=Fh?Ku(Fh):ay;const gl=dy;var ly=Object.prototype,uy=ly.hasOwnProperty;function nm(s,t){var e=Dt(s),r=!e&&lo(s),i=!e&&!r&&Ta(s),a=!e&&!r&&!i&&gl(s),o=e||r||i||a,c=o?Rv(s.length,String):[],d=c.length;for(var l in s)(t||uy.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||a&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Gu(l,d)))&&c.push(l);return c}function am(s,t){return function(e){return s(t(e))}}var hy=am(Object.keys,Object);const py=hy;var gy=Object.prototype,my=gy.hasOwnProperty;function om(s){if(!pl(s))return py(s);var t=[];for(var e in Object(s))my.call(s,e)&&e!="constructor"&&t.push(e);return t}function ml(s){return vc(s)?nm(s):om(s)}function fy(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var Ty=Object.prototype,Sy=Ty.hasOwnProperty;function vy(s){if(!Zt(s))return fy(s);var t=pl(s),e=[];for(var r in s)r=="constructor"&&(t||!Sy.call(s,r))||e.push(r);return e}function yc(s){return vc(s)?nm(s,!0):vy(s)}var yy=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ey=/^\w*$/;function zu(s,t){if(Dt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||hl(s)?!0:Ey.test(s)||!yy.test(s)||t!=null&&s in Object(t)}var Py=Yi(Object,"create");const uo=Py;function by(){this.__data__=uo?uo(null):{},this.size=0}function _y(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var wy="__lodash_hash_undefined__",Cy=Object.prototype,Ry=Cy.hasOwnProperty;function ky(s){var t=this.__data__;if(uo){var e=t[s];return e===wy?void 0:e}return Ry.call(t,s)?t[s]:void 0}var My=Object.prototype,Iy=My.hasOwnProperty;function Ay(s){var t=this.__data__;return uo?t[s]!==void 0:Iy.call(t,s)}var Dy="__lodash_hash_undefined__";function Oy(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=uo&&t===void 0?Dy:t,this}function Wi(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}Wi.prototype.clear=by;Wi.prototype.delete=_y;Wi.prototype.get=ky;Wi.prototype.has=Ay;Wi.prototype.set=Oy;function Ny(){this.__data__=[],this.size=0}function fl(s,t){for(var e=s.length;e--;)if(Tc(s[e][0],t))return e;return-1}var Ly=Array.prototype,Vy=Ly.splice;function xy(s){var t=this.__data__,e=fl(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():Vy.call(t,e,1),--this.size,!0}function Uy(s){var t=this.__data__,e=fl(t,s);return e<0?void 0:t[e][1]}function $y(s){return fl(this.__data__,s)>-1}function By(s,t){var e=this.__data__,r=fl(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function dr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}dr.prototype.clear=Ny;dr.prototype.delete=xy;dr.prototype.get=Uy;dr.prototype.has=$y;dr.prototype.set=By;var Hy=Yi(fs,"Map");const ho=Hy;function Fy(){this.size=0,this.__data__={hash:new Wi,map:new(ho||dr),string:new Wi}}function qy(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function Tl(s,t){var e=s.__data__;return qy(t)?e[typeof t=="string"?"string":"hash"]:e.map}function jy(s){var t=Tl(this,s).delete(s);return this.size-=t?1:0,t}function Gy(s){return Tl(this,s).get(s)}function Wy(s){return Tl(this,s).has(s)}function Jy(s,t){var e=Tl(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function lr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}lr.prototype.clear=Fy;lr.prototype.delete=jy;lr.prototype.get=Gy;lr.prototype.has=Wy;lr.prototype.set=Jy;var Ky="Expected a function";function Yu(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(Ky);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],a=e.cache;if(a.has(i))return a.get(i);var o=s.apply(this,r);return e.cache=a.set(i,o)||a,o};return e.cache=new(Yu.Cache||lr),e}Yu.Cache=lr;var zy=500;function Yy(s){var t=Yu(s,function(r){return e.size===zy&&e.clear(),r}),e=t.cache;return t}var Qy=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Xy=/\\(\\)?/g,Zy=Yy(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(Qy,function(e,r,i,a){t.push(i?a.replace(Xy,"$1"):r||e)}),t});const eE=Zy;function tE(s){return s==null?"":Zg(s)}function cm(s,t){return Dt(s)?s:zu(s,t)?[s]:eE(tE(s))}var sE=1/0;function Sl(s){if(typeof s=="string"||hl(s))return s;var t=s+"";return t=="0"&&1/s==-sE?"-0":t}function dm(s,t){t=cm(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[Sl(t[e++])];return e&&e==r?s:void 0}function rE(s,t,e){var r=s==null?void 0:dm(s,t);return r===void 0?e:r}function lm(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var iE=am(Object.getPrototypeOf,Object);const Qu=iE;var nE="[object Object]",aE=Function.prototype,oE=Object.prototype,um=aE.toString,cE=oE.hasOwnProperty,dE=um.call(Object);function lE(s){if(!Is(s)||Ki(s)!=nE)return!1;var t=Qu(s);if(t===null)return!0;var e=cE.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&um.call(e)==dE}function uE(){this.__data__=new dr,this.size=0}function hE(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function pE(s){return this.__data__.get(s)}function gE(s){return this.__data__.has(s)}var mE=200;function fE(s,t){var e=this.__data__;if(e instanceof dr){var r=e.__data__;if(!ho||r.length<mE-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new lr(r)}return e.set(s,t),this.size=e.size,this}function ms(s){var t=this.__data__=new dr(s);this.size=t.size}ms.prototype.clear=uE;ms.prototype.delete=hE;ms.prototype.get=pE;ms.prototype.has=gE;ms.prototype.set=fE;function TE(s,t){return s&&Sc(t,ml(t),s)}function SE(s,t){return s&&Sc(t,yc(t),s)}var hm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,qh=hm&&typeof module=="object"&&module&&!module.nodeType&&module,vE=qh&&qh.exports===hm,jh=vE?fs.Buffer:void 0,Gh=jh?jh.allocUnsafe:void 0;function pm(s,t){if(t)return s.slice();var e=s.length,r=Gh?Gh(e):new s.constructor(e);return s.copy(r),r}function yE(s,t){for(var e=-1,r=s==null?0:s.length,i=0,a=[];++e<r;){var o=s[e];t(o,e,s)&&(a[i++]=o)}return a}function gm(){return[]}var EE=Object.prototype,PE=EE.propertyIsEnumerable,Wh=Object.getOwnPropertySymbols,bE=Wh?function(s){return s==null?[]:(s=Object(s),yE(Wh(s),function(t){return PE.call(s,t)}))}:gm;const Xu=bE;function _E(s,t){return Sc(s,Xu(s),t)}var wE=Object.getOwnPropertySymbols,CE=wE?function(s){for(var t=[];s;)lm(t,Xu(s)),s=Qu(s);return t}:gm;const mm=CE;function RE(s,t){return Sc(s,mm(s),t)}function fm(s,t,e){var r=t(s);return Dt(s)?r:lm(r,e(s))}function zl(s){return fm(s,ml,Xu)}function kE(s){return fm(s,yc,mm)}var ME=Yi(fs,"DataView");const Yl=ME;var IE=Yi(fs,"Promise");const Ql=IE;var AE=Yi(fs,"Set");const pn=AE;var Jh="[object Map]",DE="[object Object]",Kh="[object Promise]",zh="[object Set]",Yh="[object WeakMap]",Qh="[object DataView]",OE=zi(Yl),NE=zi(ho),LE=zi(Ql),VE=zi(pn),xE=zi(Kl),Qr=Ki;(Yl&&Qr(new Yl(new ArrayBuffer(1)))!=Qh||ho&&Qr(new ho)!=Jh||Ql&&Qr(Ql.resolve())!=Kh||pn&&Qr(new pn)!=zh||Kl&&Qr(new Kl)!=Yh)&&(Qr=function(s){var t=Ki(s),e=t==DE?s.constructor:void 0,r=e?zi(e):"";if(r)switch(r){case OE:return Qh;case NE:return Jh;case LE:return Kh;case VE:return zh;case xE:return Yh}return t});const va=Qr;var UE=Object.prototype,$E=UE.hasOwnProperty;function BE(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&$E.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var HE=fs.Uint8Array;const rd=HE;function Zu(s){var t=new s.constructor(s.byteLength);return new rd(t).set(new rd(s)),t}function FE(s,t){var e=t?Zu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var qE=/\w*$/;function jE(s){var t=new s.constructor(s.source,qE.exec(s));return t.lastIndex=s.lastIndex,t}var Xh=Ms?Ms.prototype:void 0,Zh=Xh?Xh.valueOf:void 0;function GE(s){return Zh?Object(Zh.call(s)):{}}function Tm(s,t){var e=t?Zu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var WE="[object Boolean]",JE="[object Date]",KE="[object Map]",zE="[object Number]",YE="[object RegExp]",QE="[object Set]",XE="[object String]",ZE="[object Symbol]",eP="[object ArrayBuffer]",tP="[object DataView]",sP="[object Float32Array]",rP="[object Float64Array]",iP="[object Int8Array]",nP="[object Int16Array]",aP="[object Int32Array]",oP="[object Uint8Array]",cP="[object Uint8ClampedArray]",dP="[object Uint16Array]",lP="[object Uint32Array]";function uP(s,t,e){var r=s.constructor;switch(t){case eP:return Zu(s);case WE:case JE:return new r(+s);case tP:return FE(s,e);case sP:case rP:case iP:case nP:case aP:case oP:case cP:case dP:case lP:return Tm(s,e);case KE:return new r;case zE:case XE:return new r(s);case YE:return jE(s);case QE:return new r;case ZE:return GE(s)}}function Sm(s){return typeof s.constructor=="function"&&!pl(s)?XS(Qu(s)):{}}var hP="[object Map]";function pP(s){return Is(s)&&va(s)==hP}var ep=Sa&&Sa.isMap,gP=ep?Ku(ep):pP;const mP=gP;var fP="[object Set]";function TP(s){return Is(s)&&va(s)==fP}var tp=Sa&&Sa.isSet,SP=tp?Ku(tp):TP;const vP=SP;var yP=1,EP=2,PP=4,vm="[object Arguments]",bP="[object Array]",_P="[object Boolean]",wP="[object Date]",CP="[object Error]",ym="[object Function]",RP="[object GeneratorFunction]",kP="[object Map]",MP="[object Number]",Em="[object Object]",IP="[object RegExp]",AP="[object Set]",DP="[object String]",OP="[object Symbol]",NP="[object WeakMap]",LP="[object ArrayBuffer]",VP="[object DataView]",xP="[object Float32Array]",UP="[object Float64Array]",$P="[object Int8Array]",BP="[object Int16Array]",HP="[object Int32Array]",FP="[object Uint8Array]",qP="[object Uint8ClampedArray]",jP="[object Uint16Array]",GP="[object Uint32Array]",de={};de[vm]=de[bP]=de[LP]=de[VP]=de[_P]=de[wP]=de[xP]=de[UP]=de[$P]=de[BP]=de[HP]=de[kP]=de[MP]=de[Em]=de[IP]=de[AP]=de[DP]=de[OP]=de[FP]=de[qP]=de[jP]=de[GP]=!0;de[CP]=de[ym]=de[NP]=!1;function so(s,t,e,r,i,a){var o,c=t&yP,d=t&EP,l=t&PP;if(e&&(o=i?e(s,r,i,a):e(s)),o!==void 0)return o;if(!Zt(s))return s;var u=Dt(s);if(u){if(o=BE(s),!c)return em(s,o)}else{var p=va(s),f=p==ym||p==RP;if(Ta(s))return pm(s,c);if(p==Em||p==vm||f&&!i){if(o=d||f?{}:Sm(s),!c)return d?RE(s,SE(o,s)):_E(s,TE(o,s))}else{if(!de[p])return i?s:{};o=uP(s,p,c)}}a||(a=new ms);var T=a.get(s);if(T)return T;a.set(s,o),vP(s)?s.forEach(function(_){o.add(so(_,t,e,_,s,a))}):mP(s)&&s.forEach(function(_,k){o.set(k,so(_,t,e,k,s,a))});var E=l?d?kE:zl:d?yc:ml,b=u?void 0:E(s);return uv(b||s,function(_,k){b&&(k=_,_=s[k]),tm(o,k,so(_,t,e,k,s,a))}),o}var WP=4;function JP(s){return so(s,WP)}var KP=1,zP=4;function eh(s){return so(s,KP|zP)}var YP="__lodash_hash_undefined__";function QP(s){return this.__data__.set(s,YP),this}function XP(s){return this.__data__.has(s)}function po(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new lr;++t<e;)this.add(s[t])}po.prototype.add=po.prototype.push=QP;po.prototype.has=XP;function ZP(s,t){for(var e=-1,r=s==null?0:s.length;++e<r;)if(t(s[e],e,s))return!0;return!1}function Pm(s,t){return s.has(t)}var eb=1,tb=2;function bm(s,t,e,r,i,a){var o=e&eb,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=a.get(s),u=a.get(t);if(l&&u)return l==t&&u==s;var p=-1,f=!0,T=e&tb?new po:void 0;for(a.set(s,t),a.set(t,s);++p<c;){var E=s[p],b=t[p];if(r)var _=o?r(b,E,p,t,s,a):r(E,b,p,s,t,a);if(_!==void 0){if(_)continue;f=!1;break}if(T){if(!ZP(t,function(k,A){if(!Pm(T,A)&&(E===k||i(E,k,e,r,a)))return T.push(A)})){f=!1;break}}else if(!(E===b||i(E,b,e,r,a))){f=!1;break}}return a.delete(s),a.delete(t),f}function sb(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function th(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var rb=1,ib=2,nb="[object Boolean]",ab="[object Date]",ob="[object Error]",cb="[object Map]",db="[object Number]",lb="[object RegExp]",ub="[object Set]",hb="[object String]",pb="[object Symbol]",gb="[object ArrayBuffer]",mb="[object DataView]",sp=Ms?Ms.prototype:void 0,Vl=sp?sp.valueOf:void 0;function fb(s,t,e,r,i,a,o){switch(e){case mb:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case gb:return!(s.byteLength!=t.byteLength||!a(new rd(s),new rd(t)));case nb:case ab:case db:return Tc(+s,+t);case ob:return s.name==t.name&&s.message==t.message;case lb:case hb:return s==t+"";case cb:var c=sb;case ub:var d=r&rb;if(c||(c=th),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=ib,o.set(s,t);var u=bm(c(s),c(t),r,i,a,o);return o.delete(s),u;case pb:if(Vl)return Vl.call(s)==Vl.call(t)}return!1}var Tb=1,Sb=Object.prototype,vb=Sb.hasOwnProperty;function yb(s,t,e,r,i,a){var o=e&Tb,c=zl(s),d=c.length,l=zl(t),u=l.length;if(d!=u&&!o)return!1;for(var p=d;p--;){var f=c[p];if(!(o?f in t:vb.call(t,f)))return!1}var T=a.get(s),E=a.get(t);if(T&&E)return T==t&&E==s;var b=!0;a.set(s,t),a.set(t,s);for(var _=o;++p<d;){f=c[p];var k=s[f],A=t[f];if(r)var x=o?r(A,k,f,t,s,a):r(k,A,f,s,t,a);if(!(x===void 0?k===A||i(k,A,e,r,a):x)){b=!1;break}_||(_=f=="constructor")}if(b&&!_){var N=s.constructor,$=t.constructor;N!=$&&"constructor"in s&&"constructor"in t&&!(typeof N=="function"&&N instanceof N&&typeof $=="function"&&$ instanceof $)&&(b=!1)}return a.delete(s),a.delete(t),b}var Eb=1,rp="[object Arguments]",ip="[object Array]",kc="[object Object]",Pb=Object.prototype,np=Pb.hasOwnProperty;function bb(s,t,e,r,i,a){var o=Dt(s),c=Dt(t),d=o?ip:va(s),l=c?ip:va(t);d=d==rp?kc:d,l=l==rp?kc:l;var u=d==kc,p=l==kc,f=d==l;if(f&&Ta(s)){if(!Ta(t))return!1;o=!0,u=!1}if(f&&!u)return a||(a=new ms),o||gl(s)?bm(s,t,e,r,i,a):fb(s,t,d,e,r,i,a);if(!(e&Eb)){var T=u&&np.call(s,"__wrapped__"),E=p&&np.call(t,"__wrapped__");if(T||E){var b=T?s.value():s,_=E?t.value():t;return a||(a=new ms),i(b,_,e,r,a)}}return f?(a||(a=new ms),yb(s,t,e,r,i,a)):!1}function vl(s,t,e,r,i){return s===t?!0:s==null||t==null||!Is(s)&&!Is(t)?s!==s&&t!==t:bb(s,t,e,r,vl,i)}var _b=1,wb=2;function Cb(s,t,e,r){var i=e.length,a=i,o=!r;if(s==null)return!a;for(s=Object(s);i--;){var c=e[i];if(o&&c[2]?c[1]!==s[c[0]]:!(c[0]in s))return!1}for(;++i<a;){c=e[i];var d=c[0],l=s[d],u=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var p=new ms;if(r)var f=r(l,u,d,s,t,p);if(!(f===void 0?vl(u,l,_b|wb,r,p):f))return!1}}return!0}function _m(s){return s===s&&!Zt(s)}function Rb(s){for(var t=ml(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,_m(i)]}return t}function wm(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function kb(s){var t=Rb(s);return t.length==1&&t[0][2]?wm(t[0][0],t[0][1]):function(e){return e===s||Cb(e,s,t)}}function Mb(s,t){return s!=null&&t in Object(s)}function Ib(s,t,e){t=cm(t,s);for(var r=-1,i=t.length,a=!1;++r<i;){var o=Sl(t[r]);if(!(a=s!=null&&e(s,o)))break;s=s[o]}return a||++r!=i?a:(i=s==null?0:s.length,!!i&&Ju(i)&&Gu(o,i)&&(Dt(s)||lo(s)))}function Ab(s,t){return s!=null&&Ib(s,t,Mb)}var Db=1,Ob=2;function Nb(s,t){return zu(s)&&_m(t)?wm(Sl(s),t):function(e){var r=rE(e,s);return r===void 0&&r===t?Ab(e,s):vl(t,r,Db|Ob)}}function Lb(s){return function(t){return t==null?void 0:t[s]}}function Vb(s){return function(t){return dm(t,s)}}function xb(s){return zu(s)?Lb(Sl(s)):Vb(s)}function Ub(s){return typeof s=="function"?s:s==null?qu:typeof s=="object"?Dt(s)?Nb(s[0],s[1]):kb(s):xb(s)}function $b(s){return function(t,e,r){for(var i=-1,a=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(a[d],d,a)===!1)break}return t}}var Bb=$b();const Hb=Bb;var Fb=function(){return fs.Date.now()};const xl=Fb;var qb="Expected a function",jb=Math.max,Gb=Math.min;function sh(s,t,e){var r,i,a,o,c,d,l=0,u=!1,p=!1,f=!0;if(typeof s!="function")throw new TypeError(qb);t=Lh(t)||0,Zt(e)&&(u=!!e.leading,p="maxWait"in e,a=p?jb(Lh(e.maxWait)||0,t):a,f="trailing"in e?!!e.trailing:f);function T(K){var Y=r,Ue=i;return r=i=void 0,l=K,o=s.apply(Ue,Y),o}function E(K){return l=K,c=setTimeout(k,t),u?T(K):o}function b(K){var Y=K-d,Ue=K-l,es=t-Y;return p?Gb(es,a-Ue):es}function _(K){var Y=K-d,Ue=K-l;return d===void 0||Y>=t||Y<0||p&&Ue>=a}function k(){var K=xl();if(_(K))return A(K);c=setTimeout(k,b(K))}function A(K){return c=void 0,f&&r?T(K):(r=i=void 0,o)}function x(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function N(){return c===void 0?o:A(xl())}function $(){var K=xl(),Y=_(K);if(r=arguments,i=this,d=K,Y){if(c===void 0)return E(d);if(p)return clearTimeout(c),c=setTimeout(k,t),T(d)}return c===void 0&&(c=setTimeout(k,t)),o}return $.cancel=x,$.flush=N,$}function Xl(s,t,e){(e!==void 0&&!Tc(s[t],e)||e===void 0&&!(t in s))&&Wu(s,t,e)}function Wb(s){return Is(s)&&vc(s)}function Zl(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function Jb(s){return Sc(s,yc(s))}function Kb(s,t,e,r,i,a,o){var c=Zl(s,e),d=Zl(t,e),l=o.get(d);if(l){Xl(s,e,l);return}var u=a?a(c,d,e+"",s,t,o):void 0,p=u===void 0;if(p){var f=Dt(d),T=!f&&Ta(d),E=!f&&!T&&gl(d);u=d,f||T||E?Dt(c)?u=c:Wb(c)?u=em(c):T?(p=!1,u=pm(d,!0)):E?(p=!1,u=Tm(d,!0)):u=[]:lE(d)||lo(d)?(u=c,lo(c)?u=Jb(c):(!Zt(c)||ju(c))&&(u=Sm(d))):p=!1}p&&(o.set(d,u),i(u,d,r,a,o),o.delete(d)),Xl(s,e,u)}function Cm(s,t,e,r,i){s!==t&&Hb(t,function(a,o){if(i||(i=new ms),Zt(a))Kb(s,t,o,e,Cm,r,i);else{var c=r?r(Zl(s,o),a,o+"",s,t,i):void 0;c===void 0&&(c=a),Xl(s,o,c)}},yc)}function zb(s,t,e){for(var r=-1,i=s==null?0:s.length;++r<i;)if(e(t,s[r]))return!0;return!1}var Yb="[object Map]",Qb="[object Set]",Xb=Object.prototype,Zb=Xb.hasOwnProperty;function e_(s){if(s==null)return!0;if(vc(s)&&(Dt(s)||typeof s=="string"||typeof s.splice=="function"||Ta(s)||gl(s)||lo(s)))return!s.length;var t=va(s);if(t==Yb||t==Qb)return!s.size;if(pl(s))return!om(s).length;for(var e in s)if(Zb.call(s,e))return!1;return!0}function t_(s,t){return vl(s,t)}var s_=wv(function(s,t,e){Cm(s,t,e)});const mr=s_;var r_=1/0,i_=pn&&1/th(new pn([,-0]))[1]==r_?function(s){return new pn(s)}:ev;const n_=i_;var a_=200;function Rm(s,t,e){var r=-1,i=fv,a=s.length,o=!0,c=[],d=c;if(e)o=!1,i=zb;else if(a>=a_){var l=t?null:n_(s);if(l)return th(l);o=!1,i=Pm,d=new po}else d=t?[]:c;e:for(;++r<a;){var u=s[r],p=t?t(u):u;if(u=e||u!==0?u:0,o&&p===p){for(var f=d.length;f--;)if(d[f]===p)continue e;t&&d.push(p),c.push(u)}else i(d,p,e)||(d!==c&&d.push(p),c.push(u))}return c}function o_(s){return s&&s.length?Rm(s):[]}function c_(s,t){return s&&s.length?Rm(s,Ub(t)):[]}function Bc(s){const t={};return typeof(s==null?void 0:s.code)=="number"&&(t.code=s.code),typeof(s==null?void 0:s.code)=="string"&&(t.code=s.code.substring(0,100)),typeof(s==null?void 0:s.name)=="string"&&(t.name=s.name.substring(0,500)),typeof(s==null?void 0:s.message)=="string"&&(t.message=s.message.substring(0,500)),typeof(s==null?void 0:s.reason)=="string"&&(t.reason=s.reason.substring(0,500)),typeof(s==null?void 0:s.stack)=="string"&&(t.stack=s.stack.substring(0,500)),t}const d_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},ap={STAGING:"staging",PROD:"prod"},Fa={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},l_={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,connectedMeetings:!0,devTools:{logs:!1}};function ya(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function u_({baseURI:s}){return s.includes("staging.realtime")?ap.STAGING:ap.PROD}function gn({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function h_(s){const t=s.getValue("baseURI");return{location:gn({servicePrefix:"location",baseURI:t}),locationLegacy:gn({servicePrefix:"location-legacy",baseURI:t}),daCollector:gn({servicePrefix:"da-collector",baseURI:t})}}const p_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m16.242 2.932 4.826 4.826a2.75 2.75 0 0 1-.715 4.404l-4.87 2.435a.75.75 0 0 0-.374.426l-1.44 4.166a1.25 1.25 0 0 1-2.065.476L8.5 16.561 4.06 21H3v-1.06l4.44-4.44-3.105-3.104a1.25 1.25 0 0 1 .476-2.066l4.166-1.44a.75.75 0 0 0 .426-.373l2.435-4.87a2.75 2.75 0 0 1 4.405-.715Zm3.766 5.886-4.826-4.826a1.25 1.25 0 0 0-2.002.325l-2.435 4.871a2.25 2.25 0 0 1-1.278 1.12l-3.789 1.31 6.705 6.704 1.308-3.789a2.25 2.25 0 0 1 1.12-1.277l4.872-2.436a1.25 1.25 0 0 0 .325-2.002Z" fill="currentColor"/></svg>',g_='<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z" fill="currentColor"></path></svg>',Mc=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(a=>{a(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((a,o)=>{r.onload=()=>{a(r),window.URL.revokeObjectURL(i)},r.onerror=()=>{o(),window.URL.revokeObjectURL(i)},r.src=i})},ri={logs:"https://api.realtime.cloudflare.com/logs/otel/logs",mock:{url:"https://api.realtime.cloudflare.com/mock",domain:"mock.realtime.cloudflare.com",app:"https://examples.realtime.cloudflare.com/meeting",stagingApp:"https://examples.staging.realtime.cloudflare.com/meeting"},apiBase:{prod:"https://api.realtime.cloudflare.com",staging:"https://api.staging.realtime.cloudflare.com",prodAlternate:"https://api.realtime.cloudflare.com"},baseURI:{prod:"realtime.cloudflare.com",staging:"staging.realtime.cloudflare.com"}},m_=["b3924730-93a3-4561-a9e5-441fb860aadb","f3eeb01c-13d9-4d89-ade4-62acbe36a91b","0b80d104-96aa-4de9-b907-2af213aecee8","b1f57ddb-02d3-43f9-9d19-b87ae060d754","0ea29cac-8161-4cb4-ac22-24b98a2d0ac0","ae3c467c-f261-4307-8a32-11454edb8619","f4fc4c6a-976e-4261-b063-c5a5fefe1fd7","2479fcba-5032-415e-96b9-0d789dbe6723","b340c4f8-43bc-4edb-a54c-5ab083bd9b16","b7703581-6e68-4bc1-bf1e-c95b3d61930a","f4776519-87bb-4d2c-b801-25ac11f96ac5","80a57014-1efe-44f8-b929-b8fca1cf18a1","4f43a422-f420-40f0-968e-c0515fb73c47","cd18cbda-0c13-41e5-a881-e99ef2f00995","da1258f4-666a-48fc-ab3b-21f69c17bddd","10ad9660-3bec-43f9-8304-acd5d4284180","ff830eaa-8c28-44b6-92de-527315f24552","32a8de63-bd77-4e2d-bd04-0048a3dbdf9c","e0d26ea8-066c-47bb-b0cf-57b79d68346a","3830f724-13ee-487f-b62f-2f039d76a09e","54c140a4-e4ff-402b-85d1-ce23182ad3e3","49f9e74a-bf03-4aac-a9c2-3db9f8fdfa41","7f11749e-d90b-4e41-be70-cc9f80641129","f7174bfd-c67c-4ee1-891f-4329333a28f8","e4d08973-cba5-434f-b38a-fc7908a0ea48","31e11e56-1705-4b52-963a-2cfa4af80142","ec8139f6-fe0f-4c09-a030-b97728c4c451","46a9290b-3d63-4ded-94a4-ab3cca22eec0","39d1d29a-aa47-444a-a77c-d075bca8a08a","531356db-519b-4d0f-a5da-086cc02bbafa","546de108-91aa-4bf8-a535-18110c3f57d8","6c7371c7-bc57-4cf9-8ab6-e377e8cedc0b","e8882a98-6276-4db0-b3a8-a216259dfb31","66292cea-49de-4acb-b695-d77153897a23","5f1d6cab-a385-48df-b6c9-a7f48ed7c58d","bdb1f51a-5eb8-4664-95b3-ee933075194e","6615e115-f38b-4cbb-bd50-acadaa16380e","4a1e79f2-0aab-43d4-ab15-d3a42b3ebd1f"],f_=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/;function km(s){var r,i,a;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(ri.baseURI.staging)),e=!!((a=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&a.logs);return t||e}function T_(s,t){var r;const e=(r=s==null?void 0:s.getValue("telemetry"))==null?void 0:r.logLevel;if(e==="off")return!1;if(e!=="all"){const i=["debug","log","info","warn","error"],a=i.indexOf(t.toLowerCase()),o=i.indexOf(e);if(a<o)return!1}return!0}function Mm(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var a;if([null,void 0,NaN].includes(s[r])||t&&(((a=t.match(/\./g))==null?void 0:a.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?Mm(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function op(s,t,e={},r=""){const i={};try{const a=JSON.stringify(e),o=JSON.parse(a),c=Mm(o,r),d=JSON.stringify(c);if(!(t==null?void 0:t.startsWith("[SDP]"))&&d.length>5e3){const u=`Log named: "${t}" is trying to log an flattened object of size
|
|
5
|
+
${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw km(s)&&console.error(u,{log:e,flattened:d}),new Error(u)}return JSON.parse(d)}catch(a){const o=Bc(a);i[`${r}.error.message`]=o.message||"",i[`${r}.error.stack`]=o.stack||"",i[`${r}.error.reason`]=o.reason||"",i[`${r}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}class y{constructor(){h(this,"logsCache",[]);h(this,"logsProcessorTimer");h(this,"compressionSupported",null);h(this,"tracingEnabled",!0);h(this,"initialized",!1);h(this,"logLevel","log");h(this,"logsProcessingInterval",7e3);h(this,"logExclusionList",["message","websocket/message","roomMessage","websocket/room-message","websocket/room-legacy-mode","chatMessage","websocket/new-chat-message","websocket/no-active-speaker","websocket/selected-peers","websocket/active-speaker","ping","websocket/new-consumer","websocket/producer-score","websocket/consumer-score","websocket/plugin-event","websocket/plugin-data","websocket/plugin-internal-data"]);h(this,"meetingMetadata",{})}isCompressionSupported(){if(this.compressionSupported===null)try{this.compressionSupported=typeof CompressionStream!="undefined"&&typeof Blob!="undefined"&&typeof Blob.prototype.stream=="function"&&typeof Response!="undefined"}catch(t){this.compressionSupported=!1,this.addLogInCurrentSpan("warn","Compression feature detection failed, using uncompressed logs",{error:t})}return this.compressionSupported}get logsEndpoint(){const t=qr.getContext(this.meetingMetadata.peerId);return`https://${gn({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}get logsBatchSize(){return this.isCompressionSupported()?50:25}resetPeerId(t){this.meetingMetadata.peerId=t}init(t,e,r,i){this.tracingEnabled=!0,this.initialized=!1,i&&(this.logLevel=i),this.logsCache=[];const a=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=a,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion");const{RNDeviceInfoImpl:o}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?o==null?void 0:o.getDeviceInfo():ge.getDeviceInfo(),this.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,this.logsProcessorTimer=setInterval(()=>this.processCachedLogs().catch(()=>{}),this.logsProcessingInterval),r&&(this.initialized=!0)}static trace(t,e=void 0){return(r,i,a)=>{const o=a.value;return a.value=function(...d){const l=this==null?void 0:this.telemetry;if(!l||!l.initialized||navigator.isReactNative||!l.tracingEnabled)return o.apply(this,d);l.addLogInCurrentSpan("info",t,e);const u=performance.now(),p=o.apply(this,d);return Promise.resolve(p).then(()=>{const f=performance.now();f-u>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:f-u})}).catch(()=>{const f=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:f-u})}),p},a}}injectContext(t){var i;const e=nr.v4().replace(/-/g,"").substring(0,16),r=(i=this.meetingMetadata.peerId)==null?void 0:i.replace(/-/g,"");t.TRACEPARENT=`00-${r}-${e}-01`}addLogInCurrentSpan(t,e,r={},i=!1){r!=null&&r.error&&Object.assign(r,{error:Bc(r.error)});const a=qr.getContext(this.meetingMetadata.peerId);if(km(a)&&(e_(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!T_(a,t))try{const c=op(a,e,r,"metadata"),d=new Date,l={message:e,level:t,...c,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};i?this.sendOtelLogsToNewRelic([l],{isInDestructionMode:!1}).catch(()=>{}):this.logsCache.push(l)}catch(c){this.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:Bc(c)})}}async sendOtelLogsToNewRelic(t,{isInDestructionMode:e=!1}={isInDestructionMode:!1}){const r=new AbortController,i=setTimeout(()=>r.abort("Logs request timed out after 8 seconds"),8e3);try{const a=qr.getContext(this.meetingMetadata.peerId),o=JSON.stringify({meetingMetadata:op(a,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:a.getValue("sdkName"),logs:t});let c;const d={Authorization:`Bearer ${a.getValue("authToken")}`};if(this.isCompressionSupported()){const l=new Blob([o]).stream().pipeThrough(new CompressionStream("gzip"));c=await new Response(l).arrayBuffer(),d["Content-Type"]="application/gzip",d["Content-Encoding"]="gzip"}else c=o,d["Content-Type"]="application/json";await fetch(this.logsEndpoint,{method:"POST",headers:d,body:c,signal:r.signal,keepalive:!!e})}catch(a){e||(this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Bc(a)}),this.logsCache.push(...t))}finally{clearTimeout(i)}}async processCachedLogs({isInDestructionMode:t=!1}={isInDestructionMode:!1}){const e=this.logsCache.splice(0,this.logsBatchSize);e!=null&&e.length&&await this.sendOtelLogsToNewRelic(e,{isInDestructionMode:t})}async destruct(){for(clearInterval(this.logsProcessorTimer);this.logsCache.length;)await this.processCachedLogs({isInDestructionMode:!0})}}function S_(s){const t={...s},e=new Map,r=(l,u)=>(e.has(l)||e.set(l,new Set),e.get(l).add(u),()=>{var p;return(p=e.get(l))==null?void 0:p.delete(u)}),i=(l,u)=>{var p;(p=e.get(l))==null||p.delete(u)},a=l=>{var u;(u=e.get(l))==null||u.forEach(p=>{try{p(t[l])}catch(f){}})};return{subscribe:r,unsubscribe:i,notify:a,setValue:(l,u,p=!0)=>{t[l]=u,p&&a(l)},getValue:l=>t[l],getAllValues:()=>t}}class v_{constructor(){h(this,"contexts",new Map);h(this,"mostRecentPeerId",null)}createContext(t,e){if(this.contexts.has(t))return this.contexts.get(t);const r=new y,i=new oS;this.contexts.set(t,S_(e)),this.contexts.get(t).setValue("peerSessionStore",new cS(i));const a=new Yg;return a.setMaxListeners(50),this.contexts.get(t).setValue("logger",i),this.contexts.get(t).setValue("telemetry",r),this.contexts.get(t).setValue("callstats",a),this.mostRecentPeerId=t,this.contexts.get(t)}remapContext(t,e){const r=e.getValue("peerId");r!==t&&(e.setValue("peerId",t),this.mostRecentPeerId=t,this.contexts.set(t,e),this.contexts.delete(r))}getContext(t){return this.contexts.get(t)}getMostRecentPeerId(){return this.mostRecentPeerId}}const qr=new v_,y_={"00":"Client","01":"Controller","02":"RoomNodeClient","03":"HiveNodeClient","04":"SocketService","05":"Chat","06":"Plugin","07":"Polls","08":"Meta","09":"Preset",10:"Recording",11:"Self",12:"Participant",13:"Spotlight",14:"Remote Request",15:"Webinar",16:"LocalMediaHandler",17:"End-End Encryption",18:"AI",19:"Livestream",20:"Stage"},Hc={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0004":"Invalid auth token","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0013":"Rate Limited","0014":"Failed to establish media connection.","0100":"Internal exception","0101":"Permission denied","0102":"Prerequisite module missing","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0404":"Missing prerequisites to establish a websocket connection","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0503":"Text Message is too large","0504":"Message not found by the given id","0505":"Action not permitted without joining room","0506":"Message search is disabled","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0700":"Internal exception","0705":"Action not permitted without joining room","0800":"Internal exception","0801":"Permission denied","0900":"Internal exception","0904":"Could not load preset",1e3:"Internal exception",1001:"Permission denied",1004:"Could not find specified recording",1005:"Action not permitted in given recording state",1100:"Internal exception",1101:"Permission denied",1102:"Unsupported",1103:"Name cannot be empty",1104:"No device selected while calling meeting.self.setDevice",1105:"Action not permitted without joining room",1106:"Can't set currently used device",1200:"Internal exception",1201:"Permission denied",1202:"Invalid page number was requested",1203:"Invalid participant count per page was requested",1204:"No participants exists with the given UserIds",1205:"Action not permitted without joining room",1206:"Manual Subscription Mode was not ACTIVATED",1207:"Invalid view mode",1208:"Manual Subscription not enabled for organization",1209:"Broadcast message type must be a non-empty string",1300:"Internal exception",1400:"Internal exception",1402:"No existing remote requests",1403:"No peer exists with given id",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1605:"Failed to get audio & video track",1606:"No audio input devices are available",1607:"No video input devices are available",1608:"No audio output devices (speakers) are available",1609:"Failed to fetch list of media devices",1610:"No media track exists",1611:"Failed to unmute track",1612:"Failed to get screenshare tracks",1701:"Crypto error",1800:"Internal exception",1801:"Can't fetch transcript file",1900:"Internal exception",1901:"Permission denied.",1902:"Livestream that has not yet started, can't be stopped",2e3:"Internal exception",2001:"Permission denied",2002:"Unsupported",2003:"Stage is disabled",2004:"Method not implemented",2005:"Action not permitted without joining room",2006:"Action not permitted in current stage status",9900:"Internal exception"};Object.keys(Hc).forEach(s=>{Hc[s]=`{${y_[s.slice(0,2)]}} ${Hc[s]}`});class C extends Error{constructor(e,r,i=void 0,a=!1){super(e);h(this,"code");this.code=r,this.name="ClientError";const o=this.code?`[ERR${this.code}]`:"[ERR]",c=this.code?Hc[this.code]:"";this.message=`${o}: ${c}
|
|
6
|
+
${this.message}`;try{let d=a&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const l=qr.getContext(qr.getMostRecentPeerId());if(l){const u=l.getValue("onError");try{u(this)}catch(p){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(d){}}}function Ic(s,t,e,r){if(r instanceof C)throw r;if(r instanceof t){const i=new C(r.message,e);throw i.stack=r.stack,i}else throw r}function cp(s,t,e){if(!s.value){const i=s.get,a=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Ic(this,t,e,o)}}),a&&(s.set=function(o){try{return a.apply(this,[o])}catch(c){Ic(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const a=r.apply(this,i);return a&&a instanceof Promise?a.catch(o=>{Ic(this,t,e,o)}):a}catch(a){Ic(this,t,e,a)}},s}function E_(s,t){return(e,r,i)=>{if(i)return cp(i,s,t);for(const a of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,a);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,a,cp(o,s,t))}}}const rt=s=>E_(Error,s);var rr=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(rr||{}),H=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(H||{}),Yp;typeof process!="undefined"&&(Yp=process==null?void 0:process.env)!=null&&Yp.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var Im=[-2,-1,0,1,2],P_=[0,1,2,3,4];function b_(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t=`0x${s[1]}${s[1]}`,e=`0x${s[2]}${s[2]}`,r=`0x${s[3]}${s[3]}`):s.length>6&&(t=`0x${s[1]}${s[2]}`,e=`0x${s[3]}${s[4]}`,r=`0x${s[5]}${s[6]}`),[+t,+e,+r]}var __=(s,t,e)=>{let r,i,a;if(t==0)r=i=a=e;else{const o=(l,u,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?l+(u-l)*6*p:p<.5?u:p<.6666666666666666?l+(u-l)*(.6666666666666666-p)*6:l),c=e<.5?e*(1+t):e+t-e*t,d=2*e-c;r=o(d,c,s+1/3),i=o(d,c,s),a=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(a*255)]},w_=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let a,o;const c=(r+i)/2;if(r==i)a=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:a=(t-e)/d+(t<e?6:0);break;case t:a=(e-s)/d+2;break;case e:a=(s-t)/d+4;break}a/=6}return[a,o,c]},C_=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},Am=(s,t=Im,e=.4)=>{const r=[],[i,a,o]=b_(s),[c,d,l]=w_(i,a,o),u=Math.round(l*100);u>70?e=.8:u>60?e=.9:u<10?e=.075:u<42&&(e=.3);const p=t.findIndex(_=>_===0);if(p===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const f=5-p,T=p+1,E=(100-u)/f,b=u/T;for(const _ of t){let k;_<0?k=u+_*b*e:_>0?k=u+_*E*e:k=u;const[A,x,N]=__(c,d,k/100);r.push(C_(A,x,N))}return r},dp={dark:{background:{1e3:"#252525",900:"#2F2F2F",800:"#323232",700:"#3E3E3E",600:"#4A4A4A"},text:"#F5F5F5","video-bg":"#1C1C1C"},light:{background:{1e3:"#FFFFFF",900:"#F5F5F5",800:"#EBEBEB",700:"#E0E0E0",600:"#D6D6D6"},text:"#111111","text-on-brand":"#ffffff","video-bg":"#DADADA"}},R_=s=>{const[t,e,r,i,a]=Am(s,Im);return{300:t,400:e,500:r,600:i,700:a}},k_=s=>{if(s==="#FFFFFF")return dp.light.background;if(s==="#000000")return dp.dark.background;const[t,e,r,i,a]=Am(s,P_);return{1e3:t,900:e,800:r,700:i,600:a}},M_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:R_("#2160FD"),background:k_("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Dm(){return eh(M_)}var I_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:Dm(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function A_(){return eh(I_)}var D_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:Dm(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function rh(){return eh(D_)}function O_(){ge.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(a=>{var o;return(o=a.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var w=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(w||{});class Pa extends st.EventEmitter{constructor(e){super();h(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}return super.on(e,r)}addListener(e,r){var i;try{const a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Lt extends st.EventEmitter{constructor(e){super();h(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}return super.on(e,r)}addListener(e,r){var i;try{const a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}function N_(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(i=>i.charAt(0)).join("").toUpperCase()}const lp=1080,up=1920,L_=(s,t,e,r,i,a)=>{let o=.5,c=.5;const d=i,l=a,u=Math.min(e/d,r/l);let p=d*u,f=l*u,T,E,b,_,k=1;return p<e&&(k=e/p),Math.abs(k-1)<1e-14&&f<r&&(k=r/f),p*=k,f*=k,b=d/(p/e),_=l/(f/r),T=(d-b)*o,E=(l-_)*c,T<0&&(T=0),E<0&&(E=0),b>d&&(b=d),_>l&&(_=l),[T,E,b,_,s,t,e,r]};var Bt,ii,Ye,Ht,Pe,is,xs,it,ke,Sn,vn,Us,yn;const bh=class extends Lt{constructor(e,r,i,a){const o=e.getValue("logger");super(o);g(this,Bt,void 0);g(this,ii,void 0);g(this,Ye,void 0);g(this,Ht,void 0);g(this,Pe,{height:lp,width:up});g(this,is,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,xs,void 0);g(this,it,{});g(this,ke,void 0);g(this,Sn,void 0);g(this,vn,void 0);g(this,Us,void 0);g(this,yn,!1);h(this,"cleanupEventListeners",()=>{n(this,ii).unsubscribe("stageStatus",this.handlePipMediaControls),n(this,ke).removeListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,ke).removeListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,ke).removeListener("roomLeft",()=>this.disable())});h(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});h(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});h(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});h(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});h(this,"eventCallback",e=>{e==="CAMERA"&&(n(this,ke).videoEnabled?n(this,ke).disableVideo():n(this,ke).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(n(this,ke).audioEnabled?n(this,ke).disableAudio():n(this,ke).enableAudio(),this.emit("micToggled")),e==="END"&&(n(this,ii).getValue("peerSessionStore").emit(w.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});h(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});h(this,"animate",()=>{if(!this.isActive&&n(this,Us)==="active"){this.disable(!0);return}n(this,it)!==void 0&&this.paintCanvas(),n(this,xs)!==void 0&&m(this,xs,requestAnimationFrame(()=>this.animate()))});h(this,"disable",(e=!1)=>{m(this,Us,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(n(this,xs)),e!==!0&&document.body.removeChild(n(this,Ye)),m(this,xs,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});m(this,ii,e),m(this,Us,"idle"),m(this,ke,r),m(this,is,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),a&&this.setupIcon("handRaise",a)}static async _init(e,r){let i,a;try{i=await Mc(p_),a=await Mc(g_)}catch(o){}return new bh(e,r,i,a)}async setupIcon(e,r){switch(e){case"handRaise":m(this,vn,r);break;case"pin":m(this,Sn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":m(this,vn,await Mc(r));break;case"pin":m(this,Sn,await Mc(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),a=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(a)},r.src=a})}createVideoContainer(){m(this,Ye,document.createElement("div")),n(this,Ye).style.width="0.1px",n(this,Ye).style.height="0.1px",n(this,Ye).style.overflow="hidden",n(this,Ye).style.position="absolute",n(this,Ye).style.bottom="0",n(this,Ye).style.right="0",n(this,Ye).style.opacity="0",n(this,Ye).appendChild(n(this,Ht))}setupEventListeners(){n(this,ii).subscribe("stageStatus",this.handlePipMediaControls),n(this,ke).addListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,ke).addListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,ke).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=n(this,Pe).height,e.width=n(this,Pe).width,m(this,Bt,e)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||n(this,ke).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||n(this,ke).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(n(this,it)).reduce((i,a)=>(i[a.pinned?"pinned":"regular"].push(a),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,a){if(n(this,Bt)===void 0)return;const o=n(this,Bt).getContext("2d"),c=n(this,Bt).width,d=0,l=0,u=r-d*2,p=i-d*2,f=Math.floor(c/u),T=Math.floor(e/f),b=e%f*(u+d)+d,_=T*(p+d)+d,{displayText:k,image:A}=a!=null?a:{};o.fillStyle=k||A?n(this,is).videoBackground:n(this,is).background,o.strokeStyle=n(this,is).brand,o.beginPath(),o.moveTo(b+l,_),o.arcTo(b+u,_,b+u,_+l,l),o.arcTo(b+u,_+p,b+u-l,_+p,l),o.arcTo(b,_+p,b,_+p-l,l),o.arcTo(b,_,b+l,_,l),o.closePath(),o.fill(),o.stroke();const x=u/6,N=u/2+b,$=p/2+_;o.save(),(k||A)&&(o.beginPath(),o.arc(N,$,x,0,Math.PI*2),o.fillStyle=n(this,is).brand,o.fill(),A?(o.clip(),o.drawImage(A,N-x,$-x,x*2,x*2),o.restore()):k&&(o.fillStyle=n(this,is).textOnBrand,o.font=`${x/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(k,N,$)),this.drawIcons(a,b,_,Math.max(u,p)))}drawIcons(e,r,i,a){const o=Math.min(Math.max(a*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,p=f=>{const T=n(this,Bt).getContext("2d");T.save(),T.fillStyle=n(this,is).background,T.beginPath(),T.moveTo(l+d,u),T.arcTo(l+o,u,l+o,u+d,d),T.arcTo(l+o,u+o,l+o-d,u+o,d),T.arcTo(l,u+o,l,u+o-d,d),T.arcTo(l,u,l+d,u,d),T.closePath(),T.fill(),typeof f=="string"?(T.font=`${o/1.5}px sans-serif`,T.fillStyle=n(this,is).text,T.textAlign="center",T.textBaseline="top",T.fillText(f,o/2+l,u+c)):T.drawImage(f,l+c,u+c,o-c*2,o-c*2),l+=o+c,T.restore()};e.pinned&&p(n(this,Sn)),e.handRaised&&p(n(this,vn)),e.reaction&&p(e.reaction)}drawTile(e,r,i){var l,u;if(n(this,Bt)===void 0)return;const a=n(this,Bt).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<n(this,Pe).height-5;){let p=0;for(;p<n(this,Pe).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const f=o[d].element,[T,E,b,_,k,A,x,N]=L_(p,c,e,r,f.videoWidth,f.videoHeight);((u=f==null?void 0:f.classList)==null?void 0:u.contains("mirror"))?(a.save(),a.scale(-1,1),a.drawImage(f,T,E,b,_,-1*k,A,-1*x,N),a.restore()):a.drawImage(f,T,E,b,_,k,A,x,N),this.drawIcons(o[d],k,A,Math.max(x,N))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,p+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[n(this,Pe).width,n(this,Pe).height];case 2:return[Math.floor(n(this,Pe).width/2),n(this,Pe).height];case 3:case 4:return[Math.floor(n(this,Pe).width/2),Math.floor(n(this,Pe).height/2)];case 5:case 6:return[Math.floor(n(this,Pe).width/3),Math.floor(n(this,Pe).height/2)];case 7:case 8:case 9:return[Math.floor(n(this,Pe).width/3),Math.floor(n(this,Pe).height/3)];default:return[Math.floor(n(this,Pe).width/3),Math.floor(n(this,Pe).height/2)]}}paintCanvas(){let e=this.getSources().length;e!==1&&(e=e%2>0?e+1:e);const[r,i]=this.calcGridElemSize(e);this.drawTile(r,i,e)}isSupported(){var e;return!!window.chrome&&document.pictureInPictureEnabled&&((e=n(this,ke).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(m(this,yn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),n(this,Ye))try{document.body.removeChild(n(this,Ye))}catch(e){}this.removeAllSources(),m(this,Bt,void 0),m(this,Ht,void 0),m(this,xs,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(n(this,yn))return;m(this,yn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");m(this,Pe,{height:e!=null?e:lp,width:r!=null?r:up}),i.height=n(this,Pe).height,i.width=n(this,Pe).width,i.autoplay=!0,i.muted=!0,i.srcObject=n(this,Bt).captureStream(24),m(this,Ht,i),n(this,Ht).onloadedmetadata=()=>{try{this.emit("pipStarted"),n(this,Ht).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(a){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){n(this,it)[e]!==void 0&&(n(this,it)[e].enabled=!0)}disableSource(e){n(this,it)[e]!==void 0&&(n(this,it)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const a=await(await fetch(r)).blob(),o=window.URL.createObjectURL(a);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(a){this.logger.error("Pip::GenerateAvatar",{error:a})}}addSource(e,r,i,a=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),n(this,it)[e]={id:e,element:r,enabled:i,pinned:a,displayText:o?N_(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised,reaction:r.reaction}});const i=n(this,it)[e];i&&(n(this,it)[e]={...i,...r})}removeSource(e){delete n(this,it)[e]}removePinnedSource(){Object.values(n(this,it)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){m(this,it,{})}enable(){m(this,Us,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",n(this,ke).videoEnabled),this.updateMediaSession("MIC",n(this,ke).audioEnabled),document.body.appendChild(n(this,Ye)),m(this,xs,requestAnimationFrame(()=>this.animate())),n(this,Ht).onloadedmetadata=()=>{n(this,Ht).requestPictureInPicture().then(()=>{m(this,Us,"active")})},n(this,Ht).readyState===4&&n(this,Ht).requestPictureInPicture().then(()=>{m(this,Us,"active")})}};let eu=bh;Bt=new WeakMap,ii=new WeakMap,Ye=new WeakMap,Ht=new WeakMap,Pe=new WeakMap,is=new WeakMap,xs=new WeakMap,it=new WeakMap,ke=new WeakMap,Sn=new WeakMap,vn=new WeakMap,Us=new WeakMap,yn=new WeakMap;var or;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(or||(or={}));var ir;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(ir||(ir={}));class V_ extends S.MessageType{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const Om=new V_;class x_ extends S.MessageType{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const U_=new x_;class $_ extends S.MessageType{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new $_;class B_ extends S.MessageType{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",or]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const Ts=new B_;class H_ extends S.MessageType{constructor(){super("media.ProducerPayload",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const F_=new H_;class q_ extends S.MessageType{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>Ts},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>F_}])}}const j_=new q_;class G_ extends S.MessageType{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const W_=new G_;class J_ extends S.MessageType{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Nm=new J_;class K_ extends S.MessageType{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts}])}}const z_=new K_;class Y_ extends S.MessageType{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts}])}}new Y_;class Q_ extends S.MessageType{constructor(){super("media.NestedScore",[{no:1,name:"encoding_idx",kind:"scalar",T:5},{no:2,name:"rid",kind:"scalar",T:9},{no:3,name:"score",kind:"scalar",T:5},{no:4,name:"ssrc",kind:"scalar",T:3,L:0}])}}const X_=new Q_;class Z_ extends S.MessageType{constructor(){super("media.ProducerTrack",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9},{no:3,name:"stream_id",kind:"scalar",T:9}])}}const ew=new Z_;class tw extends S.MessageType{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new tw;class sw extends S.MessageType{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new sw;class rw extends S.MessageType{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",ir]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"codec",kind:"message",T:()=>Om}])}}const Ec=new rw;class iw extends S.MessageType{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ec},{no:3,name:"producer_track",kind:"message",T:()=>ew},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const nw=new iw;class aw extends S.MessageType{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>nw}}])}}const Lm=new aw;class ow extends S.MessageType{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>pp},{no:2,name:"receiver",kind:"message",T:()=>pp}])}}const Vm=new ow;class cw extends S.MessageType{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Om},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>U_}])}}const hp=new cw;class dw extends S.MessageType{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>hp},{no:2,name:"video",kind:"message",T:()=>hp}])}}const pp=new dw;class lw extends S.MessageType{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const uw=new lw;class hw extends S.MessageType{constructor(){super("media.Simulcast",[{no:1,name:"preferred_rid",kind:"scalar",opt:!0,T:9},{no:2,name:"priority_ordering",kind:"scalar",opt:!0,T:9},{no:3,name:"rid_not_available",kind:"scalar",opt:!0,T:9}])}}const xm=new hw;class pw extends S.MessageType{constructor(){super("media.edge.GeoLocation",[{no:1,name:"latitude",kind:"scalar",T:2},{no:2,name:"longitude",kind:"scalar",T:2},{no:3,name:"region",kind:"scalar",opt:!0,T:9}])}}const gw=new pw;class mw extends S.MessageType{constructor(){super("media.edge.PeerJoinRequest",[{no:1,name:"display_name",kind:"scalar",opt:!0,T:9},{no:2,name:"prejoined",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:5,name:"preset",kind:"scalar",opt:!0,T:12},{no:6,name:"user_id",kind:"scalar",opt:!0,T:9},{no:7,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:8,name:"location",kind:"message",T:()=>gw},{no:9,name:"capabilities",kind:"message",T:()=>Vm}])}}const fw=new mw;class Tw extends S.MessageType{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const Sw=new Tw;class vw extends S.MessageType{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const yw=new vw;class Ew extends S.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new Ew;class Pw extends S.MessageType{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>uw},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>xm}])}}const bw=new Pw;class _w extends S.MessageType{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>bw},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const ww=new _w;class Cw extends S.MessageType{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>xm},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const Rw=new Cw;class kw extends S.MessageType{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>Rw},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Mw=new kw;class Iw extends S.MessageType{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>Ts},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const Aw=new Iw;class Dw extends S.MessageType{constructor(){super("media.edge.SelectedPeersRequest",[])}}new Dw;class Ow extends S.MessageType{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Nw=new Ow;class Lw extends S.MessageType{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Ac=new Lw;class Vw extends S.MessageType{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new Vw;class xw extends S.MessageType{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ts},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const Uw=new xw;class $w extends S.MessageType{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>Ts},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Bw=new $w;class Hw extends S.MessageType{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Hw;class Fw extends S.MessageType{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Um=new Fw;class qw extends S.MessageType{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const jw=new qw;class Gw extends S.MessageType{constructor(){super("media.edge.HostMediaControlForPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"audio",kind:"scalar",T:8},{no:3,name:"video",kind:"scalar",T:8},{no:4,name:"scree_share",kind:"scalar",T:8}])}}const Ww=new Gw;class Jw extends S.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerRequest",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8}])}}const Kw=new Jw;class zw extends S.MessageType{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const Yw=new zw;class Qw extends S.MessageType{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const Xw=new Qw;class Zw extends S.MessageType{constructor(){super("media.edge.EmptyResponse",[])}}new Zw;class eC extends S.MessageType{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>Ec},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>Vm}])}}const $m=new eC;class tC extends S.MessageType{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const tu=new tC;class sC extends S.MessageType{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const rC=new sC;class iC extends S.MessageType{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>rC}])}}const gp=new iC;class nC extends S.MessageType{constructor(){super("media.edge.PeerJoinResponse",[])}}new nC;class aC extends S.MessageType{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>Yw},{no:2,name:"participants",kind:"message",repeat:1,T:()=>$m},{no:3,name:"selected_peers",kind:"message",T:()=>tu},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const su=new aC;class oC extends S.MessageType{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const cC=new oC;class dC extends S.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Lm}])}}new dC;class lC extends S.MessageType{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Lm},{no:3,name:"description",kind:"message",T:()=>Ts}])}}const uC=new lC;class hC extends S.MessageType{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>Ts}])}}const pC=new hC;class gC extends S.MessageType{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>X_}])}}new gC;class mC extends S.MessageType{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new mC;class fC extends S.MessageType{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new fC;class TC extends S.MessageType{constructor(){super("media.edge.ProducerToggleResponse",[])}}new TC;class SC extends S.MessageType{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new SC;class vC extends S.MessageType{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Ts}])}}const yC=new vC;class EC extends S.MessageType{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Ts}])}}const PC=new EC;class bC extends S.MessageType{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new bC;class _C extends S.MessageType{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new _C;class wC extends S.MessageType{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new wC;class CC extends S.MessageType{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const RC=new CC;class kC extends S.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const MC=new kC;class IC extends S.MessageType{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const AC=new IC;class DC extends S.MessageType{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>$m}])}}const mp=new DC;class OC extends S.MessageType{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const fp=new OC;class NC extends S.MessageType{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>fp},{no:3,name:"screenshare",kind:"message",T:()=>fp}])}}const LC=new NC;class VC extends S.MessageType{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Nm},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>LC}])}}new VC;class xC extends S.MessageType{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ec}])}}const UC=new xC;class $C extends S.MessageType{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ec},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Tp=new $C;class BC extends S.MessageType{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ec}])}}const HC=new BC;class FC extends S.MessageType{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const ru=new FC;class qC extends S.MessageType{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Sp=new qC;class jC extends S.MessageType{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new jC;class GC extends S.MessageType{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new GC;class WC extends S.MessageType{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new WC;class JC extends S.MessageType{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new JC;class KC extends S.MessageType{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new KC;class zC extends S.MessageType{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new zC;class YC extends S.MessageType{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const Ul=new YC;class QC extends S.MessageType{constructor(){super("socket.api.BaseSocketHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9}])}}new QC;class XC extends S.MessageType{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const ZC=new XC;var ji;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(ji||(ji={}));var er;(function(s){s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.ON_STAGE=1]="ON_STAGE",s[s.APPROVED_STAGE=2]="APPROVED_STAGE",s[s.REQUESTED_STAGE=3]="REQUESTED_STAGE",s[s.OFF_STAGE=4]="OFF_STAGE"})(er||(er={}));var iu;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(iu||(iu={}));var nu;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(nu||(nu={}));var id;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(id||(id={}));class eR extends S.MessageType{constructor(){super("socket.room.PeerFlags",[{no:1,name:"preset_name",kind:"scalar",T:9},{no:2,name:"recorder_type",kind:"scalar",T:9},{no:3,name:"hidden_participant",kind:"scalar",T:8}])}}const tR=new eR;class sR extends S.MessageType{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",er,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>tR}])}}const yl=new sR;class rR extends S.MessageType{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>yl}])}}const tn=new rR;class iR extends S.MessageType{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",er,"STAGE_TYPE_"]}])}}const vp=new iR;class nR extends S.MessageType{constructor(){super("socket.room.RoomPeersInfoRequest",[{no:1,name:"seach_query",kind:"scalar",T:9},{no:2,name:"limit",kind:"scalar",T:5},{no:3,name:"offset",kind:"scalar",T:5}])}}const aR=new nR;class oR extends S.MessageType{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>yl}])}}const $l=new oR;class cR extends S.MessageType{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const yp=new cR;class dR extends S.MessageType{constructor(){super("socket.room.Room",[{no:1,name:"room_id",kind:"scalar",T:9},{no:2,name:"title",kind:"scalar",T:9},{no:4,name:"created_at",kind:"scalar",T:4,L:2},{no:5,name:"active_recordings",kind:"message",repeat:1,T:()=>uR},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Bm=new dR;class lR extends S.MessageType{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",ji]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const uR=new lR;class hR extends S.MessageType{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Bm}])}}const Ep=new hR;class pR extends S.MessageType{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Hm=new pR;class gR extends S.MessageType{constructor(){super("socket.room.UpdatePeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9}])}}new gR;class mR extends S.MessageType{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>yl},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:5,name:"use_hive",kind:"scalar",opt:!0,T:8},{no:6,name:"preset",kind:"scalar",opt:!0,T:12},{no:7,name:"capabilities",kind:"enum",repeat:1,T:()=>["socket.room.Capabilities",id,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const fR=new mR;class TR extends S.MessageType{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>yl},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const SR=new TR;class vR extends S.MessageType{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Bm}])}}new vR;class yR extends S.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new yR;class ER extends S.MessageType{constructor(){super("socket.room.ServiceError",[{no:1,name:"message",kind:"scalar",opt:!0,T:9},{no:2,name:"code",kind:"scalar",opt:!0,T:9}])}}const ih=new ER;class PR extends S.MessageType{constructor(){super("socket.room.ConnectedMeetingPeer",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:5,name:"display_picture_url",kind:"scalar",opt:!0,T:9}])}}const bR=new PR;class _R extends S.MessageType{constructor(){super("socket.room.ConnectedMeetingDump",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>bR}])}}const Pp=new _R;class wR extends S.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>Pp},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>Pp}])}}const CR=new wR;class RR extends S.MessageType{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const kR=new RR;class MR extends S.MessageType{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>kR}])}}const IR=new MR;class AR extends S.MessageType{constructor(){super("socket.room.CreateRoomResponsePayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>ih}])}}const DR=new AR;class OR extends S.MessageType{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>DR}])}}const bp=new OR;class NR extends S.MessageType{constructor(){super("socket.room.UpdateRoomRequestPayload",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9}])}}const LR=new NR;class VR extends S.MessageType{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>LR}])}}new VR;class xR extends S.MessageType{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const UR=new xR;class $R extends S.MessageType{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>UR}])}}const BR=new $R;class HR extends S.MessageType{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>jR}])}}const FR=new HR;class qR extends S.MessageType{constructor(){super("socket.room.DisableConnectedRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"status",kind:"scalar",opt:!0,T:9},{no:3,name:"title",kind:"scalar",opt:!0,T:9},{no:4,name:"error",kind:"message",T:()=>ih}])}}const jR=new qR;class GR extends S.MessageType{constructor(){super("socket.room.MovePeerPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"preset_id",kind:"scalar",opt:!0,T:9}])}}const WR=new GR;class JR extends S.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsRequest",[{no:1,name:"source_meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"destination_meeting_id",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>WR}])}}const KR=new JR;class zR extends S.MessageType{constructor(){super("socket.room.MovedPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>ih}])}}const Fm=new zR;class YR extends S.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Fm}])}}new YR;class QR extends S.MessageType{constructor(){super("socket.room.TransferPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"auth_token",kind:"scalar",opt:!0,T:9}])}}const XR=new QR;class ZR extends S.MessageType{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>sk}])}}const ek=new ZR;class tk extends S.MessageType{constructor(){super("socket.room.AddedParticipant",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const sk=new tk;class rk extends S.MessageType{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const qm=new rk;class ik extends S.MessageType{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"ids",kind:"scalar",repeat:2,T:9},{no:5,name:"broadcast_type",kind:"enum",opt:!0,T:()=>["socket.room.BroadcastType",nu,"BROADCAST_TYPE_"]}])}}const qa=new ik;class nk extends S.MessageType{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const ak=new nk;class ok extends S.MessageType{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const ck=new ok;class dk extends S.MessageType{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const lk=new dk;class uk extends S.MessageType{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>lk}])}}const _p=new uk;class hk extends S.MessageType{constructor(){super("socket.room.GetRoomStageStateResponse",[{no:1,name:"on_stage_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"approved_stage_peers",kind:"scalar",repeat:2,T:9},{no:3,name:"requested_stage_peers",kind:"scalar",repeat:2,T:9}])}}const wp=new hk;var au;(function(s){s[s.NONE=0]="NONE",s[s.SKIP=1]="SKIP",s[s.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",s[s.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(au||(au={}));var Br;(function(s){s[s.NONE=0]="NONE",s[s.ALLOWED=1]="ALLOWED",s[s.NOT_ALLOWED=2]="NOT_ALLOWED",s[s.CAN_REQUEST=3]="CAN_REQUEST"})(Br||(Br={}));class pk extends S.MessageType{constructor(){super("socket.preset.PollsPermissionUpdate",[{no:1,name:"can_create",kind:"scalar",opt:!0,T:8},{no:2,name:"can_vote",kind:"scalar",opt:!0,T:8},{no:3,name:"can_view",kind:"scalar",opt:!0,T:8}])}}const gk=new pk;class mk extends S.MessageType{constructor(){super("socket.preset.PluginsPermissionsUpdate",[{no:1,name:"can_close",kind:"scalar",opt:!0,T:8},{no:2,name:"can_start",kind:"scalar",opt:!0,T:8}])}}const fk=new mk;class Tk extends S.MessageType{constructor(){super("socket.preset.PublicChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"text",kind:"scalar",opt:!0,T:8},{no:3,name:"files",kind:"scalar",opt:!0,T:8}])}}const Sk=new Tk;class vk extends S.MessageType{constructor(){super("socket.preset.PrivateChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"can_receive",kind:"scalar",opt:!0,T:8},{no:3,name:"text",kind:"scalar",opt:!0,T:8},{no:4,name:"files",kind:"scalar",opt:!0,T:8}])}}const yk=new vk;class Ek extends S.MessageType{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>Sk},{no:2,name:"private",kind:"message",T:()=>yk}])}}const Pk=new Ek;class bk extends S.MessageType{constructor(){super("socket.preset.ConnectedMeetingPermissionUpdate",[{no:1,name:"can_alter_connected_meetings",kind:"scalar",opt:!0,T:8},{no:2,name:"can_switch_to_parent_meeting",kind:"scalar",opt:!0,T:8},{no:3,name:"can_switch_connected_meetings",kind:"scalar",opt:!0,T:8}])}}const _k=new bk;class wk extends S.MessageType{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Br,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Br,"STREAM_PERMISSION_TYPE_"]}])}}const Bl=new wk;class Ck extends S.MessageType{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Bl},{no:2,name:"audio",kind:"message",T:()=>Bl},{no:3,name:"screenshare",kind:"message",T:()=>Bl}])}}const Rk=new Ck;class kk extends S.MessageType{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>gk},{no:2,name:"plugins",kind:"message",T:()=>fk},{no:3,name:"chat",kind:"message",T:()=>Pk},{no:4,name:"accept_waiting_requests",kind:"scalar",opt:!0,T:8},{no:5,name:"can_accept_production_requests",kind:"scalar",opt:!0,T:8},{no:6,name:"can_edit_display_name",kind:"scalar",opt:!0,T:8},{no:7,name:"can_record",kind:"scalar",opt:!0,T:8},{no:8,name:"can_livestream",kind:"scalar",opt:!0,T:8},{no:9,name:"can_spotlight",kind:"scalar",opt:!0,T:8},{no:10,name:"disable_participant_audio",kind:"scalar",opt:!0,T:8},{no:11,name:"disable_participant_screensharing",kind:"scalar",opt:!0,T:8},{no:12,name:"disable_participant_video",kind:"scalar",opt:!0,T:8},{no:13,name:"kick_participant",kind:"scalar",opt:!0,T:8},{no:14,name:"pin_participant",kind:"scalar",opt:!0,T:8},{no:15,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:16,name:"waiting_room_type",kind:"enum",opt:!0,T:()=>["socket.preset.WaitingRoomType",au,"WAITING_ROOM_TYPE_"]},{no:17,name:"is_recorder",kind:"scalar",opt:!0,T:8},{no:18,name:"recorder_type",kind:"enum",opt:!0,T:()=>["socket.room.RecorderType",iu,"RECORDER_TYPE_"]},{no:19,name:"hidden_participant",kind:"scalar",opt:!0,T:8},{no:20,name:"show_participant_list",kind:"scalar",opt:!0,T:8},{no:21,name:"can_change_participant_permissions",kind:"scalar",opt:!0,T:8},{no:22,name:"connected_meetings",kind:"message",T:()=>_k},{no:23,name:"media",kind:"message",T:()=>Rk}])}}const nh=new kk;class Mk extends S.MessageType{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Ik=new Mk;class Ak extends S.MessageType{constructor(){super("socket.preset.PeerPreset",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"preset",kind:"scalar",T:12}])}}const Dk=new Ak;class Ok extends S.MessageType{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>Dk}])}}const Nk=new Ok;class Lk extends S.MessageType{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>nh}])}}const jm=new Lk;class Vk extends S.MessageType{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>jm}])}}const xk=new Vk;class Uk extends S.MessageType{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>jm}])}}const Cp=new Uk;class $k extends S.MessageType{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const Bk=new $k;class Hk extends S.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Bk},{no:2,name:"patch",kind:"message",T:()=>nh}])}}new Hk;class Fk extends S.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>nh}])}}new Fk;class qk extends S.MessageType{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const Wr=new qk;class jk extends S.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageFilters",[{no:1,name:"pinned",kind:"scalar",oneof:"filters",T:8},{no:2,name:"user_id",kind:"scalar",oneof:"filters",T:9}])}}const Gk=new jk;class Wk extends S.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageRoomRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"filters",kind:"message",T:()=>Gk}])}}const Jk=new Wk;class Kk extends S.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Wr},{no:2,name:"next",kind:"scalar",T:8}])}}const zk=new Kk;class Yk extends S.MessageType{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Wr}])}}const Gm=new Yk;class Qk extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const Xk=new Qk;class Zk extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Wr}])}}const Hl=new Zk;class eM extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const tM=new eM;class sM extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Wr}])}}const Fl=new sM;class rM extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}new rM;class iM extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Wr}])}}new iM;class nM extends S.MessageType{constructor(){super("socket.chat.EditChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",opt:!0,T:5},{no:3,name:"payload",kind:"scalar",opt:!0,T:9},{no:4,name:"pinned",kind:"scalar",opt:!0,T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const aM=new nM;class oM extends S.MessageType{constructor(){super("socket.chat.PinChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const cM=new oM;class dM extends S.MessageType{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:4,name:"message",kind:"message",T:()=>Wr}])}}const Dc=new dM;class lM extends S.MessageType{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Wr}])}}const Oc=new lM;class uM extends S.MessageType{constructor(){super("socket.chat.DeleteChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const hM=new uM;class pM extends S.MessageType{constructor(){super("socket.chat.DeleteChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Nc=new pM;class gM extends S.MessageType{constructor(){super("socket.chat.SearchChatMessagesRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"search_term",kind:"scalar",T:9}])}}const mM=new gM;class fM extends S.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"channel_index",kind:"scalar",T:9}])}}new fM;class TM extends S.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new TM;class SM extends S.MessageType{constructor(){super("socket.chat.CreateChatChannelRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8}])}}new SM;class vM extends S.MessageType{constructor(){super("socket.chat.UpdateChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:4,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:5,name:"visibility",kind:"scalar",opt:!0,T:9},{no:6,name:"is_direct_message",kind:"scalar",opt:!0,T:8}])}}new vM;class yM extends S.MessageType{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new yM;class EM extends S.MessageType{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new EM;class PM extends S.MessageType{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Wr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const bM=new PM;class _M extends S.MessageType{constructor(){super("socket.chat.ChatChannel",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8},{no:6,name:"latest_message_and_unread_count",kind:"message",T:()=>bM},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const wM=new _M;class CM extends S.MessageType{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>wM}])}}new CM;class RM extends S.MessageType{constructor(){super("socket.chat.ChannelMember",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const kM=new RM;class MM extends S.MessageType{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>kM}])}}new MM;class IM extends S.MessageType{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const AM=new IM;class DM extends S.MessageType{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const OM=new DM;class NM extends S.MessageType{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const LM=new NM;class VM extends S.MessageType{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const xM=new VM;class UM extends S.MessageType{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const $M=new UM;class BM extends S.MessageType{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const HM=new BM;class FM extends S.MessageType{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const qM=new FM;class jM extends S.MessageType{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}const GM=new jM;class WM extends S.MessageType{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const ah=new WM;class JM extends S.MessageType{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>ah}])}}const Rp=new JM;class KM extends S.MessageType{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>ah}])}}const zM=new KM;class YM extends S.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>ah}])}}const QM=new YM;class XM extends S.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const ZM=new XM;class eI extends S.MessageType{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const ou=new eI;class tI extends S.MessageType{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>ou}])}}const sI=new tI;class rI extends S.MessageType{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const kp=new rI;class iI extends S.MessageType{constructor(){super("socket.plugin.PluginStoreItem",[{no:1,name:"timestamp",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"store_key",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}])}}const nI=new iI;class aI extends S.MessageType{constructor(){super("socket.plugin.PluginStoreResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"store_items",kind:"message",repeat:1,T:()=>nI}])}}const Mp=new aI;class oI extends S.MessageType{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const Ip=new oI;class cI extends S.MessageType{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const Ap=new cI;class dI extends S.MessageType{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Dp=new dI;class lI extends S.MessageType{constructor(){super("socket.livestreaming.StageRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9}])}}const uI=new lI;class hI extends S.MessageType{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>uI}])}}const ql=new hI;class pI extends S.MessageType{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const gI=new pI;class mI extends S.MessageType{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const fI=new mI;class TI extends S.MessageType{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Op=new TI;class SI extends S.MessageType{constructor(){super("socket.polls.Poll",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"created_by",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"question",kind:"scalar",T:9},{no:5,name:"options",kind:"message",repeat:1,T:()=>yI},{no:6,name:"hide_votes",kind:"scalar",T:8},{no:7,name:"anonymous",kind:"scalar",T:8},{no:8,name:"votes",kind:"scalar",repeat:2,T:9}])}}const Wm=new SI;class vI extends S.MessageType{constructor(){super("socket.polls.PollOption",[{no:1,name:"text",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",opt:!0,T:4,L:2},{no:3,name:"votes",kind:"message",repeat:1,T:()=>PI}])}}const yI=new vI;class EI extends S.MessageType{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const PI=new EI;class bI extends S.MessageType{constructor(){super("socket.polls.NewPollRequest",[{no:1,name:"question",kind:"scalar",T:9},{no:2,name:"options",kind:"scalar",repeat:2,T:9},{no:3,name:"anonymous",kind:"scalar",T:8},{no:4,name:"hide_votes",kind:"scalar",T:8},{no:5,name:"created_by",kind:"scalar",opt:!0,T:9},{no:6,name:"created_by_user_id",kind:"scalar",opt:!0,T:9}])}}const _I=new bI;class wI extends S.MessageType{constructor(){super("socket.polls.VotePollRequest",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"index",kind:"scalar",T:4,L:2}])}}const CI=new wI;class RI extends S.MessageType{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Wm}])}}const jl=new RI;class kI extends S.MessageType{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Wm}])}}const MI=new kI;class II extends S.MessageType{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",ji]}])}}const Np=new II;class AI extends S.MessageType{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const t=this.create(),e=Date.now();return t.seconds=S.PbLong.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(S.PbLong.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=S.PbLong.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=S.PbLong.from(t.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(t.nanos>0){let a=(t.nanos+1e9).toString().substring(1);a.substring(3)==="000000"?i="."+a.substring(0,3)+"Z":a.substring(6)==="000"?i="."+a.substring(0,6)+"Z":i="."+a+"Z"}return new Date(r).toISOString().replace(".000Z",i)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+S.typeofJsonValue(t)+".");let i=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let a=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(a))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(a<Date.parse("0001-01-01T00:00:00Z")||a>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=S.PbLong.from(a/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new AI;class DI extends S.MessageType{constructor(){super("common.BaseHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9},{no:11,name:"use_start_session",kind:"scalar",opt:!0,T:8}])}}const cu=new DI;class OI extends S.MessageType{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>cu}])}}new OI;class NI extends S.MessageType{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>cu},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>cu}])}}new NI;const LI=0,VI=1,xI=2,UI=3,$I=5,BI={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToEntity:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43,livestreamingInvoked:44},HI={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},FI={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},qI={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Jm={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,updateConsumersSimulcastConfig:8,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94,audioActivity:100},jI={getUserPresets:0,updateUserPreset:1};function Pc(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Km(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const V=Pc(LI,BI),Oe=Pc(VI,HI),F=Pc(xI,FI),Ns=Pc(UI,qI),yr=Km(Jm,16777216),gs=Km(Jm,50331648),Fc=Pc($I,jI);var GI=Object.defineProperty,WI=Object.getOwnPropertyDescriptor,Jr=(s,t,e,r)=>{for(var i=r>1?void 0:r?WI(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&GI(t,e,i),i},Qt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(Qt||{}),wt,En;class ur{constructor(t,e){g(this,wt,void 0);g(this,En,void 0);m(this,wt,e),m(this,En,t)}get telemetry(){return n(this,En).getValue("telemetry")}get logger(){return n(this,En).getValue("logger")}getChatMessages(){return n(this,wt).sendMessagePromise(Oe.getMessages)}async getChatMessagesPaginated(t,e,r,i){const a={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await n(this,wt).sendMessagePromise(Oe.getPaginatedMessages,Jk.toBinary(a));return o.payload?zk.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};n(this,wt).sendMessage(Oe.sendMessageToRoom,Xk.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};n(this,wt).sendMessage(Oe.sendMessageToPeers,tM.toBinary(i))}sendMessage(t,e,r){if(r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i){const a={chatId:t,payloadType:r,payload:e};i!==void 0&&(a.pinned=i);const o=await n(this,wt).sendMessagePromise(Oe.editMessage,aM.toBinary(a));return Oc.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await n(this,wt).sendMessagePromise(Oe.deleteMessage,hM.toBinary(e));return{id:Nc.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,a,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(a=e.limit)!=null?a:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await n(this,wt).sendMessagePromise(Oe.searchChannelMessages,mM.toBinary(r));return Gm.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await n(this,wt).sendMessagePromise(Oe.pinMessage,cM.toBinary(r));return Dc.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Oe.sendMessageToRoom:{r=Hl.fromBinary.bind(Hl),i=Hl.create();break}case Oe.sendMessageToPeers:{r=Fl.fromBinary.bind(Fl),i=Fl.create();break}case Oe.editMessage:{r=Oc.fromBinary.bind(Oc),i=Oc.create();break}case Oe.pinMessage:{r=Dc.fromBinary.bind(Dc),i=Dc.create();break}case Oe.deleteMessage:{r=Nc.fromBinary.bind(Nc),i=Nc.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}n(this,wt).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}wt=new WeakMap,En=new WeakMap;Jr([y.trace("SocketService.getChatMessages")],ur.prototype,"getChatMessages",1);Jr([y.trace("SocketService.getChatMessagesPaginated")],ur.prototype,"getChatMessagesPaginated",1);Jr([y.trace("SocketService.sendMessageToRoom")],ur.prototype,"sendMessageToRoom",1);Jr([y.trace("SocketService.sendMessageToPeers")],ur.prototype,"sendMessageToPeers",1);Jr([y.trace("SocketService.sendMessage")],ur.prototype,"sendMessage",1);Jr([y.trace("SocketService.editMessage")],ur.prototype,"editMessage",1);Jr([y.trace("SocketService.deleteMessage")],ur.prototype,"deleteMessage",1);Jr([y.trace("SocketService.searchMessages")],ur.prototype,"searchMessages",1);function JI(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function ks(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>ks(e));const t={};return Object.keys(s).forEach(e=>{const r=nr.validate(e)?e:JI(e);t[r]=ks(s[e])}),t}function KI(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function zm(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>zm(e));const t={};return Object.keys(s).forEach(e=>{const r=nr.validate(e)?e:KI(e);t[r]=s[e]}),t}function nd(s,t={}){return s==null?{}:(Object.getOwnPropertyNames(s).forEach(e=>{if(typeof s[e]!="function"){if(typeof s[e]=="object"){nd(s[e],t[e]={});return}t[e]=s[e]}}),t)}class du extends Error{constructor(e){var t=(...args)=>{super(...args);h(this,"status");h(this,"response");h(this,"isTimeout")};e instanceof Error?(t(e.message),this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(t(`Request failed with status ${e.status}`),this.status=e.status,this.response=e,this.isTimeout=!1),this.name="RequestError"}get isHttpError(){return this.status!==void 0}get isNetworkError(){return this.status===void 0&&!this.isTimeout}}class Lp{constructor(t){h(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const a=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{a.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${a.toString()}`}return i}async request(t){var p;const e=((p=t.method)==null?void 0:p.toUpperCase())||"GET",r=this.buildURL(t.url||"",t.params),i={...this.defaults.headers.common,...t.headers};e!=="GET"&&e!=="HEAD"&&t.data&&!i["Content-Type"]&&(i["Content-Type"]="application/json");const o=i["Content-Type"]==="application/json"?JSON.stringify(t.data):t.data,c={method:e,headers:i,body:e!=="GET"&&e!=="HEAD"&&t.data?o:void 0},d=t.timeout||this.defaults.timeout,l=t.retry!==void 0?t.retry:this.defaults.retry,u=t.retryDelay||this.defaults.retryDelay;try{const f=new AbortController,T=setTimeout(()=>f.abort(),d);c.signal=f.signal;const E=await fetch(r,c);clearTimeout(T);let b=null;const _=E.headers.get("content-type");_&&_.includes("application/json")?b=await E.json():b=await E.text();const k={};E.headers.forEach((x,N)=>{k[N]=x});const A={data:b,status:E.status,statusText:E.statusText,headers:k,config:t};if(!E.ok)throw A;return A}catch(f){if(f instanceof Error&&l>0)return await new Promise(T=>setTimeout(T,u)),this.defaults.baseURL===ri.apiBase.prod?this.defaults.baseURL=ri.apiBase.prodAlternate:this.defaults.baseURL===ri.apiBase.prodAlternate&&(this.defaults.baseURL=ri.apiBase.prod),this.request({...t,retry:l-1});throw f}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const zI=3,YI=30,QI=8e3;class XI{constructor(t,e){h(this,"fetchClient");h(this,"requests");h(this,"roomName");h(this,"roomUUID");h(this,"authToken");h(this,"organizationId");h(this,"iceServers");h(this,"pluginInformation");h(this,"userDetails");h(this,"roomDetails");h(this,"context");this.context=t;const{timeout:r=QI,retry:i=zI,retryDelay:a=YI,baseURL:o=ri.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new Lp({baseURL:o,timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.fetchClient=new Lp({baseURL:"",timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var f,T,E,b,_;const p=t.getValue("telemetry");try{p.injectContext(this.requests.defaults.headers.common);const k=await l(u);return u.url!==p.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:k.status,statusText:k.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),k}catch(k){if(!k)throw new C("Unknown network error occurred","0011");if(k instanceof C||k instanceof du)throw k;((f=k.config)==null?void 0:f.url)!==p.logsEndpoint&&this.logger.error("xhr::fetch",{error:k,networkCall:{status:k.status,statusText:k.statusText,baseURL:((T=k.config)==null?void 0:T.baseURL)||this.requests.defaults.baseURL,url:(E=k.config)==null?void 0:E.url,retries:(b=k.config)==null?void 0:b.retry,method:(_=k.config)==null?void 0:_.method,isOnline:navigator.onLine?"online":"offline"}});const A=k instanceof Error&&k.message||"Network request failed";throw new C(A,"0011"),new du(k)}}}get peerId(){return this.context.getValue("peerId")}get logger(){return this.context.getValue("logger")}setAuthToken(t,e){const{bearer:r}=e||{};this.authToken=t,this.requests.defaults.headers.common.Authorization=r?`Bearer ${t}`:t}setHeader(t,e){this.requests.defaults.headers.common[t]=e}setRoomName(t){this.roomName=t}setRoomUUID(t){this.roomUUID=t}setOrganizationId(t){this.organizationId=t}}var ZI=Object.defineProperty,eA=Object.getOwnPropertyDescriptor,As=(s,t,e,r)=>{for(var i=r>1?void 0:r?eA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZI(t,e,i),i};class Ss extends XI{constructor(e,r){super(e,r);h(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(await this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r}async getPlugins(){var a,o,c,d,l;if(this.pluginInformation)return this.pluginInformation;const{plugins:e}=(await this.requests.get("/v2/plugins/user")).data.data,r=m_,i=e.reduce((u,p)=>(u[r.includes(p.id)?"v1":"v2"].push({...p,name:p.name.replace("v2","")}),u),{v1:[],v2:[]});return(c=(o=(a=this.context.getValue("modules"))==null?void 0:a.devTools)==null?void 0:o.plugins)!=null&&c.length&&((l=(d=this.context.getValue("modules"))==null?void 0:d.devTools)==null||l.plugins.forEach(u=>{var f,T,E;const p={...Fa,tags:[...Fa.tags],baseUrl:`http://localhost:${u.port}`,name:u.name,picture:(f=u.picture)!=null?f:Fa.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:u.id,organizationId:this.organizationId,description:(T=u.description)!=null?T:Fa.description,staggered:(E=u.staggered)!=null?E:Fa.staggered};i.v2.push(p)})),i.v2}async getPluginDetails(e){const{plugin:r}=(await this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r}async getPluginConfig(e){return(await this.fetchClient.get(`${e}/dyte-config.json`)).data}async authorizePlugin(e){const r={peerId:this.peerId},{token:i}=(await this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return i}async getPresignedUrls(e){const r=ya(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:a,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:a,putLocation:o}}async uploadFile(e,r){if(navigator.isReactNative&&"uri"in e)try{await fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){this.logger.error(`sendFileMessage::${i}`)}else await this.fetchClient.put(r,e,{headers:{"Content-Type":e.type}})}async startLivestreaming({manualIngestion:e}){const r=ks(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!e})).data.data;return{playbackUrl:r.playbackUrl,status:r.status,manualIngest:r.manualIngest,ingestionCredentials:r.streamKey?{ingestionServer:r.ingestServer,streamKey:r.streamKey}:null}}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const e=ks((await this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{playbackUrl:e.playbackUrl,status:e.status,manualIngest:e.manualIngest,ingestionCredentials:e.streamKey?{ingestionServer:e.ingestServer,streamKey:e.streamKey}:null}}async getUserDetails(){if(this.userDetails)return this.userDetails;const e=(await this.requests.get("v2/internals/participant-details")).data.data;return ks(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...zm(e),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r})).data.data.id}async updateRecording(e,r){return this.requests.put(`v2/recordings/${e}`,{action:r})}async getActiveRecording(){const{status:e,id:r}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}}async getActiveTranscript(){const{transcript_download_url:e}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.fetchClient.get(e)).data}}catch(r){throw new C("Cant fetch transcript s3 url","1801")}}}As([y.trace("APIClient.getICEServers")],Ss.prototype,"getICEServers",1);As([y.trace("APIClient.getPlugins")],Ss.prototype,"getPlugins",1);As([y.trace("APIClient.startLivestreaming")],Ss.prototype,"startLivestreaming",1);As([y.trace("APIClient.stopLivestreaming")],Ss.prototype,"stopLivestreaming",1);As([y.trace("APIClient.getActiveLivestream")],Ss.prototype,"getActiveLivestream",1);As([y.trace("APIClient.getUserDetails")],Ss.prototype,"getUserDetails",1);As([y.trace("APIClient.startRecording")],Ss.prototype,"startRecording",1);As([y.trace("APIClient.stopRecording")],Ss.prototype,"updateRecording",1);As([y.trace("APIClient.getActiveRecording")],Ss.prototype,"getActiveRecording",1);As([y.trace("APIClient.getActiveTranscript")],Ss.prototype,"getActiveTranscript",1);let lu;function tA(s,t){return lu=new Ss(s,t),lu}function ht(){return lu}const ba={maxInvocations:5,period:1};function Et(s,t){return function(e,r,i){const a=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),u=t?this[t]:s;if(l-c>u.period*1e3&&(c=l,o=0),o>=u.maxInvocations)throw new C(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,a.apply(this,d)},i}}var sA=Object.defineProperty,rA=Object.getOwnPropertyDescriptor,vs=(s,t,e,r)=>{for(var i=r>1?void 0:r?rA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&sA(t,e,i),i};const iA=["text","image","file","custom","poll"],qc={maxInvocations:180,period:60};var Z,ni,$e,Pn,md,Ym,fo,uu,Qp;let Ot=(Qp=class extends Lt{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,md);g(this,fo);h(this,"messages");g(this,Z,void 0);g(this,ni,void 0);g(this,$e,void 0);g(this,Pn,void 0);h(this,"maxTextLimit",2e3);m(this,Pn,t),m(this,$e,e),m(this,Z,r),m(this,ni,i),this.messages=[]}get telemetry(){return n(this,Pn).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e){switch(t.type){case"text":{await this.sendTextMessageInternal(t.message,e);break}case"image":await this.sendImageMessageInternal(t.image,e);break;case"file":await this.sendFileMessageInternal(t.file,e);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e){var i,a,o,c,d,l;if(t.length>this.maxTextLimit)throw new C("Max character limit breached","0503");if(e&&e.length>0){if(!((i=n(this,Z).permissions)!=null&&i.chatPrivate.canSend)||!((a=n(this,Z).permissions)!=null&&a.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((c=(o=n(this,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=n(this,Z).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new C("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(n(this,Z).id),r=n(this,ni).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(n(this,Z).userId)),n(this,$e).sendMessage(t,Qt.TEXT,e)}async sendImageMessageInternal(t,e){var i,a,o,c,d,l;if(e&&e.length>0){if(!((i=n(this,Z).permissions)!=null&&i.chatPrivate.canSend)||!((a=n(this,Z).permissions)!=null&&a.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=n(this,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=n(this,Z).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:t.type}});return}try{const u=ht(),{getLocation:p,putLocation:f}=await u.getPresignedUrls(t.name);await u.uploadFile(t,f);let T=[];e&&e.length>0&&(e.push(n(this,Z).id),T=n(this,ni).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),T.push(n(this,Z).userId)),n(this,$e).sendMessage(p,Qt.IMAGE,e)}catch(u){throw new C("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,a,o,c,d;if(e&&e.length>0){if(!((r=n(this,Z).permissions)!=null&&r.chatPrivate.canSend)||!((i=n(this,Z).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(a=n(this,Z).permissions)==null?void 0:a.chatPublic)!=null&&o.canSend)||!((d=(c=n(this,Z).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=ht(),{getLocation:u,putLocation:p}=await l.getPresignedUrls(t.name);await l.uploadFile(t,p);let f=[];e&&e.length>0&&(e.push(n(this,Z).id),f=n(this,ni).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),f.push(n(this,Z).userId));const T=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});n(this,$e).sendMessage(T,Qt.FILE,e)}catch(l){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return qc}updateRateLimits(t,e){qc.maxInvocations=t,qc.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var a,o,c,d,l,u,p,f,T,E,b,_,k,A,x;if(e&&e.length>0){if(!((a=n(this,Z).permissions)!=null&&a.chatPrivate.canSend)||!((o=n(this,Z).permissions)!=null&&o.chatPrivate.files)||!((c=n(this,Z).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=n(this,Z).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((p=(u=n(this,Z).permissions)==null?void 0:u.chatPublic)!=null&&p.files)||!((T=(f=n(this,Z).permissions)==null?void 0:f.chatPublic)!=null&&T.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async N=>{try{if(typeof N=="string")return{link:N};const $=ht(),{getLocation:K,putLocation:Y}=await $.getPresignedUrls(N.name);return await $.uploadFile(N,Y),{link:K,type:N.type,name:N.name,size:N.size}}catch($){throw new C("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((b=(E=t.files)!=null?E:[])==null?void 0:b.map(async N=>r(N))),images:await Promise.all((k=(_=t.images)!=null?_:[])==null?void 0:k.map(async N=>r(N))),videos:await Promise.all((x=(A=t.videos)!=null?A:[])==null?void 0:x.map(async N=>r(N)))};n(this,$e).sendMessage(JSON.stringify(i),Qt.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,Z).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(a=n(this,Z).permissions)==null?void 0:a.chatPublic)!=null&&o.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}n(this,$e).editMessage(t,e,Qt.TEXT)}async editImageMessage(t,e){var i,a,o,c;if(!((a=(i=n(this,Z).permissions)==null?void 0:i.chatPublic)!=null&&a.canSend)||!((c=(o=n(this,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:e.type}});return}try{const d=ht(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),n(this,$e).editMessage(t,l,Qt.IMAGE)}catch(d){throw new C("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,Z).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(a=n(this,Z).permissions)==null?void 0:a.chatPublic)!=null&&o.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=ht(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),n(this,$e).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Qt.FILE)}catch(c){throw new C("Error editing file message.","0500",this.logger)}}async editMessage(t,e){switch(e.type){case"text":{this.editTextMessage(t,e.message);break}case"image":{this.editImageMessage(t,e.image);break}case"file":{this.editFileMessage(t,e.file);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t){n(this,$e).deleteMessage(t)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!n(this,fo,uu))throw new C("Can`t pin message without joining room","0505");try{await n(this,$e).setPinState(t,!0)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!n(this,fo,uu))throw new C("Can`t unpin message without joining room","0505");try{await n(this,$e).setPinState(t,!1)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,$e).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>Xt.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await n(this,$e).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>Xt.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,$e).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>Xt.formatSocketPeerMessage(o))}async getMessages(t,e,r,i=0){const a=await n(this,$e).getChatMessagesPaginated(t,e,r);return{messages:a.messages.map(o=>Xt.formatSocketPeerMessage(o)),next:a.next}}async searchMessages(t,e){throw new C("searchMessages is disabled! Please use `fetchPublicMessages` method instead.","0506")}get pinned(){return this.messages.filter(t=>t.pinned)}},Z=new WeakMap,ni=new WeakMap,$e=new WeakMap,Pn=new WeakMap,md=new WeakSet,Ym=function(){return n(this,Pn).getValue("connectionHandler")},fo=new WeakSet,uu=function(){return n(this,md,Ym).socketJoined===!0},Qp);vs([y.trace("Chat.sendTextMessage"),Et(qc)],Ot.prototype,"sendTextMessage",1);vs([y.trace("Chat.sendImageMessage"),Et({maxInvocations:20,period:60})],Ot.prototype,"sendImageMessage",1);vs([y.trace("Chat.sendFileMessage"),Et({maxInvocations:20,period:60})],Ot.prototype,"sendFileMessage",1);vs([y.trace("Chat.sendMessage"),Et({maxInvocations:180,period:60})],Ot.prototype,"sendMessage",1);vs([y.trace("Chat.editTextMessage")],Ot.prototype,"editTextMessage",1);vs([y.trace("Chat.editImageMessage")],Ot.prototype,"editImageMessage",1);vs([y.trace("Chat.editFileMessage")],Ot.prototype,"editFileMessage",1);vs([y.trace("Chat.editMessage")],Ot.prototype,"editMessage",1);vs([y.trace("Chat.deleteMessage")],Ot.prototype,"deleteMessage",1);vs([y.trace("Chat.searchMessages")],Ot.prototype,"searchMessages",1);Ot=vs([rt("0500")],Ot);var nA=Object.defineProperty,aA=Object.getOwnPropertyDescriptor,oA=(s,t,e,r)=>{for(var i=r>1?void 0:r?aA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&nA(t,e,i),i},ai,Xp;const fr=(Xp=class{constructor(s,t,e,r){h(this,"chat");h(this,"chatSocketHandler");h(this,"self");g(this,ai,void 0);m(this,ai,s),this.chatSocketHandler=t,this.chat=new Ot(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return n(this,ai).getValue("telemetry")}get logger(){return n(this,ai).getValue("logger")}static async init(s,t,e,r){return new fr(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:iA[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case Qt.TEXT:{e.message=s.payload;break}case Qt.IMAGE:{e.link=s.payload;break}case Qt.FILE:{const{link:r,name:i,size:a}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=a;break}case Qt.CUSTOM:{const{html:r,images:i,message:a,videos:o,files:c}=JSON.parse(s.payload);e.message=a,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return fr.formatMessage(e)}async getChatMessages(){if(this.self.config.viewType==="LIVESTREAM")return;const s=await this.chatSocketHandler.getChatMessages();if(!(s!=null&&s.payload))return;const t=Gm.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>fr.formatSocketPeerMessage(e))}setupEvents(){n(this,ai).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Oe.sendMessageToRoom,s=>{if(!s.message)return;const t=fr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Oe.sendMessageToPeers,s=>{const t=fr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Oe.editMessage,s=>{if(!s.message)return;const t=fr.formatSocketPeerMessage(s.message),e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t),this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Oe.deleteMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);let e={id:s.chatId};t!==-1&&([e]=this.chat.messages.splice(t,1)),this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Oe.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=fr.formatSocketPeerMessage(s.message);t!==-1&&(this.chat.messages[t]=e),this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}),s.pinned?this.chat.emit("pinMessage",{message:e,messages:this.chat.messages}):this.chat.emit("unpinMessage",{message:e,messages:this.chat.messages})})}},ai=new WeakMap,Xp);let Xt=fr;oA([y.trace("ChatController.setupEvents")],Xt.prototype,"setupEvents",1);var cA=Object.defineProperty,dA=Object.getOwnPropertyDescriptor,lA=(s,t,e,r)=>{for(var i=r>1?void 0:r?dA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&cA(t,e,i),i},fd,Qm,Td,Xm,bn,_n,To,Zp;let hu=(Zp=class extends Lt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,fd);g(this,Td);h(this,"items");g(this,bn,void 0);g(this,_n,void 0);g(this,To,void 0);m(this,To,t),m(this,bn,e),m(this,_n,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!n(this,Td,Xm))throw new C("Can't create polls without joining room","0705");if(!n(this,bn).permissions.polls.canCreate){this.logger.error("Polls::create::permission_denied");return}if(!t||!e){this.logger.error("Polls::question_and_options_can_not_be_empty",{polls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){this.logger.error("Polls::there_must_be_at_least_two_options",{polls:{hasQuestion:!!t,optionsLength:e.length}});return}await n(this,_n).createPoll(t,e,r,i)}async vote(t,e){if(!n(this,bn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await n(this,_n).votePoll(t,e)}},fd=new WeakSet,Qm=function(){return n(this,To).getValue("connectionHandler")},Td=new WeakSet,Xm=function(){var t;return((t=n(this,fd,Qm))==null?void 0:t.socketJoined)===!0},bn=new WeakMap,_n=new WeakMap,To=new WeakMap,Zp);hu=lA([rt("0700")],hu);var uA=Object.defineProperty,hA=Object.getOwnPropertyDescriptor,pA=(s,t,e,r)=>{for(var i=r>1?void 0:r?hA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uA(t,e,i),i},Pr,wn,oi,eg;const sn=(eg=class{constructor(s,t,e){h(this,"polls");g(this,Pr,void 0);g(this,wn,void 0);g(this,oi,void 0);this.polls=new hu(s,t,e),m(this,wn,t),m(this,Pr,s),m(this,oi,e),this.setupEvents()}get telemetry(){return n(this,Pr).getValue("telemetry")}get logger(){return n(this,Pr).getValue("logger")}static async init(s,t,e){return new sn(s,t,e)}canViewPolls(){return n(this,wn).permissions.polls.canView}setupEvents(){const s={[Ns.createPoll]:r=>{r.poll&&this.updatePoll(sn.formatSocketServicePoll(r.poll))},[Ns.updatePoll]:r=>{r.poll&&this.updatePoll(sn.formatSocketServicePoll(r.poll))},[Ns.votePoll]:r=>{r.poll&&this.updatePoll(sn.formatSocketServicePoll(r.poll))}},t=()=>{n(this,Pr).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,oi).on(r,s[r])})},e=()=>{n(this,Pr).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,oi).removeListeners(r)})};n(this,wn).permissions.on("permissionsUpdate",async r=>{var i;r!=null&&r.polls&&((i=r==null?void 0:r.polls)!=null&&i.canView?(await this.getPolls(),t()):(this.polls.items=[],e()))}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await n(this,oi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=MI.fromBinary(s.payload);this.polls.items=t.map(e=>sn.formatSocketServicePoll(e))}static formatSocketServicePoll(s){const t=s.options.map(e=>({count:e.count,text:e.text,votes:e.votes.map(r=>({id:r.userId,name:r.name}))}));return{anonymous:s.anonymous,createdBy:s.createdBy,createdByUserId:s.createdByUserId,hideVotes:s.hideVotes,id:s.pollId,options:t,question:s.question,voted:s.votes}}},Pr=new WeakMap,wn=new WeakMap,oi=new WeakMap,eg);let Zm=sn;pA([y.trace("PollController.setupEvents")],Zm.prototype,"setupEvents",1);var gA=Object.defineProperty,mA=Object.getOwnPropertyDescriptor,fA=(s,t,e,r)=>{for(var i=r>1?void 0:r?mA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&gA(t,e,i),i},ef=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(ef||{}),Cn,So,gu,ci,vo,tg;let pu=(tg=class extends Lt{constructor(t,e,r,i,a){const o=t.getValue("logger");super(o);g(this,So);h(this,"selfActiveTab");h(this,"broadcastTabChanges");g(this,Cn,void 0);g(this,ci,void 0);g(this,vo,void 0);h(this,"viewType");h(this,"meetingStartedTimestamp");h(this,"meetingTitle");h(this,"sessionId");m(this,Cn,t),m(this,ci,e),this.viewType=r,m(this,vo,i),this.meetingTitle=a,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return n(this,So,gu).socketState}get mediaState(){return n(this,So,gu).mediaState}get meetingId(){return n(this,Cn).getValue("meetingId")}setBroadcastTabChanges(t){if(!n(this,ci).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new C("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=n(this,ci).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){n(this,vo).broadcastMessage("spotlight",{userId:n(this,ci).userId,currentTab:this.selfActiveTab})}},Cn=new WeakMap,So=new WeakSet,gu=function(){return n(this,Cn).getValue("connectionHandler")},ci=new WeakMap,vo=new WeakMap,tg);pu=fA([rt("0800")],pu);function TA(s){let t="",e=[""];const r=[e];let i=0,a=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
|
|
7
|
+
`&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++a]=[c=""],i=0):e[i]+=c,t=c;return r}var SA=Object.defineProperty,vA=Object.getOwnPropertyDescriptor,tf=(s,t,e,r)=>{for(var i=r>1?void 0:r?vA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&SA(t,e,i),i},yo,sg;let jr=(sg=class extends Lt{constructor(t){const e=t.getValue("logger");super(e);h(this,"transcripts");g(this,yo,void 0);m(this,yo,t),this.transcripts=[]}get telemetry(){return n(this,yo).getValue("telemetry")}static async init(t,e){const r=new jr(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(a){i.error("Error fetching active transcriptions ",a)}return r}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,a,o,c,d]]=TA(t);return{id:nr.v4(),name:c,peerId:i,userId:a,customParticipantId:o,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
|
|
8
|
+
`).map(e=>jr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=ht(),{transcript:e}=await t.getActiveTranscript();this.transcripts=jr.parseTranscripts(e)}catch(t){}}async onTranscript(t){var r;const e=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((r=e==null?void 0:e.at(-1))!=null&&r.isPartialTranscript){const i=e.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)}},yo=new WeakMap,sg);tf([y.trace("Ai.getActiveTranscript")],jr.prototype,"getActiveTranscript",1);jr=tf([rt("0000")],jr);var yA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,PA=(s,t,e,r)=>{for(var i=r>1?void 0:r?EA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&yA(t,e,i),i},br,Rn,Ct,rg;const sf=(rg=class{constructor(s,t,e,r,i,a){h(this,"meta");h(this,"ai");g(this,br,void 0);g(this,Rn,void 0);h(this,"aiSocketHandler");g(this,Ct,void 0);m(this,Ct,s),this.meta=new pu(s,t,t.config.viewType,e,a),this.ai=r,m(this,br,t),m(this,Rn,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return n(this,Ct).getValue("telemetry")}get logger(){return n(this,Ct).getValue("logger")}static async init(s,t,e,r,i){const a=await jr.init(s,t.permissions.transcriptionEnabled);return new sf(s,t,e,a,r,i)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,ef.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){n(this,Ct).getValue("peerSessionStore").on(w.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),n(this,Ct).getValue("peerSessionStore").on(w.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),n(this,Ct).getValue("peerSessionStore").on(w.ROOM_STATE,({createdAt:s,roomUuid:t})=>{const e=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!e){const r=new Date(s*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),n(this,Ct).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),n(this,br).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&n(this,Rn).broadcastMessage("spotlight",{userId:n(this,br).userId,currentTab:this.meta.selfActiveTab})),n(this,Ct).getValue("peerSessionStore").on(w.PEER_JOINED_INTERNAL,async s=>{n(this,br).permissions.canSpotlight&&this.meta.selfActiveTab&&n(this,Rn).broadcastToPeers("spotlight",[s.id],{userId:n(this,br).userId,currentTab:this.meta.selfActiveTab})}),n(this,Ct).getValue("peerSessionStore").on(w.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),n(this,Ct).getValue("peerSessionStore").on(w.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),this.aiSocketHandler.on(V.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=jr.parseTranscript(e,r)}catch(d){this.logger.error(`Failed to parse transcript: ${e}`,d)}if(!i){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(i),this.meta.emit("transcript",i);const{peerId:a,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${a} - ${o}: ${c}`)})}},br=new WeakMap,Rn=new WeakMap,Ct=new WeakMap,rg);let rf=sf;PA([y.trace("MetaController.setupEvents")],rf.prototype,"setupEvents",1);const ja={},hr={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,a)=>{const o=a.value;return a.value=function(...d){var E,b;const l=(b=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.authToken))!=null?b:"",u=`${t}-${l}`,p=this==null?void 0:this.logger;if(ja[u]){const _=new Error(`Unsupported concurrent calls on method: ${s}.`);throw _.name="UnsupportedConcurrentMethodExecution",p==null||p.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:_.stack},locker:{methodName:s,lockName:u}}),_}ja[u]=!0;const f=setTimeout(()=>delete ja[u],e),T=o.apply(this,d);return Promise.resolve(T).then(()=>{delete ja[u],clearTimeout(f)}).catch(()=>{delete ja[u],clearTimeout(f)}),T},a}}};var bA=Object.defineProperty,_A=Object.getOwnPropertyDescriptor,Qi=(s,t,e,r)=>{for(var i=r>1?void 0:r?_A(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&bA(t,e,i),i},Ft,Sd,ee,Eo,Es,Be,Po,mu,kn,jc;class Kr extends Lt{constructor(e,r,i,a,o){const c=e.getValue("logger");super(c);g(this,Po);g(this,kn);g(this,Ft,void 0);g(this,Sd,void 0);g(this,ee,void 0);g(this,Eo,void 0);g(this,Es,void 0);g(this,Be,void 0);m(this,Be,e),m(this,Ft,a),m(this,Sd,o),m(this,ee,r),m(this,Eo,i),m(this,Es,[]),this.setupEvents()}get telemetry(){return n(this,Be).getValue("telemetry")}get status(){return n(this,Be).getValue("stageStatus")}setupEvents(){const e={[w.GET_STAGE_REQUESTS]:async a=>{m(this,Es,a)},[w.UPDATE_STAGE_REQUESTS]:async({add:a})=>{const o=n(this,Es).length,{stageRequests:c}=this.getAccessRequests();(a||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([a,o])=>{n(this,Be).getValue("peerSessionStore").onAsync(a,o)})},i=()=>{Object.entries(e).forEach(([a,o])=>{n(this,Be).getValue("peerSessionStore").removeListener(a,o)})};n(this,ee).permissions.on("permissionsUpdate",a=>{const{canAcceptProductionRequests:o}=a;o!==void 0&&(n(this,ee).permissions.acceptStageRequests?(r(),n(this,Ft).getStageRequests()):(i(),m(this,Es,[]),this.emit("stageAccessRequestUpdate",n(this,Es))))}),n(this,ee).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ee).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new C("You do not have permission to perform this action","2001");const e=n(this,Eo).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return m(this,Es,e),{stageRequests:n(this,Es)}}async requestAccess(){if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`,"2006");if(n(this,ee).permissions.stageAccess===H.Allowed){L(this,kn,jc).call(this,"ACCEPTED_TO_JOIN_STAGE");return}n(this,Ft).requestAccess(),L(this,kn,jc).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");n(this,Ft).cancelRequestAccess(),L(this,kn,jc).call(this,"OFF_STAGE")}grantAccess(e){if(!n(this,ee).roomJoined)throw new C("Can`t grant for participant without joining room");if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ee).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new C("You do not have permission to perform this action","2001");return n(this,Ft).grantAccess(e)}denyAccess(e){if(!n(this,ee).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ee).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new C("You do not have permission to perform this action","2001");return n(this,Ft).denyAccess(e)}get peerId(){return n(this,Be).getValue("peerId")}async join(){const e=n(this,Be).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||n(this,ee).permissions.stageAccess===H.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`,"2006");if(n(this,Be).setValue("stageStatus","ON_STAGE",!1),await n(this,Ft).joinStage(),e===rr.Livestream){await n(this,Be).getValue("selfController").joinRoom();return}n(this,Be).notify("stageStatus"),n(this,ee).audioEnabled&&n(this,Po,mu).shareMic(n(this,ee).audioTrack),n(this,ee).videoEnabled&&n(this,Po,mu).shareWebcam(n(this,ee).videoTrack)}async leave(){if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`,"2006");n(this,ee).setIsPinned(!1),n(this,Be).setValue("stageStatus","OFF_STAGE",!1),await n(this,Ft).leaveStage(n(this,ee).userId);try{await n(this,Be).getValue("peerSessionStore").emitAsync(w.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}n(this,Be).notify("stageStatus")}async kick(e){if(!n(this,ee).roomJoined)throw new C("Can`t kick participant without joining room","2005");if(!n(this,ee).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ee).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new C("You do not have permissions for kick","2001");return n(this,Ft).kick(e)}}Ft=new WeakMap,Sd=new WeakMap,ee=new WeakMap,Eo=new WeakMap,Es=new WeakMap,Be=new WeakMap,Po=new WeakSet,mu=function(){return n(this,Be).getValue("roomNodeClient")},kn=new WeakSet,jc=async function(e){this.status!==e&&n(this,Be).setValue("stageStatus",e)};Qi([y.trace("Stage.getStageRequests")],Kr.prototype,"getAccessRequests",1);Qi([y.trace("Stage.requestAccess")],Kr.prototype,"requestAccess",1);Qi([y.trace("Stage.cancelRequestAccess")],Kr.prototype,"cancelRequestAccess",1);Qi([y.trace("Stage.grantAccess")],Kr.prototype,"grantAccess",1);Qi([y.trace("Stage.denyAccess")],Kr.prototype,"denyAccess",1);Qi([hr.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),y.trace("Stage.joinStage")],Kr.prototype,"join",1);Qi([y.trace("Stage.leaveStage")],Kr.prototype,"leave",1);function wA(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function oh(s){switch(s){case er.UNSPECIFIED:return"OFF_STAGE";case er.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case er.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case er.OFF_STAGE:return"OFF_STAGE";case er.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var CA=Object.defineProperty,RA=Object.getOwnPropertyDescriptor,kA=(s,t,e,r)=>{for(var i=r>1?void 0:r?RA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&CA(t,e,i),i},_r,ns,wr,bo,nt;class nf{constructor(t,e,r,i,a){h(this,"stage");g(this,_r,void 0);g(this,ns,void 0);g(this,wr,void 0);g(this,bo,0);g(this,nt,void 0);m(this,nt,t),this.stage=new Kr(t,i,a,e,r),m(this,wr,e),m(this,_r,i),m(this,ns,a),this.setupEvents()}get telemetry(){return n(this,nt).getValue("telemetry")}get logger(){return n(this,nt).getValue("logger")}setupEvents(){n(this,nt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),n(this,wr).on(V.grantStageAccess,()=>{n(this,_r).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),n(this,wr).on(V.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===n(this,_r).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),n(this,wr).on(V.denyStageAccess,()=>{n(this,_r).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),n(this,wr).on(V.getStageRequests,async t=>{var r;if(n(this,_r).permissions.stageAccess!==H.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await n(this,nt).getValue("peerSessionStore").emitAsync(w.GET_STAGE_REQUESTS,e),n(this,bo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),m(this,bo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return n(this,ns).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&n(this,nt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=oh(t.stageType),r=n(this,nt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:n(this,nt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:n(this,nt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=n(this,ns).joined.get(t.peerId),r=n(this,ns).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&n(this,nt).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:n(this,ns).viewMode,page:n(this,ns).currentPage});break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&n(this,nt).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:n(this,ns).viewMode,page:n(this,ns).currentPage});break}n(this,nt).getValue("peerSessionStore").emit(w.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}_r=new WeakMap,ns=new WeakMap,wr=new WeakMap,bo=new WeakMap,nt=new WeakMap;kA([y.trace("Stage.setupEvents")],nf.prototype,"setupEvents",1);var MA=Object.defineProperty,IA=Object.getOwnPropertyDescriptor,El=(s,t,e,r)=>{for(var i=r>1?void 0:r?IA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&MA(t,e,i),i};const _e={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};var Qe,Rt,Mn,In,$s,An,Cr,Dn,ig;let Ea=(ig=class extends Pa{constructor(t,{baseURL:e,createdAt:r,description:i,id:a,name:o,organizationId:c,picture:d,private:l,published:u,staggered:p,tags:f,type:T,updatedAt:E},b,_,k,A,x){const N=t.getValue("logger");super(N);g(this,Qe,void 0);h(this,"baseURL");h(this,"createdAt");h(this,"description");h(this,"id");h(this,"name");g(this,Rt,void 0);g(this,Mn,void 0);g(this,In,void 0);h(this,"organizationId");h(this,"picture");h(this,"private");h(this,"published");h(this,"staggered");h(this,"tags");h(this,"type");h(this,"updatedAt");g(this,$s,void 0);h(this,"config");g(this,An,void 0);h(this,"active");h(this,"iframes");h(this,"enabledBy");g(this,Cr,void 0);g(this,Dn,void 0);m(this,Cr,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=a,this.name=o,m(this,Rt,_),this.organizationId=c,this.picture=d,this.private=l,this.published=u,this.staggered=p,this.tags=f,this.type=T,this.updatedAt=new Date(E),this.active=!1,this.iframes=new Map,m(this,Qe,b),m(this,Mn,k),m(this,In,A),this.enabledBy="",m(this,Dn,x)}get telemetry(){return n(this,Cr).getValue("telemetry")}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}async handleIframeMessage(t){var o;if(!this.active)return;const e=t,{payload:r,uuid:i,type:a}=e;switch(a){case F.customPluginEventToRoom:{n(this,Qe).customPluginEventToRoom(this.id,r,i);break}case F.customPluginEventToPeers:{n(this,Qe).customPluginEventToPeers(this.id,r.peerIds,r,i);break}case F.enablePluginForRoom:{n(this,Qe).enablePluginForRoom(this.id,i);break}case F.enablePluginForPeers:{n(this,Qe).enablePluginForPeers(this.id,r.peerIds,i);break}case F.disablePluginForRoom:{n(this,Qe).disablePluginForRoom(this.id,i);break}case F.disablePluginForPeers:{n(this,Qe).disablePluginForPeers(this.id,r.peerIds,i);break}case F.storeInsertKeys:{n(this,Qe).storeInsertKeys(this.id,r.store,r.insertKeys,i);break}case F.storeGetKeys:{n(this,Qe).storeGetKeys(this.id,r.store,r.getKeys,i);break}case F.storeDeleteKeys:{n(this,Qe).storeDeleteKeys(this.id,r.store,r.deleteKeys,i);break}case F.storeDelete:{n(this,Qe).storeDelete(this.id,r.store,i);break}case _e.chatMessage:{const{messagePayload:c,peerIds:d}=r;if(!n(this,In)){this.sendIframeEvent({type:_e.chatMessage,uuid:e.uuid,payload:{error:"Chat is disabled for this room."}});return}try{await n(this,In).sendMessage(c,d),this.sendIframeEvent({type:_e.chatMessage,uuid:e.uuid,payload:{success:!0}})}catch(l){this.sendIframeEvent({type:_e.chatMessage,uuid:e.uuid,payload:{error:l}})}break}case _e.getPeer:{let c;const{peerId:d}=r,l={...n(this,Rt),id:n(this,Rt).id,isRecorder:(o=n(this,Rt).permissions)==null?void 0:o.isRecorder,isHidden:n(this,Rt).permissions.hiddenParticipant,stageStatus:n(this,Rt).stageStatus};d?(c=n(this,Mn).joined.get(r.peerId),n(this,Rt).id===d&&(c=l)):c=l,this.sendIframeEvent({type:_e.getPeer,payload:{peer:c&&nd(c)},uuid:e.uuid});break}case _e.getPeers:{const c=n(this,Mn).joined.toArray().map(d=>nd(d));this.sendIframeEvent({type:_e.getPeers,payload:{peers:c},uuid:e.uuid});break}case _e.getPluginInitiator:{this.sendIframeEvent({type:_e.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:e.uuid});break}case _e.getDisplayTitle:{this.sendIframeEvent({type:_e.getDisplayTitle,payload:{displayTitle:n(this,Dn)},uuid:e.uuid});break}case _e.getRoomName:{this.sendIframeEvent({type:_e.getRoomName,payload:{roomName:n(this,Cr).getValue("meetingId")},uuid:e.uuid});break}case _e.customPluginEventToParent:{this.emit(e.payload.eventName,e.payload.data);break}}}sendData(t){this.active&&(this.logger.info("Plugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:_e.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var i;const{iframe:e,listener:r}=(i=this.iframes.get(t))!=null?i:{};(e||r)&&(navigator.isReactNative?e.props.onMessage=void 0:window.removeEventListener("message",r),this.iframes.delete(t))}addPluginView(t,e="default"){var o;if(!n(this,An))throw this.logger.error("Plugin::addPluginView::no_auth_token_set_for_plugin"),new C("No auth token set for plugin.","0602");if(!t)throw this.logger.error("Plugin::addPluginView::iframe_was_not_provided"),new C("Iframe was not provided.","0603");this.removePluginView(e);const r=t,i=new URL(this.baseURL),a={auth:n(this,An),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:n(this,Cr).getValue("apiBase"),pluginId:this.id,roomName:(o=n(this,Cr).getValue("meetingId"))!=null?o:"",displayTitle:n(this,Dn)};if(Object.keys(a).forEach(c=>{i.searchParams.set(c,a[c])}),r.src=i.href,r.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",r.title=e,navigator.isReactNative)r.props.onMessage=c=>{this.handleIframeMessage(JSON.parse(c.nativeEvent.data))},this.iframes.set(e,{iframe:r});else{const c=async d=>{d.source===t.contentWindow&&await this.handleIframeMessage(d.data)};window.addEventListener("message",c),this.iframes.set(e,{iframe:r,listener:c})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}async activateForSelf(){const t=ht(),e=await t.authorizePlugin(this.id);m(this,An,e),m(this,$s,new Date);try{const r=await t.getPluginConfig(this.baseURL);this.config=r}catch(r){this.logger.error("Plugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),m(this,$s,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}async enable(){return this.activateForSelf()}disable(){return this.deactivateForSelf()}async activate(){var t,e;this.active||(e=(t=n(this,Rt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(n(this,Qe).addPlugin(this.id,this.staggered),m(this,$s,new Date),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))}async deactivate(){var t,e;this.active&&(!((e=(t=n(this,Rt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==n(this,Rt).id||(n(this,Qe).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:n(this,$s)?new Date().getTime()-n(this,$s).getTime():0}}),m(this,$s,void 0)))}},Qe=new WeakMap,Rt=new WeakMap,Mn=new WeakMap,In=new WeakMap,$s=new WeakMap,An=new WeakMap,Cr=new WeakMap,Dn=new WeakMap,ig);El([Et({maxInvocations:5,period:1})],Ea.prototype,"sendData",1);El([y.trace("Plugin.activatePlugin")],Ea.prototype,"activate",1);El([y.trace("Plugin.deactivatePlugin")],Ea.prototype,"deactivate",1);Ea=El([rt("0600")],Ea);var Me,di;class af extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:a,onClearEvent:o}=e;super();g(this,Me,void 0);g(this,di,void 0);h(this,"onAddEvent");h(this,"onDeleteEvent");h(this,"onClearEvent");m(this,Me,new Pa(r)),this.onAddEvent=i,this.onDeleteEvent=a,this.onClearEvent=o,m(this,di,new Map)}emit(e,...r){return n(this,Me).emit(e,...r)}on(e,r){return n(this,Me).on(e,r)}addListener(e,r){return n(this,Me).addListener(e,r)}off(e,r){return n(this,Me).off(e,r)}once(e,r){return n(this,Me).once(e,r)}prependListener(e,r){return n(this,Me).prependListener(e,r)}prependOnceListener(e,r){return n(this,Me).prependOnceListener(e,r)}removeListener(e,r){return n(this,Me).removeListener(e,r)}removeAllListeners(e){return n(this,Me).removeAllListeners(e)}listeners(e){return n(this,Me).listeners(e)}listenerCount(e){return n(this,Me).listenerCount(e)}getMaxListeners(){return n(this,Me).getMaxListeners()}setMaxListeners(e){return n(this,Me).setMaxListeners(e)}eventNames(){return n(this,Me).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const a=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return n(this,di).set(e,o),r.on("*",o),i&&n(this,Me).emit(this.onAddEvent,r),a}delete(e,r=!0,i=!1){const a=this.get(e);if(!a)return!1;a.removeListener("*",n(this,di).get(e));const o=super.delete(e);return i&&a.removeAllListeners(),r&&n(this,Me).emit(this.onDeleteEvent,a),o}clear(e=!0,r=!1){this.forEach(a=>{a.removeListener("*",n(this,di).get(a.id)),r&&a.removeAllListeners()});const i=super.clear();return e&&n(this,Me).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Me=new WeakMap,di=new WeakMap;class Vp extends af{constructor(t){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"},t)}add(t,e=!0){return super.add(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var AA=Object.defineProperty,DA=Object.getOwnPropertyDescriptor,OA=(s,t,e,r)=>{for(var i=r>1?void 0:r?DA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&AA(t,e,i),i};let fu=class{constructor(s){h(this,"all");h(this,"active");this.all=new Vp(s),this.active=new Vp(s)}};fu=OA([rt("0600")],fu);var NA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,Pl=(s,t,e,r)=>{for(var i=r>1?void 0:r?LA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&NA(t,e,i),i},qt,On,as,ng;const of=(ng=class{constructor(s,t,e,r){h(this,"plugins");g(this,qt,void 0);g(this,On,void 0);g(this,as,void 0);m(this,qt,t),m(this,On,e),m(this,as,s),this.plugins=r,this.setupEvents()}get telemetry(){return n(this,as).getValue("telemetry")}get logger(){return n(this,as).getValue("logger")}static async init(s,t,e,r,i,a,o,c){const d=s.getValue("logger"),l=new fu(d);return t.forEach(u=>{const p=new Ea(s,u,e,a,o,i,c);l.all.add(p)}),new of(s,e,r,l)}async getRoomPlugins(){var t;const{plugins:s}=await n(this,qt).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(e=>{this.disablePlugin({id:e.id})}),await Promise.all(s.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))}async enablePlugin({id:s,enabledBy:t}){const e=this.plugins.all.get(s);e&&(await e.activateForSelf(),e.enabledBy=t)}async disablePlugin({id:s}){const t=this.plugins.all.get(s);t&&t.deactivateForSelf()}sendIframeEvent(s,t,e,r){const i=this.plugins.all.get(t);i&&i.sendIframeEvent({type:s,uuid:e,payload:r})}broadcastIframeEvent(s,t){this.plugins.active.forEach(e=>{this.sendIframeEvent(s,e.id,"",t)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),n(this,as).getValue("peerSessionStore").onAsync(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{await this.getRoomPlugins(),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")}),n(this,qt).on(F.addPlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active||await this.enablePlugin({id:t,enabledBy:s.enabledBy})}),n(this,qt).on(F.removePlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active&&await this.disablePlugin({id:t})}),[F.enablePluginForPeers,F.enablePluginForRoom].forEach(s=>{n(this,qt).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{enabledBy:t.enabledBy})})}),[F.disablePluginForPeers,F.disablePluginForRoom].forEach(s=>{n(this,qt).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{disabledBy:t.disabledBy})})}),[F.customPluginEventToPeers,F.customPluginEventToRoom].forEach(s=>{n(this,qt).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{data:JSON.parse(new TextDecoder().decode(t.pluginData))})})}),[F.storeInsertKeys,F.storeGetKeys,F.storeDeleteKeys].forEach(s=>{n(this,qt).on(s,async(t,e)=>{var i;const r=(i=t.storeItems)==null?void 0:i.map(a=>{var o;return{timestamp:a.timestamp,peerId:a.peerId,payload:JSON.parse((o=a.payload)!=null&&o.length?new TextDecoder().decode(a.payload):"{}"),key:a.storeKey}});this.sendIframeEvent(s,t.pluginId,e,{storeName:t.storeName,storeItems:r})})}),n(this,qt).on(F.storeDelete,async(s,t)=>{this.sendIframeEvent(F.storeDelete,s.pluginId,t,{storeName:s.storeName})}),n(this,On).on(Oe.sendMessageToPeers,s=>{const t=Xt==null?void 0:Xt.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(_e.chatMessage,{message:t})}),n(this,On).on(Oe.sendMessageToRoom,s=>{const t=Xt==null?void 0:Xt.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(_e.chatMessage,{message:t})}),n(this,as).getValue("peerSessionStore").on(w.PEER_JOINED_INTERNAL,s=>{const t=nd(s);this.broadcastIframeEvent(_e.peerJoined,t)}),n(this,as).getValue("peerSessionStore").on(w.PEER_CLOSED,s=>{this.broadcastIframeEvent(_e.peerLeft,s)}),n(this,as).getValue("peerSessionStore").on(w.UPDATE_PEER_STAGE_STATUS,s=>{this.broadcastIframeEvent(_e.peerStageStatusUpdate,s)}),n(this,as).subscribe("stageStatus",s=>{this.broadcastIframeEvent(_e.stageStatusUpdate,s)})}},qt=new WeakMap,On=new WeakMap,as=new WeakMap,ng);let bc=of;Pl([y.trace("PluginController.getRoomPlugins")],bc.prototype,"getRoomPlugins",1);Pl([y.trace("PluginController.enableForSelf")],bc.prototype,"enablePlugin",1);Pl([y.trace("PluginController.disableForSelf")],bc.prototype,"disablePlugin",1);Pl([y.trace("PluginController.setupEvents")],bc.prototype,"setupEvents",1);var _o;class VA{constructor(t){h(this,"mediaJoined");h(this,"socketJoined");h(this,"socketJoinAttempted");h(this,"mediaJoinAttempted");h(this,"socketState");h(this,"mediaState");g(this,_o,void 0);this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0},m(this,_o,t)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(t,e){let r;const{reconnected:i}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(n(this,_o).getValue("peerSessionStore").emit(w.SOCKET_STATE_UPDATE,r),this.socketState=r)}}_o=new WeakMap;var xA=Object.defineProperty,UA=Object.getOwnPropertyDescriptor,_c=(s,t,e,r)=>{for(var i=r>1?void 0:r?UA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xA(t,e,i),i},Nn,Ln,Vn,Gc,ag;let Ji=(ag=class extends Lt{constructor(t,e){const r=t.getValue("logger");super(r);g(this,Vn);g(this,Nn,void 0);g(this,Ln,void 0);h(this,"recordingPeerIds",[]);h(this,"recordings",[]);m(this,Ln,t),m(this,Nn,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}get telemetry(){return n(this,Ln).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!n(this,Nn).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new C("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw this.logger.error("Recording::start::recording_in_progress",{recording:{state:this.recordingState}}),new C(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=ht(),{recording:r={}}=n(this,Ln).getValue("defaults"),i=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("Recording::stop::recording_failed_to_start",{error:e}),new C("Error while starting recording","1000",this.logger)}}async stop(t){await L(this,Vn,Gc).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await L(this,Vn,Gc).call(this,"pause",["RECORDING"],t)}async resume(t){await L(this,Vn,Gc).call(this,"resume",["PAUSED"],t)}},Nn=new WeakMap,Ln=new WeakMap,Vn=new WeakSet,Gc=async function(t,e,r){if(!n(this,Nn).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new C("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const a=this.recordings.find(o=>o.id===r);if(a===void 0)throw new C("Could not find the specified recording","1004");if(e.includes(a.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:a.state}});return}i.push(a)}else i=this.recordings.filter(a=>e.includes(a.state));i.forEach(async a=>{const o=a.state;t==="stop"&&(a.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await ht().updateRecording(a.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),a.state!==o&&(a.state=o,this.emit("recordingUpdate",o)),new C("Error while stopping recording","1000",this.logger)}})},ag);_c([y.trace("Recording.start")],Ji.prototype,"start",1);_c([y.trace("Recording.stop")],Ji.prototype,"stop",1);_c([y.trace("Recording.stop")],Ji.prototype,"pause",1);_c([y.trace("Recording.stop")],Ji.prototype,"resume",1);Ji=_c([rt("1000")],Ji);var $A=Object.defineProperty,BA=Object.getOwnPropertyDescriptor,HA=(s,t,e,r)=>{for(var i=r>1?void 0:r?BA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&$A(t,e,i),i},li;class cf{constructor(t,e,r){h(this,"recording");h(this,"room");g(this,li,void 0);m(this,li,t),this.recording=new Ji(t,e),this.room=r,this.setupEvents()}get telemetry(){return n(this,li).getValue("telemetry")}get logger(){return n(this,li).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case ji.BROWSER:e="BROWSER";break;case ji.COMPOSITE:e="COMPOSITE";break;case ji.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){n(this,li).getValue("peerSessionStore").on(w.ROOM_STATE,t=>{t.activeRecordings.length!==0?this.recording.updateRecordings(t.activeRecordings.map(e=>{const r=this.getRecordingTypeFromProtoType(e.recordingType);return{id:e.recordingId,state:e.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(V.recordingStarted,t=>{let e=!1;const r=[...this.recording.recordings];if(r.forEach(i=>{i.id===t.recordingId&&(e=!0,i.state="RECORDING")}),e===!1){const i=this.getRecordingTypeFromProtoType(t.recordingType);r.push({id:t.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(r)}),this.room.on(V.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(V.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}li=new WeakMap;HA([y.trace("RecordingController.setupEvents")],cf.prototype,"setupEvents",1);var ui;class FA{constructor(t){g(this,ui,void 0);m(this,ui,t)}hasFeature(t){return n(this,ui).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return n(this,ui).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return n(this,ui).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}ui=new WeakMap;class ch{constructor(t,e,r,i){h(this,"authToken");h(this,"logger");h(this,"features");h(this,"browserSpecs");h(this,"callStats");this.authToken=t,this.logger=e,this.features=r,this.browserSpecs=ge,this.callStats=i}static init(t){return new ch(t.getValue("authToken"),t.getValue("logger"),new FA(t),t.getValue("callstats"))}}class dh{constructor(t){h(this,"internals");this.internals=t}static async init(t){const e=ch.init(t);return new dh(e)}}var qA=Object.defineProperty,jA=Object.getOwnPropertyDescriptor,Vt=(s,t,e,r)=>{for(var i=r>1?void 0:r?jA(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&qA(t,e,i),i},Le,he,oe,Bs,jt,wo,be;class Pt extends Pa{constructor(e,r,i=ad,a=!0){const o=e.getValue("logger");super(o);g(this,Le,void 0);g(this,he,void 0);g(this,oe,void 0);g(this,Bs,void 0);g(this,jt,void 0);g(this,wo,void 0);g(this,be,void 0);h(this,"audioUpdateInProgress");h(this,"videoUpdateInProgress");m(this,be,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,m(this,Le,new df(e,r)),m(this,he,new p0(e,n(this,Le),void 0,i)),m(this,oe,new y0(e,n(this,Le),void 0,i)),m(this,jt,new T0(n(this,be),n(this,Le))),m(this,Bs,new m0(e,n(this,Le))),m(this,wo,a),n(this,he).on("trackMuted",this.onAudioTrackMuted.bind(this)),n(this,he).on("trackChanged",this.onAudioTrackChanged.bind(this)),n(this,oe).on("trackChanged",this.onVideoTrackChanged.bind(this)),n(this,oe).on("trackEnded",this.onVideoTrackEnded.bind(this)),n(this,jt).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return n(this,be).getValue("telemetry")}set context(e){m(this,be,e)}async onVisibilityChange(){n(this,be).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?n(this,be).getValue("callstats").browserBackgrounded():(n(this,be).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?n(this,be).getValue("callstats").audioOn():n(this,be).getValue("callstats").audioOff(),r?n(this,be).getValue("callstats").videoOn():n(this,be).getValue("callstats").videoOff();let i,a;if(e&&r)try{const c=await n(this,Le).getAudioAndVideoTrack(n(this,he).userSelectedDevice,n(this,oe).userSelectedDevice);i=c.audioTrack,a=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await n(this,Le).getAudioTrack(!1,n(this,he).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!a&&r)try{a=await n(this,Le).getVideoTrack(n(this,oe).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&n(this,be).getValue("callstats").audioOff(),r&&!a&&n(this,be).getValue("callstats").videoOff(),await n(this,he).setMediaTrack(i),await n(this,oe).setMediaTrack(a);try{await this.setupSpeaker()}catch(c){}if(a){const c=await this.getDeviceById(a.getSettings().deviceId);n(this,be).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);n(this,be).getValue("callstats").selectedDevice("AUDIO",c)}(o=n(this,Bs).currentDevice)!=null&&o.deviceId&&n(this,be).getValue("callstats").selectedDevice("SPEAKER",n(this,Bs).currentDevice),n(this,Le).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:n(this,he).currentDevice,video:n(this,oe).currentDevice,speaker:n(this,Bs).currentDevice}}get permissions(){return n(this,Le).permissions}getAllDevices(){return n(this,Le).getAvailableDevices()}getDeviceById(e,r){return n(this,Le).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return n(this,he).mediaTrack}get audioTrack(){return n(this,he).transformedMediaTrack}get audioEnabled(){return n(this,he).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await n(this,he).enableTrack(!1,e):await n(this,he).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){n(this,he).mediaTrack&&!n(this,he).isCustomTrack?n(this,he).muteTrack():n(this,he).disableTrack()}getAudioDevices(e){return n(this,Le).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await n(this,he).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,be).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await n(this,Bs).setPreferredSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})}async setSpeakerDevice(e,{saveDevicePreference:r}){await n(this,Bs).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,be).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return n(this,oe).mediaTrack}get videoTrack(){return n(this,oe).transformedMediaTrack}get videoEnabled(){return n(this,oe).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await n(this,oe).enableTrack(!1,e):await n(this,oe).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){n(this,oe).disableTrack()}getVideoDevices(e){return n(this,Le).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await n(this,oe).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,be).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await n(this,oe).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:n(this,jt).audioMediaTrack,video:n(this,jt).videoMediaTrack}}get screenShareEnabled(){return n(this,jt).trackEnabled}async enableScreenShare(){await n(this,jt).enableScreenShare()}async disableScreenShare(){n(this,jt).disableScreenShare()}async updateScreenshareConstraints(e){await n(this,jt).updateConstraints(e)}getSpeakerDevices(e){return n(this,Le).getAudioOutputDevices(e)}addAudioMiddleware(e){return n(this,he).addMiddleware(e)}removeAudioMiddleware(e){return n(this,he).removeMiddleware(e)}removeAllAudioMiddlewares(){return n(this,he).removeAllMiddlewares()}addVideoMiddleware(e){return n(this,oe).addMiddleware(e)}removeVideoMiddleware(e){return n(this,oe).removeMiddleware(e)}removeAllVideoMiddlewares(){return n(this,oe).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return n(this,oe).setVideoMiddlewareGlobalConfig(e)}destruct(){n(this,he).disableTrack(),n(this,oe).disableTrack(),n(this,oe).terminateMiddlewareWebWorker(),n(this,jt).disableScreenShare(),n(this,Le).destruct()}async onDeviceChange(e,r){var a,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!n(this,wo))return;let i=!1;(a=e==null?void 0:e.added)==null||a.reverse().forEach(async c=>{var d;c&&!ad(c)&&(c.kind==="audioinput"&&((d=this.audioTrack)==null?void 0:d.enabled)===!0?await this.setAudioDevice(c,{saveDevicePreference:!1}):c.kind==="audiooutput"&&(i=!0,await this.setSpeakerDevice(c,{saveDevicePreference:!1})))}),i||(o=e==null?void 0:e.removed)==null||o.forEach(async c=>{var d;if(c.kind==="audiooutput"&&((d=this.getCurrentDevices().speaker)==null?void 0:d.deviceId)===c.deviceId){const l=await this.getSpeakerDevices();(l==null?void 0:l.length)>0&&await this.setSpeakerDevice(l[0],{saveDevicePreference:!1})}})}removeAllTracks(){this.destruct()}removeAudioTrack(){n(this,he).disableTrack()}removeVideoTrack(){n(this,oe).disableTrack(),n(this,oe).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Le=new WeakMap,he=new WeakMap,oe=new WeakMap,Bs=new WeakMap,jt=new WeakMap,wo=new WeakMap,be=new WeakMap;Vt([y.trace("MediaHandler.setupStreams")],Pt.prototype,"setupStreams",1);Vt([y.trace("MediaHandler.enableAudio")],Pt.prototype,"enableAudio",1);Vt([y.trace("MediaHandler.disableAudio")],Pt.prototype,"disableAudio",1);Vt([y.trace("MediaHandler.setAudioDevice")],Pt.prototype,"setAudioDevice",1);Vt([y.trace("MediaHandler.enableVideo")],Pt.prototype,"enableVideo",1);Vt([y.trace("MediaHandler.disableVideo")],Pt.prototype,"disableVideo",1);Vt([y.trace("MediaHandler.setVideoDevice")],Pt.prototype,"setVideoDevice",1);Vt([y.trace("MediaHandler.updateVideoConstraints")],Pt.prototype,"updateVideoConstraints",1);Vt([y.trace("MediaHandler.enableScreenShare")],Pt.prototype,"enableScreenShare",1);Vt([y.trace("MediaHandler.disableScreenShare")],Pt.prototype,"disableScreenShare",1);Vt([y.trace("MediaHandler.updateScreenshareConstraints")],Pt.prototype,"updateScreenshareConstraints",1);Vt([y.trace("MediaHandler.destruct")],Pt.prototype,"destruct",1);Vt([y.trace("MediaHandler.onDeviceChange")],Pt.prototype,"onDeviceChange",1);function Lc(s,t,e){switch(!0){case ge.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case ge.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case ge.isFirefox():switch(t){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const GA=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function ad(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=ge._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:GA.some(i=>t==null?void 0:t.includes(i))}async function WA(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,a=await Promise.all(t==null?void 0:t.map(d=>d(i))),o=i.createMediaStreamSource(new MediaStream([e])),c=i.createMediaStreamDestination();try{let d=o;for(let l=0;l<a.length;l+=1)d.connect(a[l]),d=a[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}var hi,Co;class JA{constructor(t){g(this,hi,void 0);g(this,Co,void 0);m(this,Co,t)}get logger(){return n(this,Co).getValue("logger")}terminateMiddlewareWebWorker(){if(n(this,hi))try{Uc.clearInterval(n(this,hi)),m(this,hi,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),a=await Promise.all(t==null?void 0:t.map(f=>f({canvas:i,WorkerTimers:Uc})));if(r.disablePerFrameCanvasRendering){const T=i.captureStream().getVideoTracks()[0];return Object.defineProperty(T,"originalSettings",{value:e.getSettings()}),T}const o=document.createElement("video"),c=new MediaStream;c.addTrack(e);const d=i.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let f=0;f<a.length;f+=1)typeof a[f]=="function"&&await a[f](i,d)}catch(f){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:f})}};try{o.play()}catch(f){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,m(this,hi,Uc.setInterval(l,50))},!1);const p=i.captureStream().getVideoTracks()[0];return Object.defineProperty(p,"originalSettings",{value:e.getSettings()}),p}}hi=new WeakMap,Co=new WeakMap;const KA={qvga:{width:{ideal:320},height:{ideal:240},frameRate:{ideal:30}},vga:{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30}},hd:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},fhd:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},uhd:{width:{ideal:3840},height:{ideal:2160},frameRate:{ideal:30}}},zA=[[320,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[640,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[1280,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[1920,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[3840,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]]],YA=(s,t)=>{var d,l,u;const e=(d=s==null?void 0:s.getValue("overrides"))==null?void 0:d.simulcastConfig;if((l=e==null?void 0:e.encodings)!=null&&l.length)return e.encodings;const r="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((u=t.originalSettings)==null?void 0:u.width),i=zA,a=i.map(([p])=>p).sort((p,f)=>p-f);let o=Number.MAX_VALUE,c=0;return a.forEach((p,f)=>{Math.abs(p-r)<o&&(o=Math.abs(p-r),c=f)}),i[c][1]};var Ee=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Ee||{});const QA=A_(),en=ks(QA.config.media);function XA(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}var pi,vd;class ZA{constructor(t,e){g(this,pi,void 0);g(this,vd,void 0);h(this,"getScreenShareConstraints",()=>{var l,u,p,f,T,E,b,_,k;const t=(l=n(this,pi))==null?void 0:l.screenshare,e=(p=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?p:1920,r=(T=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?T:1080,i=(b=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?b:5,a=(k=(_=t==null?void 0:t.frameRate)==null?void 0:_.ideal)!=null?k:5,o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;let d={width:{max:e},height:{max:r},frameRate:{ideal:a,max:i}};return o!==void 0&&["monitor","browser","window"].includes(o)&&(d={...d,displaySurface:o}),c!==void 0&&(d={...d,selfBrowserSurface:c}),{audio:!0,video:d}});h(this,"getAudioConstraints",t=>{var a,o,c,d,l,u,p;const e={},r=(a=n(this,pi))==null?void 0:a.audio,i=r!=null&&r.enableStereo?2:1;return ge.isFirefox()||ge.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(o=r==null?void 0:r.autoGainControl)!=null?o:!0,echoCancellation:(c=r==null?void 0:r.echoCancellation)!=null?c:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:i},e):(e.audio={autoGainControl:(l=r==null?void 0:r.autoGainControl)!=null?l:!0,echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0,noiseSuppression:(p=r==null?void 0:r.noiseSupression)!=null?p:!0,channelCount:i},t&&(e.audio.deviceId={exact:t}),e)});h(this,"getVideoConstraints",t=>{var o,c,d;const e={},r=(o=n(this,pi))==null?void 0:o.video,i=JP(KA);let a=i.vga;if(typeof r=="string"){const l=i[r];l&&(a=l)}else r!==void 0&&(a.height.ideal=r.height.ideal,a.width.ideal=r.width.ideal,a.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=a,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});m(this,vd,t),m(this,pi,e)}getUpdatedVideoConstraints(t){return t}}pi=new WeakMap,vd=new WeakMap;class Gl extends Error{constructor(e,r,i){super(r);h(this,"constraints");h(this,"name");this.name=e,this.constraints=i}}class e0{constructor(){h(this,"permissions");this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}async getAudioInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audioinput")}async getVideoInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="videoinput")}async getAudioOutputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audiooutput")}}var t0=Object.defineProperty,s0=Object.getOwnPropertyDescriptor,ys=(s,t,e,r)=>{for(var i=r>1?void 0:r?s0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&t0(t,e,i),i},xn,Gt,He,og;let Nt=(og=class extends e0{constructor(t,e){super();g(this,xn,void 0);g(this,Gt,void 0);g(this,He,void 0);m(this,He,t),m(this,Gt,new ZA(t,e)),m(this,xn,new AbortController)}get telemetry(){return n(this,He).getValue("telemetry")}get logger(){return n(this,He).getValue("logger")}get constraintsBuilder(){return n(this,Gt)}async destruct(){var t;(t=n(this,xn))==null||t.abort()}handlePermissionErrors(t,e){const r=Lc(t,e.name,e.message);return this.permissions[t]=r,n(this,He).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,a,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(k=>k.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const p=!!(d!=null&&d.find(k=>k.deviceId===e));let f;e&&p?f=e:d&&((a=d[0])!=null&&a.deviceId)&&(f=(o=d[0])==null?void 0:o.deviceId);const T={audio:n(this,Gt).getAudioConstraints(u).audio,video:n(this,Gt).getVideoConstraints(f).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(T)});const E=await navigator.mediaDevices.getUserMedia(T);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(T)});const b=E.getAudioTracks()[0];let _=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",_.label.includes("OBS Virtual")){const A=(await this.getVideoInputDevices()).find(x=>x.label.includes("OBS Virtual"));_=await this.getVideoTrack(A.deviceId)}return n(this,He).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),n(this,He).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:b,videoTrack:_}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new C("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",n(this,He).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let a;e&&i?a=e:(c=r[0])!=null&&c.deviceId&&(a=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(f=>f.deviceId!==l),u=n(this,Gt).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[p]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),p}catch(p){const f=Lc("audio",p.name,p.message),T=new Gl(p.name,p.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw T;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const b=n(this,Gt).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(b)}),o(E.deviceId)}throw T}};try{const l=await o(a);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",n(this,He).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new C(l.message,"1601")}}async getVideoTrack(t){var c,d,l;const e=(c=await this.getCurrentDeviceLabel(t))==null?void 0:c.includes("OBS Virtual"),r=await this.getVideoInputDevices();if(!(r!=null&&r.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",n(this,He).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available","1607");const i=!!(r!=null&&r.find(u=>u.deviceId===t));let a;t&&i?a=t:(d=r[0])!=null&&d.deviceId&&(a=(l=r[0])==null?void 0:l.deviceId);const o=async u=>{try{let p=u;const{video:f}=p;e&&typeof f!="boolean"&&(p={video:{deviceId:f.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(p)});const[T]=(await navigator.mediaDevices.getUserMedia(p)).getVideoTracks();if(e&&typeof f!="boolean"&&typeof f.width=="object"){const{width:E,height:b}=T.getSettings(),{ideal:_}=f.width;T.applyConstraints({width:{ideal:_},height:{ideal:Math.floor(b*_/E)},frameRate:f.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(p)}),T}catch(p){const f=Lc("video",p.name,p.message),T=new Gl(p.name,p.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw T;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const b=n(this,Gt).getVideoConstraints(E.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(b)}),o({video:b.video})}throw T}};try{const u=n(this,Gt).getVideoConstraints(a),p=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",n(this,He).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),p}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new C(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),n(this,He).getValue("callstats").screenShareRequested();const r=await navigator.mediaDevices.getDisplayMedia(e);return this.logger.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const i=Lc("video",r.name,r.message),a=new Gl(r.name,r.message,e),o={video:!0};if(t_(e,o))throw a;if(i==="COULD_NOT_START")return t(o);throw a}};try{const e=n(this,Gt).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",n(this,He).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new C(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const a=((o=i.label)==null?void 0:o.toLowerCase())||"";return ad(i)?4:a.includes("airpods")||a.includes("airdopes")||a.includes("bluetooth")||a.includes("wireless")||a.includes("headphones")||a.includes("headset")||a.includes("earbuds")||a.includes("usb")||a.includes("external")?0:i.deviceId==="default"||a.includes("default")?1:a.includes("built-in")||a.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const a=((o=i.label)==null?void 0:o.toLowerCase())||"";return a.includes("front")||a.includes("user")||a.includes("selfie")?!0:!(a.includes("back")||a.includes("rear")||a.includes("environment"))};return t.sort((i,a)=>{var u,p;const o=e(i),c=e(a);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=a.deviceId==="default"||((p=a.label)==null?void 0:p.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&a.kind==="videoinput"){const f=r(i),T=r(a);if(f&&!T)return-1;if(!f&&T)return 1}return 0})}async getAvailableDevices(){try{return await this.enumerateDevicesWithExternalFirst()||[]}catch(t){return this.logger.error("enumerate_devices_failed",{error:t}),[]}}async getAvailableDevicesByKind(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(({kind:e})=>t===e)}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get available devices by kind","1609")}}async getDevice(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(r=>r.deviceId===t)[0]}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get device","1609")}}async onDeviceChange(t){if(ge.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;const i=p=>`${p.kind}-${p.label}-${p.deviceId}-${p.groupId}`,a=new Set(e.map(p=>i(p))),o=await this.getAvailableDevices(),c=new Set(o.map(p=>i(p))),d={added:o.filter(p=>!a.has(i(p))),removed:e.filter(p=>!c.has(i(p))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(u=d.removed)!=null&&u.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const p=[...d.added,...d.removed];p.some(f=>f.kind==="audioinput")&&n(this,He).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&n(this,He).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&n(this,He).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(f=>f.kind==="audiooutput")),t(r,d,!1)}},{signal:n(this,xn).signal})}}},xn=new WeakMap,Gt=new WeakMap,He=new WeakMap,og);ys([y.trace("WebMediaInterface.destruct")],Nt.prototype,"destruct",1);ys([y.trace("WebMediaInterface.handlePermissionErrors")],Nt.prototype,"handlePermissionErrors",1);ys([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Nt.prototype,"getAudioAndVideoTrack",1);ys([y.trace("WebMediaInterface.getAudioTrack")],Nt.prototype,"getAudioTrack",1);ys([y.trace("WebMediaInterface.getVideoTrack")],Nt.prototype,"getVideoTrack",1);ys([y.trace("WebMediaInterface.getScreenShareTracks")],Nt.prototype,"getScreenShareTracks",1);ys([y.trace("WebMediaInterface.getAvailableDevices")],Nt.prototype,"getAvailableDevices",1);ys([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Nt.prototype,"getAvailableDevicesByKind",1);ys([y.trace("WebMediaInterface.getDevice")],Nt.prototype,"getDevice",1);ys([y.trace("WebMediaInterface.onDeviceChange")],Nt.prototype,"onDeviceChange",1);Nt=ys([rt("1600")],Nt);const df=Nt,Gi={setItem:(s,t,e)=>{try{localStorage.setItem(s,t)}catch(r){e==null||e.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:s,value:t}})}},getItem:(s,t)=>{try{return localStorage.getItem(s)}catch(e){t==null||t.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:s}})}return null}},r0=(s=0)=>new Promise(t=>setTimeout(t,s)),i0=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),a=s.createAnalyser();a.fftSize=2048,i.connect(a);const o=new Uint8Array(a.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(a.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):r0().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},n0=typeof AudioContext!="undefined"?AudioContext:null;class lh{constructor(t){h(this,"_AudioContext");h(this,"audioContext");h(this,"_audioContextRefContainers");const e={AudioContext:n0,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:lh}})}getOrCreate(t){if(!this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.add(t),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(e){}return this.audioContext}release(t){this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.delete(t),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const xp=new lh,a0=3,o0=250;function c0(s){const t={},e=xp.getOrCreate(t);let r=a0;function i(){return r-=1,i0(e,s.srcObject,o0).then(a=>a?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{xp.release(t)})}async function Up(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const a=e.play();a&&await a,i=await c0(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(a){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:a})}finally{e.pause(),e.remove()}return i}var d0=Object.defineProperty,l0=Object.getOwnPropertyDescriptor,lf=(s,t,e,r)=>{for(var i=r>1?void 0:r?l0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&d0(t,e,i),i};let od=class extends Pa{constructor(t,e,r,i){var o;const a=t.getValue("logger");super(a);h(this,"constructorName",this.constructor.name);h(this,"userSelectedDevice");h(this,"mediaInterface");h(this,"isNonPreferredDevice");h(this,"_mediaTrack");h(this,"transformedMediaTrack");h(this,"middlewares",[]);h(this,"currentDevice");h(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);h(this,"setUserPreferredDevice",t=>Gi.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>Gi.getItem(this.userPreferredDeviceKey,this.logger));h(this,"isCustomTrack",!1);h(this,"context");this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(o=this.getUserPreferredDevice())!=null?o:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}async setMediaTrack(t,e=!1){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=await this.conditionallyChangeTrack(t,e),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){r(i)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new C("Failed to unmute track","1611")}}getCurrentDeviceId(){var e;const{kind:t}=this.mediaTrack;switch(t){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((e=i==null?void 0:i.advanced)==null?void 0:e[0].deviceId)||"default":this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}async setCurrentDevice(){var e;if(!this.mediaTrack){this.currentDevice=void 0;return}const t=this.getCurrentDeviceId();((e=this.currentDevice)==null?void 0:e.deviceId)!==t&&(this.currentDevice=await this.mediaInterface.getDevice(t))}async setDevice(t,{saveDevicePreference:e}){if(!t)throw this.logger.warn(`${this.constructorName}.setDevice No device received`),new C("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(ge.isWebKitBased()&&!(ge.isSafari()&&f_.test(ge.getVersion())))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return this.logger.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return this.logger.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}}async removeAllMiddlewares(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return this.logger.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};lf([y.trace("BaseMediaHandler.unmuteTrack")],od.prototype,"unmuteTrack",1);od=lf([rt("1600")],od);const uf=od;var u0=Object.defineProperty,h0=Object.getOwnPropertyDescriptor,uh=(s,t,e,r)=>{for(var i=r>1?void 0:r?h0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&u0(t,e,i),i};const Wl="[Realtimekit]nonSilentDeviceLabels";class bl extends uf{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new C("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new C("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,this.userSelectedDevice))}catch(e){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new C(e.message,"1604")}}async enableTrack(t,e){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(e){this.isCustomTrack=!0,await this.setMediaTrack(e,!0);return}this.isCustomTrack=!1;const r=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(r)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await WA(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t,e=!1){var d;if(!t||this.userSelectedDevice||e)return t;let r=t;const i=await this.mediaInterface.getAudioInputDevices(),a=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(a!=null&&a.length))return r;a.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,a[0].deviceId));const o=JSON.parse(Gi.getItem(Wl,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await Up(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return Gi.setItem(Wl,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return a.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await Up(this.logger,r)){const p=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return Gi.setItem(Wl,JSON.stringify({devices:p}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}uh([y.trace("AudioMediaHandler.setTransformedTrack")],bl.prototype,"setTransformedTrack",1);uh([y.trace("AudioMediaHandler.onTrackEnded")],bl.prototype,"onTrackEnded",1);uh([y.trace("AudioMediaHandler.conditionallyChangeTrack")],bl.prototype,"conditionallyChangeTrack",1);const p0=bl;var gi;class g0{constructor(t,e){g(this,gi,void 0);h(this,"currentDevice");h(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");h(this,"logger");h(this,"setUserPreferredDevice",t=>Gi.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>Gi.getItem(this.userPreferredDeviceKey,this.logger));m(this,gi,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await n(this,gi).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var a,o;if(!(n(this,gi)instanceof df))return;let r=t;if(t||([r]=(await n(this,gi).getAvailableDevicesByKind("audiooutput")).filter(d=>!ad(d))),!r)throw new C("No speaker found","1608");if(((a=this.currentDevice)==null?void 0:a.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}gi=new WeakMap;const m0=g0;var Ro;class f0 extends Pa{constructor(e,r){const i=e.getValue("logger");super(i);h(this,"mediaInterface");h(this,"audioMediaTrack");h(this,"videoMediaTrack");g(this,Ro,void 0);m(this,Ro,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:a}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=a,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",n(this,Ro).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}async updateConstraints(e){if(!this.videoMediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),ge.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}Ro=new WeakMap;const T0=f0;var S0=Object.defineProperty,v0=Object.getOwnPropertyDescriptor,_l=(s,t,e,r)=>{for(var i=r>1?void 0:r?v0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&S0(t,e,i),i},Un,ko;class wc extends uf{constructor(e,r,i,a){super(e,r,i,a);g(this,Un,void 0);g(this,ko,{disablePerFrameCanvasRendering:!1});m(this,Un,new JA(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){this.logger.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await n(this,Un).getTransformedVideoTrack(this.middlewares,this.mediaTrack,n(this,ko)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){m(this,ko,e)}async updateConstraints(e){if(!this._mediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){n(this,Un).terminateMiddlewareWebWorker()}async onTrackEnded(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e,r=!1){if(!e||this.userSelectedDevice||r)return e;let i=e;const a=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?a.filter(c=>!this.isNonPreferredDevice(c)):a;return!(o!=null&&o.length)||window.FAST_RTK||o.find(c=>c.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=await this.mediaInterface.getVideoTrack(o[0].deviceId)),i}}Un=new WeakMap,ko=new WeakMap;_l([y.trace("VideoMediaHandler.setTransformedTrack")],wc.prototype,"setTransformedTrack",1);_l([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],wc.prototype,"setVideoMiddlewareGlobalConfig",1);_l([y.trace("VideoMediaHandler.onTrackEnded")],wc.prototype,"onTrackEnded",1);_l([y.trace("VideoMediaHandler.conditionallyChangeTrack")],wc.prototype,"conditionallyChangeTrack",1);const y0=wc,$p=ks(rh());var at,mi,Mo,$n;const cn=class{constructor(t){g(this,at,void 0);g(this,mi,void 0);g(this,Mo,void 0);g(this,$n,void 0);if(!t)throw new C("Could not load preset.","0904");m(this,at,t.config),m(this,Mo,t.name),m(this,mi,t.ui||ks(rh().ui)),m(this,$n,t.permissions.plugins.config)}static fromResponse(t){return new cn(t)}static default(){return new cn($p)}static init(t,e=!0){return!t||e?new cn($p):new cn(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:n(this,mi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return n(this,at).viewType}get livestreamViewerQualities(){return n(this,at).livestreamViewerQualities||[]}get maxVideoStreams(){return n(this,at).maxVideoStreams}get maxScreenShareCount(){return n(this,at).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(n(this,$n)).filter(t=>n(this,$n)[t].disabled)}get designTokens(){return n(this,mi).designTokens}get configDiff(){return n(this,mi).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=n(this,at))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,a,o,c,d,l,u,p,f,T,E,b,_,k,A,x,N,$,K,Y,Ue;return{audio:{enableStereo:(i=(r=(e=(t=n(this,at))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:en.audio.enableStereo,enableHighBitrate:(d=(c=(o=(a=n(this,at))==null?void 0:a.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:en.audio.enableHighBitrate},video:{quality:(f=(p=(u=(l=n(this,at))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:p.quality)!=null?f:en.video.quality,frameRate:(_=(b=(E=(T=n(this,at))==null?void 0:T.media)==null?void 0:E.video)==null?void 0:b.frameRate)!=null?_:en.video.frameRate},screenshare:{quality:(N=(x=(A=(k=n(this,at))==null?void 0:k.media)==null?void 0:A.screenshare)==null?void 0:x.quality)!=null?N:en.screenshare.quality,frameRate:(Ue=(Y=(K=($=n(this,at))==null?void 0:$.media)==null?void 0:K.screenshare)==null?void 0:Y.frameRate)!=null?Ue:en.screenshare.frameRate}}}get name(){return n(this,Mo)}};let Tu=cn;at=new WeakMap,mi=new WeakMap,Mo=new WeakMap,$n=new WeakMap;var E0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,hf=(s,t,e,r)=>{for(var i=r>1?void 0:r?P0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&E0(t,e,i),i},Bn,Io;class hh extends Lt{constructor(e,r){const i=e.getValue("logger");super(i);g(this,Bn,void 0);h(this,"state","IDLE");h(this,"playbackUrl");h(this,"ingestionCredentials");h(this,"viewerCount");g(this,Io,void 0);m(this,Bn,r),m(this,Io,e),this.viewerCount=0}get telemetry(){return n(this,Io).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(e={manualIngestion:!1}){if(!n(this,Bn).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new C("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=ht(),{playbackUrl:i,ingestionCredentials:a}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=a,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new C("Error while starting livestream","1900",this.logger)}}async stop(){if(!n(this,Bn).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new C("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw this.logger.error("Livestream::stop::inconsistent_state"),new C("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await ht().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream","1900",this.logger)}}}Bn=new WeakMap,Io=new WeakMap;hf([y.trace("livestream.start")],hh.prototype,"start",1);hf([y.trace("livestream.stop")],hh.prototype,"stop",1);var b0=Object.defineProperty,_0=Object.getOwnPropertyDescriptor,w0=(s,t,e,r)=>{for(var i=r>1?void 0:r?_0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&b0(t,e,i),i},Hn,Fn,Hs,Ps;class pf{constructor(t,e,r){h(this,"livestream");g(this,Hn,void 0);g(this,Fn,void 0);g(this,Hs,void 0);g(this,Ps,void 0);m(this,Ps,t),m(this,Fn,e),this.livestream=new hh(t,e),m(this,Hs,r),this.setupEvents()}get logger(){return n(this,Ps).getValue("logger")}get telemetry(){return n(this,Ps).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=ht(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:a}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=a,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){n(this,Hs).on(V.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{n(this,Fn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),n(this,Hs).on(V.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{n(this,Fn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),n(this,Hs).on(V.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),n(this,Hs).on(V.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),n(this,Hs).on(V.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),n(this,Ps).getValue("peerSessionStore").on(w.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(m(this,Hn,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),n(this,Ps).getValue("peerSessionStore").on(w.PEER_CLOSED,t=>{t.id===n(this,Hn)&&(m(this,Hn,void 0),this.livestream.setLivestreamState("IDLE"))}),n(this,Ps).getValue("peerSessionStore").onAsync(w.LEAVE_MEDIA_ROOM,async()=>{if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:t})}}}),n(this,Ps).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Hn=new WeakMap,Fn=new WeakMap,Hs=new WeakMap,Ps=new WeakMap;w0([y.trace("LivestreamController.setupEvents")],pf.prototype,"setupEvents",1);var C0=Object.defineProperty,R0=Object.getOwnPropertyDescriptor,Cc=(s,t,e,r)=>{for(var i=r>1?void 0:r?R0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&C0(t,e,i),i},Xe,Rr,kr,yd,gf;class _a{constructor({name:t,socketHandler:e,meetingId:r}){g(this,yd);h(this,"name","");g(this,Xe,{});g(this,Rr,"");g(this,kr,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});h(this,"listeners",{});this.name=t,m(this,kr,e),m(this,Rr,r)}async set(t,e,r=!0,i=!1){n(this,Xe)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(a=>a({[t]:n(this,Xe)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(a=>a({[t]:n(this,Xe)[t]})))}remoteSet(t,e){n(this,kr).storeInsertKeys(n(this,Rr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{n(this,Xe)[e]=r}),n(this,kr).storeInsertKeys(n(this,Rr),this.name,t)}async update(t,e,r=!0){L(this,yd,gf).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(n(this,Xe)[t]&&delete n(this,Xe)[t],e)return n(this,kr).storeDeleteKeys(n(this,Rr),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(i=>i({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{n(this,Xe)[e]&&delete n(this,Xe)[e]}),n(this,kr).storeDeleteKeys(n(this,Rr),this.name,t)}get(t){if(n(this,Xe)[t])return n(this,Xe)[t]}getAll(){return n(this,Xe)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){m(this,Xe,t)}}Xe=new WeakMap,Rr=new WeakMap,kr=new WeakMap,yd=new WeakSet,gf=function(t,e,r=!0){let i;const a=n(this,Xe)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(a);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...a,...e];break;case"[object Object]":i={...a,...e};break;case"[object Map]":i=new Map([...a,...e]);break;case"[object Set]":i=new Set([...a,...e]);break;default:i=e;break}this.set(t,i,r)};Cc([Et(ba,"rateLimitConfig")],_a.prototype,"remoteSet",1);Cc([Et(ba,"bulkRateLimitConfig")],_a.prototype,"bulkSet",1);Cc([Et(ba,"rateLimitConfig")],_a.prototype,"update",1);Cc([Et(ba,"rateLimitConfig")],_a.prototype,"delete",1);Cc([Et(ba,"bulkRateLimitConfig")],_a.prototype,"bulkDelete",1);var fi,Ti,Ao,Su,Do,Mr,Ed,mf;class k0{constructor(t,e){g(this,Ao);g(this,Ed);h(this,"stores",new Map);g(this,fi,void 0);g(this,Ti,"");g(this,Do,void 0);g(this,Mr,new Map);m(this,fi,e),m(this,Ti,t.getValue("meetingId")),m(this,Do,t),L(this,Ed,mf).call(this)}create(t){const e=new _a({name:t,socketHandler:n(this,fi),meetingId:n(this,Ti)});return n(this,fi).storeGetKeys(n(this,Ti),t,[]),new Promise((i,a)=>{const o=setTimeout(()=>a(Error("Failed")),3e3);n(this,Mr).set(t,{rejectTimeout:o,resolve:i,store:e})})}}fi=new WeakMap,Ti=new WeakMap,Ao=new WeakSet,Su=function(){return n(this,Do).getValue("peerId")},Do=new WeakMap,Mr=new WeakMap,Ed=new WeakSet,mf=function(){[F.storeInsertKeys,F.storeGetKeys,F.storeDeleteKeys].forEach(t=>{n(this,fi).on(t,async e=>{var a,o;if(e.pluginId!==n(this,Ti))return;const r=(a=e.storeItems)==null?void 0:a.map(c=>{var d;return{timestamp:c.timestamp,peerId:c.peerId,payload:JSON.parse((d=c.payload)!=null&&d.length?new TextDecoder().decode(c.payload):"{}"),key:c.storeKey}});if(t===F.storeGetKeys){const c=n(this,Mr).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);n(this,Mr).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),n(this,Mr).delete(e.storeName)),r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=n(this,Mr).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===F.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==n(this,Ao,Su)&&i.set(c,l,!1,!0)}),t===F.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==n(this,Ao,Su)&&i.delete(c,!1,!0)}))})})};function si(s){var t,e,r,i,a,o,c,d,l,u,p,f,T;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(a=s.mediaPermissions)==null?void 0:a.screenshare:null,audio:{enabled:(c=(o=s.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(p=(u=s.screenShareTracks)==null?void 0:u.video)==null?void 0:p.enabled,trackId:(T=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:T.id}}}}:{}}var M0=Object.defineProperty,I0=Object.getOwnPropertyDescriptor,wa=(s,t,e,r)=>{for(var i=r>1?void 0:r?I0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&M0(t,e,i),i};const A0=.8,D0=1.2;var qn,jn,kt,Si,Wa,Ir,rn,vi,Ja,Pd,ff,Fs,Oo,Ar,yi,Ka,qs,bd,No,vu,_d,Tf,wd,Sf,cg;let cr=(cg=class extends Lt{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,Si);g(this,Ir);g(this,vi);g(this,Pd);g(this,yi);g(this,No);g(this,_d);g(this,wd);h(this,"id");h(this,"userId");h(this,"name");h(this,"picture");h(this,"isHost");h(this,"customParticipantId");h(this,"flags");h(this,"device");h(this,"videoTrack");h(this,"audioTrack");h(this,"screenShareTracks");h(this,"videoEnabled");h(this,"audioEnabled");h(this,"screenShareEnabled");h(this,"producers");h(this,"manualProducerConfig");g(this,qn,void 0);h(this,"supportsRemoteControl",!1);g(this,jn,void 0);h(this,"presetName");g(this,kt,void 0);g(this,Fs,void 0);g(this,Oo,void 0);g(this,Ar,new Map);g(this,qs,1);g(this,bd,sh(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:a}=this.videoTrack.getSettings();if(!i||!a)return;const o=a/r,c=i/e,d=Math.max(o,c);d>D0&&n(this,qs)===1?(m(this,qs,0),n(this,kt).getValue("peerSessionStore").emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,qs)})):d<A0&&n(this,qs)===0&&(m(this,qs,1),n(this,kt).getValue("peerSessionStore").emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,qs)}))},2e3));m(this,kt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:p,flags:f,clientSpecificId:T,stageStatus:E,customParticipantId:b,audioMuted:_,audioTrack:k,videoEnabled:A=!1,videoTrack:x,producers:N,metadata:$}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=p,this.flags=f,this.manualProducerConfig=d_,m(this,jn,E!=null?E:"ON_STAGE"),this.customParticipantId=b!=null?b:T,this.audioEnabled=!_,this.audioTrack=k,this.videoEnabled=A,this.videoTrack=x,this.screenShareTracks={audio:void 0,video:void 0},this.producers=N!=null?N:[],this.presetName=$==null?void 0:$.preset_name,m(this,qn,!1),m(this,Fs,r),m(this,Oo,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),L(this,No,vu).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return n(this,jn)}get telemetry(){return n(this,kt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...si(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...si(this)}),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",L(this,No,vu)),n(this,Ir,rn)&&(this.on("audioUpdate",L(this,_d,Tf)),this.on("screenShareUpdate",L(this,wd,Sf)))}async pin(){if(!n(this,vi,Ja))throw new C("Can`t pin participant without joining room","1205");if(!n(this,Fs).permissions.pinParticipant)throw new C("You do not have permission to pin participants.","1201");return n(this,Si,Wa).pinPeer(this.id)}async unpin(){if(!n(this,vi,Ja))throw new C("Can`t unpin participant without joining room","1205");if(!n(this,Fs).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.","1201");return n(this,Si,Wa).pinPeer(null)}setIsPinned(t,e=!0){var i;m(this,qn,t);const r=t?"pinned":"unpinned";(i=n(this,yi,Ka))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info("Participant::disable_audio",{participant:{id:t}}),!n(this,vi,Ja))throw new C("Can`t disable participant audio without joining room","1205");if(n(this,Fs).permissions.canDisableParticipantAudio)return n(this,Si,Wa).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info("Participant::kick",{participant:{id:t}}),!n(this,Pd,ff))throw new C("Can`t kick participant without joining room","1205");if(n(this,Fs).permissions.kickParticipant){await n(this,kt).getValue("peerSessionStore").emitAsync(w.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new C("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info("Participant::disable_video",{participant:{id:t}}),!n(this,vi,Ja))throw new C("Can`t disable participant video without joining room","1205");if(n(this,Fs).permissions.canDisableParticipantVideo)return n(this,Si,Wa).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return n(this,Oo).getUserPermissions(this.userId)}setStageStatus(t){m(this,jn,t),this.emit("stageStatusUpdate",this)}get isPinned(){return n(this,qn)}registerVideoElement(t){var r,i,a,o;if(!t)return;let e;(i=(r=n(this,Ar).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>n(this,bd).call(this,t)),e.observe(t)),n(this,Ar).set(t,{observer:e}),this.updateVideo(t),(o=n(this,yi,Ka))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(a=this.raised)!=null?a:!1)}deregisterVideoElement(t){var e,r,i,a;if(!t){(e=n(this,yi,Ka))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=n(this,Ar).get(t))==null?void 0:r.observer)==null||i.disconnect(),n(this,Ar).delete(t),(a=n(this,yi,Ka))==null||a.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},qn=new WeakMap,jn=new WeakMap,kt=new WeakMap,Si=new WeakSet,Wa=function(){return n(this,kt).getValue("roomNodeClient")},Ir=new WeakSet,rn=function(){return n(this,kt).getValue("audioPlayback")},vi=new WeakSet,Ja=function(){return n(this,kt).getValue("connectionHandler").mediaJoined},Pd=new WeakSet,ff=function(){return n(this,kt).getValue("connectionHandler").socketJoined},Fs=new WeakMap,Oo=new WeakMap,Ar=new WeakMap,yi=new WeakSet,Ka=function(){return n(this,kt).getValue("pip")},qs=new WeakMap,bd=new WeakMap,No=new WeakSet,vu=function(){Array.from(n(this,Ar).keys()).forEach(this.updateVideo)},_d=new WeakSet,Tf=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=n(this,Ir,rn))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=n(this,Ir,rn))==null||e.removeParticipantTrack(this.id)},wd=new WeakSet,Sf=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=n(this,Ir,rn))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=n(this,Ir,rn))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},cg);wa([y.trace("Participant.disableAudio")],cr.prototype,"disableAudio",1);wa([y.trace("Participant.kick")],cr.prototype,"kick",1);wa([y.trace("Participant.disableVideo")],cr.prototype,"disableVideo",1);wa([y.trace("Participant.getPermissions")],cr.prototype,"getPermissions",1);wa([y.trace("Participant.setStageStatus")],cr.prototype,"setStageStatus",1);cr=wa([rt("1200")],cr);class Ga extends af{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:a="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:a},t)}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var Dr;class O0 extends Pa{constructor(e){super(e);g(this,Dr,void 0);m(this,Dr,new Map)}__set(e,r){return n(this,Dr).set(e,r)}__clear(){return n(this,Dr).clear()}get(e){return n(this,Dr).get(e)}toArray(){return Array.from(n(this,Dr).values())}}Dr=new WeakMap;class N0{constructor(){h(this,"_orderedArray");h(this,"_map");this._map=new Map,this._orderedArray=[]}add(t,e){if(!this._map.has(t))return this._map.set(t,{peerId:t,priority:e}),this._orderedArray.splice(Math.max(e-1,0),0,t),this.index(t);const r=this.index(t);this.delete(t);const i=this.add(t,e);return r!==i?i:-1}delete(t){if(this._map.has(t)){const e=this.index(t);this._map.delete(t),this._orderedArray.splice(e,1)}}index(t){return this._map.has(t)?this._orderedArray.indexOf(t):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class L0{constructor(){h(this,"_activeSpeakerPeers");h(this,"_compulsoryPeers");this._activeSpeakerPeers=new N0,this._compulsoryPeers=new Set}add(t,e,r){if(!t)return-1;if(e<0)return this._compulsoryPeers.add(t),0;const i=r.getValue("logger");if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(i.info("SelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t,r),-1;return this._activeSpeakerPeers.add(t,e)}delete(t,e){const r=e==null?void 0:e.getValue("logger");r==null||r.info("SelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}index(t){return this._activeSpeakerPeers.index(t)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(t){this._compulsoryPeers.delete(t)}}const vf=new L0;var V0=Object.defineProperty,x0=Object.getOwnPropertyDescriptor,xt=(s,t,e,r)=>{for(var i=r>1?void 0:r?x0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&V0(t,e,i),i};const U0=["ACTIVE_GRID","PAGINATED","MANUAL"];var Se,Lo,yu,Ei,za,Gn,Wc,Pi,mt,dg;let pt=(dg=class extends Lt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Lo);g(this,Ei);g(this,Gn);h(this,"waitlisted");h(this,"joined");h(this,"active");h(this,"videoSubscribed");h(this,"audioSubscribed");h(this,"pinned");h(this,"all");g(this,Se,void 0);g(this,Pi,void 0);g(this,mt,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"viewMode");h(this,"currentPage");h(this,"lastActiveSpeaker");h(this,"selectedPeers",vf);m(this,Se,t),m(this,Pi,e),m(this,mt,r),this.waitlisted=new Ga(i),this.joined=new Ga(i),this.videoSubscribed=new Ga(i),this.audioSubscribed=new Ga(i),this.active=this.videoSubscribed,this.pinned=new Ga(i),this.all=new O0(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return n(this,Se).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return n(this,Se).getValue("telemetry")}setupEvents(){n(this,Se).getValue("peerSessionStore").on(w.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=n(this,Se).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=n(this,Se).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=n(this,Se))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24","1203");n(this,Se).setValue("maxPreferredStreams",t),n(this,Gn,Wc)&&n(this,Se).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var r,i;if(!n(this,Ei,za))throw new C("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return n(this,mt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,a;return(a=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?a:r});return n(this,mt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!n(this,Ei,za))throw new C("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;n(this,mt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(this.logger.info("Participants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>U0.includes(r))(t))throw this.logger.error("Participants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new C(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,n(this,Se).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,n(this,Se).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,n(this,Se).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),n(this,Se).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),n(this,Se).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),a=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(a,o))}async setPage(t){if(this.logger.info("Participants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw this.logger.error("Participants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,n(this,Se).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(this.logger.info("Participants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!n(this,Gn,Wc))throw new C("Can`t disable all audio without joining room","1205");if(n(this,Pi).permissions.canAllowParticipantAudio)return n(this,Lo,yu).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!n(this,Gn,Wc))throw new C("Can`t disable all video without joining room","1205");if(n(this,Pi).permissions.canAllowParticipantVideo)return n(this,Lo,yu).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.","1201")}async disableAudio(t){this.joined.get(t).disableAudio()}async disableVideo(t){this.joined.get(t).disableVideo()}async kick(t){await n(this,Se).getValue("peerSessionStore").emitAsync(w.KICK_PEER,{peerId:t})}async kickAll(){if(this.logger.info("Participants::kick_all"),n(this,Se).getValue("viewType")!=="LIVESTREAM"&&!n(this,Ei,za))throw new C("Can`t kick all without joining room","1205");if(!n(this,Pi).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;n(this,mt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!n(this,Ei,za))throw new C("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await n(this,mt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(a=>{var o;return(o=r.presetNames)==null?void 0:o.includes(a.presetName)}).map(a=>a.id),await n(this,mt).broadcastToPeers(t,i,e)}else await n(this,mt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await n(this,mt).getRoomPeers(t,e,r)).peers.map(pr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(a=>t.includes(a.id)).map(a=>a.userId),i=[...new Set(r)];if(!i.length)throw new C("Cannot update permissions, no valid userIDs found","1204");n(this,mt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return n(this,mt).getRoomPeersNonPaginated()}},Se=new WeakMap,Lo=new WeakSet,yu=function(){return n(this,Se).getValue("roomNodeClient")},Ei=new WeakSet,za=function(){var t;return((t=n(this,Se).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Gn=new WeakSet,Wc=function(){var t;return((t=n(this,Se).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Pi=new WeakMap,mt=new WeakMap,dg);xt([y.trace("Participants.setViewMode")],pt.prototype,"setViewMode",1);xt([y.trace("Participants.setPage")],pt.prototype,"setPage",1);xt([y.trace("Participants.disableAllAudio")],pt.prototype,"disableAllAudio",1);xt([y.trace("Participants.disableAllVideo")],pt.prototype,"disableAllVideo",1);xt([y.trace("Participants.disablePeerAudio")],pt.prototype,"disableAudio",1);xt([y.trace("Participants.disablePeerVideo")],pt.prototype,"disableVideo",1);xt([y.trace("Participants.kickPeer")],pt.prototype,"kick",1);xt([y.trace("Participants.kickAll")],pt.prototype,"kickAll",1);xt([y.trace("Participants.broadcastMessage"),Et(ba,"rateLimitConfig")],pt.prototype,"broadcastMessage",1);xt([y.trace("Participants.getAllJoinedPeers"),Et({maxInvocations:10,period:60})],pt.prototype,"getAllJoinedPeers",1);xt([y.trace("Participant.updatePermissions"),Et({maxInvocations:1e3,period:60})],pt.prototype,"updatePermissions",1);xt([y.trace("Participants.getParticipantsInMeetingPreJoin")],pt.prototype,"getParticipantsInMeetingPreJoin",1);pt=xt([rt("1200")],pt);var $0=Object.defineProperty,B0=Object.getOwnPropertyDescriptor,Xi=(s,t,e,r)=>{for(var i=r>1?void 0:r?B0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&$0(t,e,i),i},Wt,os,Wn,lg;const yf=(lg=class{constructor(s,t,e){h(this,"participants");h(this,"self");h(this,"selectedPeers",vf);h(this,"maxSpatialLayerUpdates",new Map);h(this,"consumerPeerMap");h(this,"events");h(this,"roomSocketHandler");h(this,"context");h(this,"videoPeerConsumerMap",new Map);g(this,Wt,{mode:"ACTIVE_GRID",page:0});g(this,os,!1);g(this,Wn,!1);h(this,"updateConsumerSpatialLayers",sh(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];this.logger.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));h(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, ConsumersSyncing: ${n(this,os)}`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${s.length} producers: [${s.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(e){this.logger.error("updateConsumers: Error creating consumers",{error:e})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${t.length} producers: [${t.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.closeConsumers(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(e){this.logger.error("updateConsumers: Error closing consumers",{error:e})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new pt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=gs,t.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}setupEvents(){this.roomSocketHandler.on(V.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(w.SOCKET_PEERS,async s=>{s==null||s.forEach(t=>{t.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(t))})}),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:s})=>{this.logger.info("PEER_INFO:::MEDIA_JOIN",{participant:{id:s.peerId,maskedName:[...(s==null?void 0:s.displayName)||""].map((t,e)=>e%2?"*":t).join("")}}),this.onParticipantMediaJoined(s.peerId,s.producerStates)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:s,selectedPeers:t,roomState:e})=>{s.forEach(({peerId:a,producerStates:o})=>this.onParticipantMediaJoined(a,o));const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};e.pinnedPeerIds.length!==0&&this.onParticipantPinned(e.pinnedPeerIds[0]),this.computeActivateParticipants(r!=null?r:[],i),this.logger.info("selfJoinComplete: Emitting UPDATE_ACTIVE with createAllConsumers=true"),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers())}),this.context.getValue("peerSessionStore").on(w.NEW_PRODUCER,({peerId:s,producer:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:t==null?void 0:t.producerId,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}},participant:{id:s}});return}e.producers.push(t),this.logger.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}}}),(t==null?void 0:t.kind)==="audio"&&this.participants.audioSubscribed.get(s)||(t==null?void 0:t.kind)==="video"&&this.participants.videoSubscribed.get(s)||t!=null&&t.screenShare?(this.logger.info(`NEW_PRODUCER: scheduling syncConsumer (AUTO mode) - Producer: ${t.producerId}, Peer: ${s}, Kind: ${t.kind}, ScreenShare: ${t.screenShare}, ConsumersSyncing: ${n(this,os)}, VideoSub: ${t.kind==="video"?this.participants.videoSubscribed.has(s):"N/A"}, AudioSub: ${t.kind==="audio"?this.participants.audioSubscribed.has(s):"N/A"}`),this.scheduleSyncConsumers({source:"NEW_PRODUCER_AUTO"})):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer_auto",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"UNKNOWN",appData:{screenShare:t==null?void 0:t.screenShare}}})}),this.context.getValue("peerSessionStore").on(w.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{participant:{id:s}});return}e.producers=e.producers.filter(r=>r.producerId!==t)}),this.context.getValue("peerSessionStore").on(w.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){r==="audio"&&i.setAudioEnabled(!e);const a=i.producers.find(o=>o.producerId===t);a&&(a.pause=e),r==="video"&&this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,s=>{let t;if(s&&(t=s.participantId),!this.mediaJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);r&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${e} - ProducerCount: ${r.producers.length}, ConsumersSyncing: ${n(this,os)}, ProducerIds: [${r.producers.map(i=>i.producerId).join(", ")}]`),this.scheduleSyncConsumers({source:"GLOBAL_PEER_PIN"}))}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:s,compulsoryPeers:t})=>{this.mediaJoined&&this.onSelectedPeers(t.concat(s))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:s})=>{if(!this.mediaJoined)return;const t=s.map(e=>({peerId:e.peerId,priority:e.priority}));this.updateActiveParticipantsWithPriorities(t,!0)})}waitingRoomRequestHandler(s){const t=s.requests.filter(r=>!this.participants.waitlisted.toArray().find(i=>i.userId===r.userId)),e=this.participants.waitlisted.toArray().filter(r=>!s.requests.find(i=>i.userId===r.userId));t.forEach(r=>this.participants.waitlisted.add(new cr(this.context,{id:r.peerId,displayName:r.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:r.userId,flags:{},isHost:!1,customParticipantId:r.customParticipantId,picture:r.picture,metadata:{preset_name:r.presetName}},this.self,this.roomSocketHandler))),e.forEach(r=>this.participants.waitlisted.delete(r.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(s){const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(d=>this.participants.joined.has(d)),r=Array.from(this.participants.pinned.keys()).filter(d=>!e.includes(d)),i=Array.from(this.participants.joined.toArray().filter(d=>d.stageStatus==="ON_STAGE").map(d=>d.id)),a=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(a,o))}selectActivePeers(s){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(u=>u.stageStatus==="ON_STAGE").map(u=>(t.set(u.id,!0),u.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((u,p)=>(p.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(p.id):u.push(p.id),u),[]),a=this.self.stageStatus==="ON_STAGE"?1:0,o=s-a,c=new Set(r.concat(i).filter(u=>u!==this.self.id&&t.has(u)));let d=Array.from(c);const l=o-c.size;if(l>=0){const u=e.filter(p=>!c.has(p)&&p!==this.self.id).slice(0,l);d=Array.from(c).concat(u)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&n(this,Wt).mode!==s&&(n(this,Wt).mode=s),e&&n(this,Wt).page!==e&&(n(this,Wt).page=e);const{mode:r,page:i}=n(this,Wt);switch(r){case"PAGINATED":{if(!i)return;const a=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,a),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:a});break}case"ACTIVE_GRID":{const a=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,a),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":break;default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=n(this,Wt))==null?void 0:e.mode)==="PAGINATED"&&!n(this,os)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=n(this,Wt))==null?void 0:r.mode}, ConsumersSyncing: ${n(this,os)}, Delay: ${t}, Page: ${(i=n(this,Wt))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var o,c,d,l,u;if(((d=(c=(o=this.context.getValue("connectionHandler"))==null?void 0:o.mediaState)==null?void 0:c.recv)==null?void 0:d.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(n(this,os)){m(this,Wn,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),m(this,os,!0),m(this,Wn,!1);let s=[];this.participants.videoSubscribed.forEach(p=>{var E,b;const f=this.participants.joined.get(p.id),T=(b=(E=p.producers)==null?void 0:E.filter(_=>_.kind==="video"))!=null?b:[];f&&(T!=null&&T.length)&&T.forEach(_=>{var x,N,$,K;const k=((N=(x=f.manualProducerConfig)==null?void 0:x.video)!=null?N:!0)&&_.kind==="video"&&!_.screenShare,A=((K=($=f.manualProducerConfig)==null?void 0:$.screenshareVideo)!=null?K:!0)&&_.kind==="video"&&_.screenShare;(k||A)&&(_.pause||s.push(_))})}),this.participants.audioSubscribed.forEach(p=>{var E,b;const f=this.participants.joined.get(p.id),T=(b=(E=p.producers)==null?void 0:E.filter(_=>_.kind==="audio"))!=null?b:[];f&&(T!=null&&T.length)&&T.forEach(_=>{var x,N,$,K;const k=((N=(x=f.manualProducerConfig)==null?void 0:x.audio)!=null?N:!0)&&_.kind==="audio"&&!_.screenShare,A=((K=($=f.manualProducerConfig)==null?void 0:$.screenshareAudio)!=null?K:!0)&&_.kind==="audio"&&_.screenShare;(k||A)&&s.push(_)})}),s=c_(s,p=>p.producerId);const t=new Map;s.forEach(p=>{t.set(p.producerId,p)});const e=(l=this.roomNodeClient)==null?void 0:l.getConsumers(),r=s.filter(p=>!(e!=null&&e.has(p.producerId))),i=[];let a=Array.from((u=e==null?void 0:e.values())!=null?u:[]).map(p=>p.peerId);a=o_(a),a==null||a.forEach(p=>{var T;const f=this.participants.joined.get(p);if(!f){this.logger.warn(`Peer with ${p} doesn't exist in joined list but producers of it are being consumed.`);return}(T=f.producers)!=null&&T.length&&f.producers.forEach(E=>{const b=E.consumer&&e.has(E.consumer.id);!t.has(E.producerId)&&(e.has(E.producerId)||b)&&i.push(E)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(p=>p.producerId).join(", ")}], RemoveProducers: ${i.length} [${i.map(p=>p.producerId).join(", ")}]`.substring(0,5e3));try{r.length>0||i.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${i.length}.`),await this.updateConsumers(r,i),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(p){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:p})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),m(this,os,!1)}n(this,Wn)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,a)=>({peerId:i,priority:a+1})),r=t==null?void 0:t.map((i,a)=>({peerId:i,priority:-(a+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=yf.formatSocketPeerMessage(s);return new cr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onParticipantMediaJoined(s,t){if(!this.mediaJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{participant:{id:e.id,maskedName:[...(e==null?void 0:e.name)||""].map((r,i)=>i%2?"*":r).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(r=>{r.kind===ir.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===ir.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===ir.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType})}),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),i=new Set(t),a=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&a.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=a.shift();e[c]=o}),a.forEach(o=>{e.splice(o,1)}),Array.from(s.keys()).forEach(o=>{s.delete(o,!i.has(o))}),e.forEach(o=>{if(!this.participants.joined.get(o)){this.logger.warn("updateActiveParticipants::participant_not_in_joined_list",{participant:{id:o}});return}s.add(this.participants.joined.get(o),!r.get(o))}),s.emit("participantsUpdate")}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{s.get(r)||s.add(this.participants.joined.get(r),!0)}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}setupEventsGlobal(){this.roomSocketHandler.on(V.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info("Processing socket join",{peers:s.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info("Processed socket join",{peers:s.peerId}))}),this.roomSocketHandler.on(V.leaveRoom,s=>{const{peerId:t}=s.peer;this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),this.context.getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),this.context.getValue("peerSessionStore").on(w.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(w.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(w.NEW_CONSUMER,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(w.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(w.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(w.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(w.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),this.context.getValue("peerSessionStore").on(w.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const a=t==="video"&&((c=e==null?void 0:e.screenShare)!=null?c:!1),o=this.participants.joined.get(r);o&&(o.emit("mediaScoreUpdate",{kind:t,isScreenshare:a,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:a,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(w.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),this.context.getValue("peerSessionStore").on(w.UPDATE_ACTIVE,async({viewMode:s,page:t,createAllConsumers:e}={viewMode:"ACTIVE_GRID",page:0,createAllConsumers:!1})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${n(this,Wt).mode}, page: ${t}, CreateAllConsumers: ${e}`),e&&(this.logger.info(`UPDATE_ACTIVE viewMode: ${s}, Page: ${t}, Removing existing subscriptions.`),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear()),this.updateMediaSubscribedMaps(s,{page:t}),this.scheduleSyncConsumers({source:"UPDATE_ACTIVE"})})}async onParticipantPinned(s){if(!s){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(s===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const t=this.participants.joined.get(s);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),t.setIsPinned(!0),this.participants.pinned.add(t)}async onParticipantSocketJoined(s){var t,e,r;this.logger.info(`onParticipantSocketJoined: peer ${s.id} has joined socket edge. Processing.`),this.self.id!==s.id&&!((t=s.flags)!=null&&t.recorder)&&!((e=s.flags)!=null&&e.hidden_participant)&&!((r=s.flags)!=null&&r.hiddenParticipant)&&(this.participants.videoSubscribed.delete(s.id),this.participants.audioSubscribed.delete(s.id),this.participants.joined.add(s),this.participants.waitlisted.delete(s.id),s.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(w.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),this.roomNodeClient&&this.roomNodeClient.closeConsumers(t==null?void 0:t.producers),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1});const{currentPage:e}=this.participants,r=this.maxPreferredStreams*(e-1),i=this.participants.videoSubscribed.get(s);this.participants.viewMode==="MANUAL"?this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e}):r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?e===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(e-1):i&&this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e})}processMedia(s){var p;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:i,track:a,producerId:o,rtpReceiver:c,paused:d,localId:l}=(p=t.get(s))!=null?p:{};if(!e)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:s,kind:r,peerId:e,appData:{supportsRemoteControl:!!(i!=null&&i.supportsRemoteControl),screenShare:!!(i!=null&&i.screenShare)},remotelyPaused:d,producerId:o}}),{};const u=i;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:d,producerId:o}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:a,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:a}=this.consumerPeerMap.get(s)||{},o=this.participants.joined.get(t);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:i,producerId:a}}),this.consumerPeerMap.delete(s),e==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!o)return;const c=o.producers.find(l=>l.producerId===a);c&&(c.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:a,rtpReceiver:void 0,localId:void 0});const d=[];r&&r.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}),o.screenShareTracks.video&&d.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&d.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):e==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&d.push(o.audioTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}),o.audioTrack=void 0):e==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&d.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1}),o.videoTrack=void 0),r.e2ee&&d.forEach(l=>{this.context.getValue("peerSessionStore").emit(w.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:l})})}processConsumerResumed(s){var f;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:a,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const p=u.producers.find(T=>T.producerId===c);if(p&&(p.consumer={id:s,peerId:e,kind:r,appData:i,paused:o,producerId:c,rtpReceiver:d,localId:l}),i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:a}),i.screenShare){r==="video"?u.screenShareTracks.video=a:r==="audio"&&(u.screenShareTracks.audio=a),u.setScreenShareEnabled(!0),(f=this.context)==null||f.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=a,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=a,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:a,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:a,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(p=>p.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:a,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:a,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:a,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(p=>p.producerId===o);if(u&&(u.consumer={id:s,peerId:t,kind:e,appData:a,paused:r,producerId:o,rtpReceiver:c,localId:d}),a.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),a.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:a,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&a.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i})}static formatSocketPeerMessage(s){var e,r,i,a,o,c;if(!s)return;const t=oh(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=s.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(a=s.flags)==null?void 0:a.hiddenParticipant,recorder:((o=s.flags)==null?void 0:o.recorderType)!==void 0&&((c=s.flags)==null?void 0:c.recorderType)!=="NONE"}}}async onSelectedPeers(s,t){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(s,t)}updateActiveParticipantsWithPriorities(s,t=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority,this.context)});const e=this.selectedPeers.activeSpeakerPeers.at(0);e!==void 0&&e!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=e,this.participants.emit("activeSpeaker",{peerId:e,volume:1})),t&&this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},Wt=new WeakMap,os=new WeakMap,Wn=new WeakMap,lg);let pr=yf;Xi([y.trace("ParticipantController.setupEvents")],pr.prototype,"setupEvents",1);Xi([y.trace("ParticipantController.setupEvents")],pr.prototype,"setupEventsGlobal",1);Xi([y.trace("ParticipantController.processMedia")],pr.prototype,"processMedia",1);Xi([y.trace("ParticipantController.processConsumerClosed")],pr.prototype,"processConsumerClosed",1);Xi([y.trace("ParticipantController.processConsumerResumed")],pr.prototype,"processConsumerResumed",1);Xi([y.trace("ParticipantController.processConsumerPaused")],pr.prototype,"processConsumerPaused",1);Xi([y.trace("ParticipantController.processNewConsumer")],pr.prototype,"processNewConsumer",1);const le=ks(rh().permissions);var B,Jn,Kn,Cd,ot,bt;const dn=class extends Lt{constructor(e,r,i,a=!1){const o=e.getValue("logger");super(o);g(this,ot);g(this,B,void 0);g(this,Jn,void 0);g(this,Kn,void 0);g(this,Cd,e=>{var l,u,p;const{chat:r,connectedMeetings:i,plugins:a,polls:o,media:c,...d}=e;if(r&&(r.private&&mr(n(this,B).chat.private,r.private),r.public&&mr(n(this,B).chat.public,r.public),this.emit("chatUpdate")),i&&mr(n(this,B).connectedMeetings,i),c){const f=E=>{switch(E){case Br.NONE:return H.Allowed;case Br.ALLOWED:return H.Allowed;case Br.NOT_ALLOWED:return H.NotAllowed;case Br.CAN_REQUEST:return H.CanRequest;default:return}},T={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(T.audio={canProduce:f(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(T.video={canProduce:f(c.video.canProduce)}),(p=c.screenshare)!=null&&p.canProduce&&(T.screenshare={canProduce:f(c.screenshare.canProduce)}),mr(n(this,B).media,T)}a&&(mr(n(this,B).plugins,a),this.emit("pluginsUpdate")),o&&(mr(n(this,B).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&mr(n(this,B),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.","0904");m(this,Kn,e),m(this,Jn,i),m(this,B,r),a&&this.setupEvents()}setupEvents(){n(this,Kn).getValue("peerSessionStore").on(w.UPDATE_PERMISSIONS,n(this,Cd))}static fromResponse(e,r,i){return new dn(i,e,r,!0)}static default(e,r){return new dn(e,le,r)}static init(e,r,i){let a;return i?a=new dn(e,i,r,!0):a=new dn(e,le,r),a}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=n(this,B))==null?void 0:e.stageEnabled)||n(this,Jn)===rr.Webinar||n(this,Jn)===rr.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=n(this,B))==null?void 0:e.acceptStageRequests)||((r=n(this,B))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=n(this,B))==null?void 0:e.stageAccess)===H.NotAllowed?H.NotAllowed:((r=n(this,B))==null?void 0:r.stageAccess)===H.CanRequest?H.CanRequest:((i=n(this,B))==null?void 0:i.stageAccess)===H.Allowed||n(this,B).media.audio.canProduce===H.Allowed||n(this,B).media.video.canProduce===H.Allowed||n(this,B).media.screenshare.canProduce===H.Allowed?H.Allowed:n(this,B).media.audio.canProduce===H.CanRequest||n(this,B).media.video.canProduce===H.CanRequest||n(this,B).media.screenshare.canProduce===H.CanRequest?H.CanRequest:H.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=n(this,B))==null?void 0:e.acceptWaitingRequests)!=null?r:le.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=n(this,B))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=n(this,B))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=n(this,B))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===H.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=n(this,B))==null?void 0:e.disableParticipantAudio)!=null?r:le.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canAcceptProductionRequests)!=null?r:le.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=n(this,B))==null?void 0:e.disableParticipantVideo)!=null?r:le.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=n(this,B))==null?void 0:e.kickParticipant)!=null?r:le.kickParticipant}get pinParticipant(){var e,r;return(r=(e=n(this,B))==null?void 0:e.pinParticipant)!=null?r:le.pinParticipant}get canRecord(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canRecord)!=null?r:le.canRecord}get waitingRoomType(){var e,r;return(r=(e=n(this,B))==null?void 0:e.waitingRoomType)!=null?r:le.waitingRoomType}get waitingRoomBehaviour(){var e,r;return(r=(e=n(this,B))==null?void 0:e.waitingRoomType)!=null?r:le.waitingRoomType}get plugins(){var e,r;return(r=(e=n(this,B))==null?void 0:e.plugins)!=null?r:le.plugins}get polls(){var e,r;return(r=(e=n(this,B))==null?void 0:e.polls)!=null?r:le.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return n(this,B).media.audio.canProduce===H.CanRequest||n(this,B).media.video.canProduce===H.CanRequest||n(this,B).media.screenshare.canProduce===H.CanRequest}get canProduceVideo(){var r;const e=(r=n(this,B).media.video.canProduce)!=null?r:le.media.video.canProduce;return this.stageEnabled&&(n(this,ot,bt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,ot,bt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(n(this,ot,bt)==="OFF_STAGE"||n(this,ot,bt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var r;const e=(r=n(this,B).media.screenshare.canProduce)!=null?r:le.media.screenshare.canProduce;return this.stageEnabled&&(n(this,ot,bt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,ot,bt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(n(this,ot,bt)==="OFF_STAGE"||n(this,ot,bt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var r;const e=(r=n(this,B).media.audio.canProduce)!=null?r:le.media.audio.canProduce;return this.stageEnabled&&(n(this,ot,bt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,ot,bt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(n(this,ot,bt)==="OFF_STAGE"||n(this,ot,bt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=n(this,B))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:le.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=n(this,B))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:le.chat.private}get connectedMeetings(){var e,r;return(r=(e=n(this,B))==null?void 0:e.connectedMeetings)!=null?r:le==null?void 0:le.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=n(this,B))==null?void 0:e.hiddenParticipant)!=null?r:le.hiddenParticipant}get showParticipantList(){var e;return(e=n(this,B).showParticipantList)!=null?e:le.showParticipantList}get canChangeParticipantRole(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canChangeParticipantPermissions)!=null?r:le.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canChangeParticipantPermissions)!=null?r:le.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return n(this,B).media.audio.canProduce===H.Allowed||n(this,B).media.video.canProduce===H.Allowed||n(this,B).media.screenshare.canProduce===H.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var e;return(e=n(this,B).canEditDisplayName)!=null?e:!1}get maxScreenShareCount(){return 1}get isRecorder(){return n(this,B).isRecorder}get canSpotlight(){return n(this,B).canSpotlight}get canLivestream(){return n(this,B).canLivestream}get transcriptionEnabled(){return n(this,B).transcriptionEnabled}};let Eu=dn;B=new WeakMap,Jn=new WeakMap,Kn=new WeakMap,Cd=new WeakMap,ot=new WeakSet,bt=function(){return n(this,Kn).getValue("stageStatus")};var Mt;class Ef extends Lt{constructor(e,r){super(r);h(this,"localMediaHandler");g(this,Mt,void 0);m(this,Mt,e)}async updatePermission(){var d,l;const e=(u,p)=>{this.mediaPermissions[u]=p;const f={message:this.mediaPermissions[u],kind:u};p==="DENIED"?n(this,Mt).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_ERROR,f):n(this,Mt).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,f)};if(ge.getName()==="firefox")return;const r="microphone",i="camera",a=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(u,p)=>{switch(p){case"granted":e(u,"ACCEPTED");break;case"denied":e(u,"DENIED");break;case"prompt":e(u,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};a&&(a.onchange=()=>c("audio",a.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,a,o,c;switch(r){case"audio":{(i=n(this,Mt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(a=n(this,Mt))==null||a.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=n(this,Mt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=n(this,Mt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=n(this,Mt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var a,o,c,d,l,u,p;if(ge.init(),i&&m(this,Mt,i),!this.localMediaHandler)try{let f=!0;if((a=i==null?void 0:i.getValue("defaults"))!=null&&a.mediaHandler)f=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:T}=navigator;this.localMediaHandler=await T.init(e)}else this.localMediaHandler=new Pt(i,e.constraints,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.isNonPreferredDevice,(c=i==null?void 0:i.getValue("defaults"))==null?void 0:c.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(w.MEDIA_PERMISSION_UPDATE,async T=>{if(this.populateMediaPermissionsInCallstats({message:T.message,kind:T.kind}),T.message==="NOT_REQUESTED")switch(T==null?void 0:T.kind){case"audio":this.rawAudioTrack&&(this.logger.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(this.logger.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",T)}),i==null||i.getValue("peerSessionStore").on(w.MEDIA_PERMISSION_ERROR,async T=>{const{kind:E,message:b,constraints:_}=T;this.populateMediaPermissionsInCallstats({message:b,kind:E}),E==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):E==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:b},constraints:_,mediaPermissionsErrors:{kind:E,message:b}}),this.emit("mediaPermissionError",T),this.emit("mediaPermissionUpdate",{message:b,kind:E})}),f){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const T=this.localMediaHandler.setupStreams({video:(u=e==null?void 0:e.video)!=null?u:!0,audio:(p=e==null?void 0:e.audio)!=null?p:!0});r||await T}}catch(f){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:f.name,message:f.message}})}}set context(e){m(this,Mt,e),this.localMediaHandler.context=e}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}async addAudioMiddleware(e){return this.localMediaHandler.addAudioMiddleware(e)}async removeAudioMiddleware(e){return this.localMediaHandler.removeAudioMiddleware(e)}async removeAllAudioMiddlewares(){return this.localMediaHandler.removeAllAudioMiddlewares()}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}async addVideoMiddleware(e){return this.localMediaHandler.addVideoMiddleware(e)}async setVideoMiddlewareGlobalConfig(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)}async removeVideoMiddleware(e){return this.localMediaHandler.removeVideoMiddleware(e)}async removeAllVideoMiddlewares(){return this.localMediaHandler.removeAllVideoMiddlewares()}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}async enableAudio(){await this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){await this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){await this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}async getAudioDevices(){return await this.localMediaHandler.getAudioDevices()}async getVideoDevices(){return await this.localMediaHandler.getVideoDevices()}async getSpeakerDevices(){return await this.localMediaHandler.getSpeakerDevices()}getDeviceById(e,r){let i;return r==="audio"?i="audioinput":r==="video"?i="videoinput":r==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}async setDevice(e){switch(e.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(e,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}Mt=new WeakMap;var H0=Object.defineProperty,F0=Object.getOwnPropertyDescriptor,gt=(s,t,e,r)=>{for(var i=r>1?void 0:r?F0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&H0(t,e,i),i},zn,ct,Yn,Fe,js,Xr,qe,ze,Qn,Jc,Ie,Ne,Xn,Zn,Vo,Pu,ug;let Je=(ug=class extends Ef{constructor(t,e,r,i,a){var c;const o=t.getValue("logger");super(t,o);g(this,js);g(this,qe);g(this,Qn);g(this,Ie);g(this,Vo);h(this,"name");h(this,"picture");h(this,"customParticipantId");h(this,"waitlistStatus");g(this,zn,void 0);g(this,ct,void 0);g(this,Yn,void 0);h(this,"role");h(this,"userId");h(this,"organizationId");h(this,"supportsRemoteControl",!1);h(this,"device");g(this,Fe,void 0);h(this,"hidden",!1);h(this,"presetName");h(this,"roomState","init");g(this,Xn,new Set);g(this,Zn,new Set);m(this,Fe,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(c=e.customParticipantId)!=null?c:e.clientSpecificId,this.waitlistStatus="none",m(this,ct,r),m(this,zn,i),this.hidden=!1,m(this,Yn,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ge.isElectron(),this.device=ge.getDeviceInfo(),this.presetName=a,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),L(this,Vo,Pu).call(this)}get telemetry(){return n(this,Fe).getValue("telemetry")}get stageStatus(){return n(this,Fe).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=n(this,qe,ze).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return n(this,Fe).getValue("peerId")}static async __init__(t,e,r,i,a,o=!1){var f,T,E,b,_,k;let c=(T=(f=t.getValue("defaults"))==null?void 0:f.audio)!=null?T:!0,d=(b=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?b:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new Je(t,e,r,i,a),u=XA(i.mediaConstraints);mr(u,(_=t.getValue("defaults"))==null?void 0:_.mediaConfiguration);const p=(k=t.getValue("defaults"))==null?void 0:k.mediaHandler;return p&&(p.context=t),await l.init({audio:c,video:d,constraints:u},o,t),l.setupEvents(),l}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),n(this,ct).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",L(this,Vo,Pu));const t=n(this,Qn,Jc);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...si(this)}),n(this,Ie,Ne)&&this.audioEnabled)try{await n(this,qe,ze).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::VIDEO_TRACK_CHANGE",{...si(this)}),n(this,Ie,Ne)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&n(this,Ie,Ne))try{await n(this,qe,ze).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}),this.localMediaHandler.on("DEVICE_CHANGE",async({device:e})=>{var r;this.emit("deviceUpdate",{device:e}),e.kind==="audiooutput"&&typeof HTMLAudioElement.prototype.setSinkId=="function"&&((r=n(this,Qn,Jc))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!n(this,Ie,Ne)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await n(this,qe,ze).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::setupEvents::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...si(this)}),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}),this.localMediaHandler.on("SCREENSHARE_ENDED",async()=>{this.logger.log("Disabling screenshare due to SCREENSHARE_ENDED"),await this.disableScreenShare(),this.logger.info("Self::setupEvents::SCREENSHARE_ENDED",{...si(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=n(this,Fe))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;n(this,Ie,Ne)&&await n(this,qe,ze).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=n(this,Fe))==null||e.getValue("callstats").videoOff()}),n(this,ct).on("permissionsUpdate",e=>{var r,i,a;(r=e==null?void 0:e.media)!=null&&r.audio&&n(this,ct).canProduceAudio!==H.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&n(this,ct).canProduceVideo!==H.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(a=e==null?void 0:e.media)!=null&&a.screenshare&&n(this,ct).canProduceScreenshare!==H.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return n(this,ct)}get config(){return n(this,zn)}get roomJoined(){var t;return n(this,zn).viewType===rr.Livestream&&this.stageStatus!=="ON_STAGE"?((t=n(this,Fe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:n(this,Ie,Ne)}setName(t){if(!t)throw new C("Name cannot be empty.","1103");this.name=t}async setupTracks(t={}){t.forceReset,await this.disableAudio(),await this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&await this.enableAudio(),t.video&&await this.enableVideo()}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(t){var e;if(this.permissions.canProduceAudio!==H.NotAllowed&&!(n(this,ct).canProduceAudio===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=n(this,Fe))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),n(this,Ie,Ne)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await n(this,qe,ze).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(n(this,ct).canProduceVideo!==H.NotAllowed&&!(n(this,ct).canProduceVideo===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=n(this,Fe))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),n(this,Ie,Ne)&&this.stageStatus==="ON_STAGE")try{await n(this,qe,ze).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...si(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!n(this,Ie,Ne))throw new C("Can`t enable screenshare without joining room","1105");if(n(this,ct).canProduceScreenshare!==H.NotAllowed&&!(n(this,ct).canProduceScreenshare===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await n(this,qe,ze).shareScreen(this.screenShareTracks)}catch(t){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),n(this,Ie,Ne)&&n(this,qe,ze).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=n(this,Fe))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),n(this,Ie,Ne)&&await n(this,qe,ze).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=n(this,Fe))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),n(this,Ie,Ne)&&await n(this,qe,ze).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;m(this,Yn,t);const r=t?"pinned":"unpinned";(i=n(this,js,Xr))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return n(this,Yn)}async pin(){if(!n(this,Ie,Ne))throw new C("Can`t pin participants without joining room","1105");return this.show(),n(this,qe,ze).pinPeer(this.id)}async unpin(){if(!n(this,Ie,Ne))throw new C("Can`t unpin participants without joining room","1105");return n(this,qe,ze).pinPeer(null)}async hide(){if(!n(this,Ie,Ne))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!n(this,Ie,Ne))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,a;if(!t)throw new C("No device selected","1104");const e=this.getCurrentDevices();switch(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((i=e==null?void 0:e.video)==null?void 0:i.deviceId)===t.deviceId||((a=e==null?void 0:e.speaker)==null?void 0:a.deviceId)===t.deviceId)&&this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){n(this,Ie,Ne)&&await n(this,qe,ze).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(t,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(t,{saveDevicePreference:!0})}catch(o){n(this,Ie,Ne)&&await n(this,qe,ze).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}}cleanUpTracks(){var t,e,r,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(i=this.rawVideoTrack)==null||i.stop()}playAudio(){var t;return(t=n(this,Qn,Jc))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?n(this,Xn).add(t):n(this,Zn).add(t),this.updateVideo(t),e||(i=n(this,js,Xr))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){n(this,js,Xr).removeSource(this.id);return}t.srcObject=void 0,e?n(this,Xn).delete(t):(n(this,Zn).delete(t),n(this,js,Xr).removeSource(this.id))}updateVideo(t,e=!1){var r,i,a;if(this.videoEnabled){if(this.videoTrack==null)return;const o=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((o==null?void 0:o.id)===this.videoTrack.id)return;const c=new MediaStream;c.addTrack(this.videoTrack),t.srcObject=c,e||(i=n(this,js,Xr))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(a=n(this,js,Xr))==null||a.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},zn=new WeakMap,ct=new WeakMap,Yn=new WeakMap,Fe=new WeakMap,js=new WeakSet,Xr=function(){return n(this,Fe).getValue("pip")},qe=new WeakSet,ze=function(){return n(this,Fe).getValue("roomNodeClient")},Qn=new WeakSet,Jc=function(){return n(this,Fe).getValue("audioPlayback")},Ie=new WeakSet,Ne=function(){var t;return((t=n(this,Fe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Xn=new WeakMap,Zn=new WeakMap,Vo=new WeakSet,Pu=function(){Array.from(n(this,Zn)).forEach(t=>this.updateVideo(t,!1)),Array.from(n(this,Xn)).forEach(t=>this.updateVideo(t,!0))},ug);gt([y.trace("Self.cleanupEvents")],Je.prototype,"cleanupEvents",1);gt([y.trace("Self.setupEvents")],Je.prototype,"setupEvents",1);gt([y.trace("Self.setupTracks")],Je.prototype,"setupTracks",1);gt([y.trace("Self.destructMediaHandler")],Je.prototype,"destructMediaHandler",1);gt([y.trace("Self.removeDocumentEventListeners")],Je.prototype,"removeDocumentEventListeners",1);gt([hr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.enableAudio")],Je.prototype,"enableAudio",1);gt([hr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.enableVideo")],Je.prototype,"enableVideo",1);gt([y.trace("Self.updateVideoConstraints")],Je.prototype,"updateVideoConstraints",1);gt([y.trace("Self.enableScreenShare"),hr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],Je.prototype,"enableScreenShare",1);gt([y.trace("Self.updateScreenshareConstraints")],Je.prototype,"updateScreenshareConstraints",1);gt([hr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.disableAudio")],Je.prototype,"disableAudio",1);gt([hr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.disableVideo")],Je.prototype,"disableVideo",1);gt([hr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),y.trace("Self.disableScreenShare")],Je.prototype,"disableScreenShare",1);gt([y.trace("Self.setDevice")],Je.prototype,"setDevice",1);Je=gt([rt("1100")],Je);class ph extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,ph)}}class gh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,gh)}}var xo;class bu{constructor(t,e=!1){h(this,"pendingTasks",new Map);h(this,"nextTaskId",0);h(this,"stopping",!1);g(this,xo,void 0);this.log=e,m(this,xo,{info:e&&t?t.info:()=>{}})}get size(){return this.pendingTasks.size}async push(t,e,r){if(e=e!=null?e:t.name,typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(i){}return new Promise((i,a)=>{const o={id:this.nextTaskId++,task:t,metadata:r,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),i(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),a(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){this.stopping=!0;for(const t of this.pendingTasks.values())t.reject(new ph);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new gh)}get(t){return Array.from(this.pendingTasks.values())[t]}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=this.pendingTasks.size,r=await t.task(),i=Date.now();n(this,xo).info(`AwaitQueue.push(${t.name})_timings`,{awaitQueueTask:{id:t.id,metadata:t.metadata,queueSizeAtStart:e,execTime:(i-t.executedAt)/1e3,taskStartTime:(t.executedAt-t.enqueuedAt)/1e3}}),t.resolve(r)}catch(e){t.reject(e)}}}xo=new WeakMap;function q0(s,t){const e=new Error(t);return e.name=s,e}class go extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,go):this.stack=new Error(t).stack}}class yt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,yt):this.stack=new Error(t).stack}}class Er extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,yt):this.stack=new Error(t).stack}}const Bp=s=>new Promise(t=>setTimeout(t,s));async function Pf(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:a,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=p=>{l=!0,r(p)};for(;c<a;){try{const p=await s(c,u);return e(p)}catch(p){if(d=p,l)break;if(c<a)i==="linear"?await Bp(o*(c+1)):i==="exponential"&&await Bp(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function j0(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function G0(s){return s.map(t=>({uri:t.uri}))}function Vc(s){return{codecs:j0(s.codecs),headerExtensions:G0(s.headerExtensions?s.headerExtensions:[])}}function W0(s){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");s&&(e.codecs=e.codecs.filter(({mimeType:d})=>s===d),i.codecs=i.codecs.filter(({mimeType:d})=>s===d));const a={audio:Vc(t),video:Vc(e)};return{sender:{audio:Vc(r),video:Vc(i)},receiver:a}}var je;class J0{constructor(t){g(this,je,void 0);h(this,"events");m(this,je,t),this.events=gs}async joinRoom(t,e,r,i=!1){const a={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await n(this,je).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:fw.toBinary(a),timeout:5e3})).payload}async connectTransport(t){const e=(await n(this,je).sendMessagePromise(this.events.createWebRTCTransport,j_.toBinary(t))).payload,{transportId:r,description:i,producerIds:a}=Nm.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:a}}async produce(t){var a,o;const e=(await n(this,je).sendMessagePromise(this.events.produce,Aw.toBinary(t))).payload,r=pC.fromBinary(e);return{answer:{sdp:(a=r==null?void 0:r.description)==null?void 0:a.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await n(this,je).sendMessagePromise(this.events.consume,ww.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=uC.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await n(this,je).sendMessagePromise(this.events.closeProducer,Uw.toBinary(t))).payload,{description:r}=yC.fromBinary(e);return r}async closeConsumer(t){return(await n(this,je).sendMessagePromise(this.events.closeConsumer,Bw.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await n(this,je).sendMessagePromise(this.events.updateConsumersSimulcastConfig,Mw.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await n(this,je).sendMessagePromise(this.events.hostControlPeer,Ww.toBinary(r))).payload;if(!i)return!1;const{status:a}=RC.fromBinary(i);return a==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await n(this,je).sendMessagePromise(this.events.hostControlAllPeers,Kw.toBinary(e))).payload;if(!r)return!1;const{status:i}=MC.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};n(this,je).sendMessagePromise(V.kickAll,Um.toBinary(t))}async kickPeer(t){n(this,je).sendMessagePromise(V.kick,qm.toBinary(t))}async changeDisplayName(t){const e=(await n(this,je).sendMessagePromise(this.events.changeDisplayName,jw.toBinary(t))).payload;if(!e)return!1;const{status:r}=AC.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await n(this,je).sendMessagePromise(this.events.selfJoinComplete,Sw.toBinary(t))).payload;return su.fromBinary(e)}async audioActivity(t){n(this,je).sendMessage(this.events.audioActivity,W_.toBinary(t))}}je=new WeakMap;var mn=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(mn||{}),Uo;class wl extends st.EventEmitter{constructor(e){super();g(this,Uo,void 0);m(this,Uo,e),this.setMaxListeners(1/0)}get logger(){return n(this,Uo).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(a){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:a}),Boolean(i)}}async safeEmitAsPromise(e,...r){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)}async safeEmitAsPromiseWithTimeout(e,r,...i){return new Promise((a,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,a,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}Uo=new WeakMap;class mh extends wl{constructor(){super(...arguments);h(this,"_sendWebStream",new MediaStream);h(this,"_sendScreenShareStream",new MediaStream);h(this,"_direction");h(this,"pc");h(this,"_transportReady",!1);h(this,"_mapMidTransceiver",new Map);h(this,"enableHighBitrate",!1);h(this,"enableStereo",!1);h(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}async restartIce(){this.logger.debug(`${this.name}::restartIce()`);const e=await this.pc.createOffer({iceRestart:!0});return this.logger.debug(`[SDP] ${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`[SDP] ${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:a,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly",...this._direction==="send"?{sendEncodings:[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]}:{}});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`[SDP] connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`[SDP] ${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}async getTransportStats(){return this.pc.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}async stopSending(e){this._assertSendDirection(),this.logger.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this.pc.removeTrack(r.sender),r.direction="inactive";const i=await this.pc.createOffer();return this.logger.debug(`[SDP] stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`[SDP] stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(o)}]`),await this.pc.setRemoteDescription(o),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");await i.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters();a.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(a)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters();a.encodings.forEach((o,c)=>{a.encodings[c]={...o,...r}}),await i.sender.setParameters(a)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{this.logger.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{this.logger.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{this.logger.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{this.logger.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class fh extends mh{static createFactory(t){return()=>new fh(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},a),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(u=>{var f;const p=d.codecs.find(T=>T.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const T=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];T.push(...u.parameters);const E=Array.from(new Set(T).values());p.sdpFmtpLine=E.join(";")}l.push(p)}),this.logger.info(`selected codecs: ${JSON.stringify(l)}`),a.setCodecPreferences(l)}const o=await this.pc.createOffer();if(await this.pc.setLocalDescription(o),r&&r.findIndex(({name:d})=>d==="opus")>=0){const{enableDtx:d,enableStereo:l}=this,u=this.enableHighBitrate?l?128e3:64e3:l?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${d?"usedtx=1;":""}${l?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${u}`),o.sdp+=`a=rtcp-fb:111 nack\r
|
|
9
|
+
`}this.midTransceiverMap.set(a.mid,a);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),a.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:a.sender,mid:a.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}class cd extends mh{constructor(e,r){super(e);h(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new cd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:a}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[a?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const p=c.sender.getParameters();p.encodings=r,await c.sender.setParameters(p)}const d=(p,f)=>{var x;const T=rs.parse(p),E=T.media[T.media.length-1],b=E.rtp.filter(N=>f.some($=>$.name===N.codec)),_=E.fmtp.filter(N=>b.some($=>$.payload===N.payload)),k=(x=E.rtcpFb)==null?void 0:x.filter(N=>b.some($=>$.payload===N.payload)),A=b.map(N=>N.payload);return T.media[T.media.length-1].rtp=b,T.media[T.media.length-1].fmtp=_,T.media[T.media.length-1].rtcpFb=k,T.media[T.media.length-1].payloads=A.join(" "),rs.write(T)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:p,enableStereo:f}=this,T=this.enableHighBitrate?f?128e3:64e3:f?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${f?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${T}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async p=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(p)}]`),await this.pc.setRemoteDescription(p),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters(),o=a.encodings.length-1-r;a.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(a)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const a=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(a)))}})}}class Th extends mh{static createFactory(t){return()=>new Th(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var f;const p=o.codecs.find(T=>T.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const T=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];T.push(...u.parameters);const E=[...new Set(T).values()];p.sdpFmtpLine=E.join(";")}c.push(p)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),a.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:p}=this,f=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${f}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),a.mid),sender:a.sender,mid:a.mid}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function K0(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}var $o,bi,bs,Rd,_s,Tr,Bo,_u,kd,bf,Md,_f;class z0 extends wl{constructor(e,r){var i;super(e);g(this,_s);g(this,Bo);g(this,kd);g(this,Md);h(this,"rtpReceiver");h(this,"id");h(this,"localId");h(this,"producerId");h(this,"producingTransportId");h(this,"mimeType");h(this,"track");h(this,"peerId");h(this,"appData");h(this,"transceiver");g(this,$o,void 0);g(this,bi,void 0);g(this,bs,void 0);g(this,Rd,void 0);this.id=r.id,this.localId=r.localId,m(this,$o,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,m(this,bs,!1),this.producerId=r.producerId,this.track=r.track,m(this,bi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,L(this,kd,bf).call(this),m(this,Rd,e)}get closed(){return n(this,bs)}get kind(){return this.track.kind}get paused(){return n(this,bi)}close(e,r){n(this,bs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,n(this,_s,Tr)),m(this,bs,!0),r&&(L(this,Md,_f).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(n(this,bs))throw new yt("closed");return n(this,$o).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",n(this,_s,Tr)),n(this,bs)){this.logger.error("consumer::pause() | Consumer closed",n(this,_s,Tr));return}m(this,bi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",n(this,_s,Tr)),n(this,bs)){this.logger.error("Consumer::resume() | Consumer closed",n(this,_s,Tr));return}m(this,bi,!1),this.track.enabled=!0,this.safeEmit("resume")}}$o=new WeakMap,bi=new WeakMap,bs=new WeakMap,Rd=new WeakMap,_s=new WeakSet,Tr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Bo=new WeakSet,_u=function(){this.logger.debug('Consumer::track "ended" event',n(this,_s,Tr)),this.safeEmit("trackended")},kd=new WeakSet,bf=function(){this.track.addEventListener("ended",L(this,Bo,_u).bind(this))},Md=new WeakSet,_f=function(){try{this.track.removeEventListener("ended",L(this,Bo,_u)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...n(this,_s,Tr),error:e})}};var cs,ea,ta,_i,Jt,Ke,Or,sa,Id,It,ss;class Y0 extends wl{constructor(e,r){var i,a;super(e);g(this,It);h(this,"id");h(this,"localId");g(this,cs,void 0);h(this,"kind");h(this,"appData");h(this,"rtpSender");g(this,ea,void 0);g(this,ta,void 0);g(this,_i,void 0);g(this,Jt,!1);g(this,Ke,void 0);g(this,Or,void 0);g(this,sa,void 0);g(this,Id,void 0);this.id=r.id,this.localId=r.localId,m(this,Ke,r.track),this.kind=(i=r.track)==null?void 0:i.kind,m(this,Or,r.disableTrackOnPause?!((a=r.track)!=null&&a.enabled):!1),m(this,sa,void 0),m(this,ea,r.stopTracks),m(this,ta,r.disableTrackOnPause),m(this,_i,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),m(this,cs,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),m(this,Id,e)}get closed(){return n(this,Jt)}get track(){return n(this,Ke)}get paused(){return n(this,Or)}get maxSpatialLayer(){return n(this,sa)}async close(e){if(n(this,Jt))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,n(this,It,ss)),m(this,Jt,!0),this._destroyTrack(),e===dd){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await n(this,cs).stopSending(this.localId),{answer:a}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(a)}async getStats(){if(n(this,Jt))throw new yt("closed");return n(this,cs).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",n(this,It,ss)),n(this,Jt)&&this.logger.error("Producer::pause() | Producer closed",n(this,It,ss)),m(this,Or,!0),n(this,Ke)&&n(this,ta)&&(n(this,Ke).enabled=!1),n(this,_i)&&n(this,cs).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",n(this,It,ss)),n(this,Jt)){this.logger.error("Producer::resume() | Producer closed",n(this,It,ss));return}m(this,Or,!1),n(this,Ke)&&n(this,ta)&&(n(this,Ke).enabled=!0),n(this,_i)&&n(this,cs).replaceTrack(this.localId,n(this,Ke)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,n(this,It,ss)),n(this,Jt)){if(e&&n(this,ea))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...n(this,It,ss),error:r})}throw new yt("closed")}else if(e&&e.readyState==="ended")throw new yt("track ended");if(e===n(this,Ke)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,n(this,It,ss));return}(!n(this,_i)||!n(this,Or))&&await n(this,cs).replaceTrack(this.localId,e),this._destroyTrack(),m(this,Ke,e),this._handleTrack()}async setMaxSpatialLayer(e){if(n(this,Jt))throw new yt("closed");if(this.kind!=="video")throw new go("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await n(this,cs).setMaxSpatialLayer(this.localId,e),m(this,sa,e)}async setRtpEncodingParameters(e){if(n(this,Jt))throw new yt("closed");if(typeof e!="object")throw new TypeError("invalid params");await n(this,cs).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,n(this,It,ss)),this.safeEmit("trackended",this.track.id)}_handleTrack(){n(this,Ke)&&n(this,Ke).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(n(this,Ke))try{n(this,Ke).removeEventListener("ended",this._onTrackEnded),n(this,ea)&&n(this,Ke).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...n(this,It,ss),error:r})}}}cs=new WeakMap,ea=new WeakMap,ta=new WeakMap,_i=new WeakMap,Jt=new WeakMap,Ke=new WeakMap,Or=new WeakMap,sa=new WeakMap,Id=new WeakMap,It=new WeakSet,ss=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function wf(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Jl(s){return Math.random().toString(36).substring(2,2+s)}const xc=1;function Hp(s){const t=s;return delete t.payload._bolt,t}function Q0(s){return s.payload&&wf(s.payload)}function X0(s){var t,e;return Q0(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}var Nr,Ad,wi;const ln=class extends st.EventEmitter{constructor(e,r,i,a){super();h(this,"channel");h(this,"queue");h(this,"serverProtocolVersion");g(this,Nr,new Map);g(this,Ad,void 0);g(this,wi,void 0);h(this,"respond",(e,r,i=!1)=>{let a;i?a=ln.createErrorResponse(e,r):a=ln.createResponse(e,r),this.channel.send(JSON.stringify(a))});h(this,"notify",e=>{const r=ln.createNotification(e);this.channel.send(JSON.stringify(r))});h(this,"request",async e=>{const r=ln.createRequest(e),i=new Promise((a,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),a(u))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(u))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});h(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const a=i-200,o=Math.ceil(r.length/a),c=[];for(let l=0;l<o;l+=1){const u=l*a,p=(l+1)*a;c.push(r.slice(u,p))}const d=nr.v4();for(let l=0;l<o;l+=1){const u=c[l],f=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});n(this,wi).debug(`Sending message chunk over dc: ${f}`),this.channel.send(f)}}else n(this,wi).debug(`Sending message over dc: ${r}`),this.channel.send(r)});h(this,"processMessage",e=>{var i;n(this,Nr).has(e.id)||n(this,Nr).set(e.id,[]);const r=n(this,Nr).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(a=>a===void 0)){const a=n(this,Nr).get(e.id),o=a==null?void 0:a.reduce((d,l)=>d+l.chunk,"");n(this,Nr).delete(e.id);const c=JSON.parse(o);if(!c.payload||!wf(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});h(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(n(this,wi).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(Hp(e)):i.resolve(Hp(e)),!0):!1});h(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:Jl(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=a,m(this,Ad,e),m(this,wi,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Zr=ln;Nr=new WeakMap,Ad=new WeakMap,wi=new WeakMap,h(Zr,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:Jl(8),type:"REQUEST",version:xc}}}}),h(Zr,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:xc}}}}),h(Zr,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:Jl(8),type:"NOTIFY",version:xc}}}}),h(Zr,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:xc}}}));const dd="transport closed";var Ci;const un=class extends wl{constructor(e,{id:r,direction:i,handlerFactory:a,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:p}){var b,_,k;super(e);h(this,"awaitQueue");h(this,"observer");h(this,"id");h(this,"serverId");h(this,"direction");h(this,"maxSctpMessageSize");h(this,"handler");h(this,"connectionState","new");h(this,"producers");h(this,"consumers");h(this,"datachannels");h(this,"connected",!1);h(this,"eventsDCReadyPromise");h(this,"eventsDCReadyPromiseResolver");h(this,"eventsDCFailureTimer");h(this,"transportConnectionPromise");h(this,"consumerTrackEvents");h(this,"unknownTracksMap");h(this,"appData");g(this,Ci,void 0);m(this,Ci,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const T=K0(l,{});delete T.iceServers,delete T.iceTransportPolicy,delete T.bundlePolicy,delete T.rtcpMuxPolicy,delete T.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new bu(f,!0),this.handler=a(),this.handler.enableHighBitrate=(b=p==null?void 0:p.enableHighBitrate)!=null?b:!1,this.handler.enableStereo=(_=p==null?void 0:p.enableStereo)!=null?_:!1,this.handler.enableDtx=(k=p==null?void 0:p.enableDtx)!=null?k:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const E=3e4;this.transportConnectionPromise=new Promise(A=>{const x=setTimeout(()=>{f.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),A(!1)},E);this.once("connected",()=>{clearTimeout(x),A(!0)}),this.once("disconnect",()=>{clearTimeout(x),A(!1)}),this.once("close",()=>{clearTimeout(x),A(!1)})}),this.eventsDCReadyPromise=new Promise(A=>{this.eventsDCReadyPromiseResolver=A}),this.handler.on("@connectionstatechange",A=>{A!==this.connectionState&&(this.logger.debug(`connection state changed to ${A}`),this.connectionState=A,A==="connected"&&(this.connected=!0,this.emit("connected")),A==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(A==="failed"||A==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",A))}),this.handler.on("@icecandidate",({candidate:A})=>{this.closed||this.safeEmit("icecandidate",A)}),this.handler.on("dc_open",A=>{let x=this.datachannels.get(A.label);x||(x||(x=new Zr(n(this,Ci),A,A.label,this.serverId),this.datachannels.set(A.label,x)),this.eventsDCFailureTimer=setTimeout(()=>{A.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",A.label))},5e3))}),this.handler.on("datachannel",(A,x)=>{A.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const N=this.datachannels.get(A.label);if(!N){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:A.label,message:x}});return}try{const $=JSON.parse(x);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:$.id,count:$.count,chunkIndex:$.chunkIndex,chunk:$.chunk,transprtId:this.serverId}});const K=N.processMessage($);if(!K)return;this.logger.debug(`datachannel message with id:${$.id} on transport:${this.serverId}complete - ${JSON.stringify(K)}`),this.emit(`datachannel:${A.label}`,N.label,K)}catch($){this.logger.error("error parsing message",{error:$})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(dd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(dd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new yt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:a,answer:o}=await e(r);this.setServerId(a),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new yt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new go("not a sending Transport");if(r.readyState==="ended")throw new yt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Er("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:a,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:p={}}=e;this.logger.debug(`produce() [track:${a.id}]`);const{producerId:f,localId:T,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:b,callback:_,sender:k,mid:A}=await this.handler.send({track:a,encodings:o,codecOptions:c,screenShare:p==null?void 0:p.screenShare}),{answer:x,producerId:N}=await r({offer:b,kind:a.kind,paused:l?!a.enabled||Object.hasOwn(a,"fakeTracks"):!1,appData:{...p||{},mid:A},codecOptions:c,producingTransportId:this.serverId}),$=await _(x);return{producerId:N,localId:$,rtpSender:k}},"Transport.produce");return this.createProducerObject({id:f,localId:T,track:a,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:p,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new Y0(n(this,Ci),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new yt("closed");if(this.direction!=="recv")throw new go("not a receiving transport");if(!await this.transportConnectionPromise)throw new Er("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const a={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,p)=>{a[p]=this.createConsumerObjectAndWaitForTrack({...u,producerId:p})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(a).map(([u,p])=>p.then(f=>l.push(f)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=rs.parse(e.sdp),a={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(a[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),a}static setCodecAndFmtpMappings(e,r,i){const a=rs.parse(e.sdp);return a.media=a.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:rs.write(a)}}static parseHeaderExtensionMappings(e){const r=rs.parse(e.sdp),i={};return r.media.forEach(a=>{i[a.mid]=a.ext}),i}static setHeaderExtensionMappings(e,r){const i=rs.parse(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:rs.write(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),a=un.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=un.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=un.setCodecAndFmtpMappings(c,i,a),c=un.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=rs.parse(r.sdp);return i.media=i.media.map(a=>{if(a.type==="audio"){const o={...a},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return a}),r.sdp=rs.write(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const a=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(a)});const o=this.consumerTrackEvents.get(a);o?(o(r,i),this.consumerTrackEvents.delete(a)):(this.logger.warn(`track event handler not found ${a}`),this.unknownTracksMap.set(a,e))}sendErrorOverDC(e,r,i){const a=this.getDatachannel(e);if(!a)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});a.respond(r,i,!0)}sendResponseOverDC(e,r,i){const a=this.getDatachannel(e);if(!a)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});a.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:a,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:p,mimeType:f}=e,T=`${c}:${p}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(b,_)=>{const k=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${T} producingPeerId: ${a}`),this.consumerTrackEvents.delete(T),E.isTimedout=!0,_(E)},5e3),A=(N,$)=>{try{if(N.readyState==="ended")clearTimeout(k),_(E);else{const K=N;K.enabled=!0,this.handler.midTransceiverMap.set($.mid,$);const Y=new z0(n(this,Ci),{id:r,localId:$.mid,transceiver:$,track:K,paused:d,producerId:i,producingPeerId:a,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:a},rtpReceiver:$.receiver,mimeType:f});this.consumers.set(r,Y),Y.once("close",()=>{this.consumers.delete(Y.id),this.handler.midTransceiverMap.delete($.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:p,appData:{screenShare:l},peerId:a,producerId:i}}),this.emit("newconsumer",Y),clearTimeout(k),b(Y)}}catch(K){this.logger.warn("error while creating consumer:",K),clearTimeout(k),_(E)}},x=this.unknownTracksMap.get(T);x?(this.logger.info(`track event already received [trackId: ${x.track.id}] [mid: ${x.transceiver.mid}]`),this.unknownTracksMap.delete(T),A(x.track,x.transceiver)):(this.logger.info(`Registering onTrack handler for key ${T} [producingPeerId: ${a}]`),this.consumerTrackEvents.set(T,A))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw q0("DC_NOT_READY",`${e} datachannel not ready`);const a=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(a)}`),a}};let wu=un;Ci=new WeakMap;function Z0(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=fg.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}var Gs,Ri;class eD{constructor(t,{handlerName:e,handlerFactory:r}={}){h(this,"handlerFactory");g(this,Gs,void 0);g(this,Ri,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),m(this,Gs,t),m(this,Ri,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)n(this,Ri).debug(`Device::constructor() | handler given: ${e}`);else if(e=Z0(n(this,Ri)),e)n(this,Ri).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=fh.createFactory(n(this,Gs));break;case"Safari12":this.handlerFactory=Th.createFactory(n(this,Gs));break;case"Firefox60":this.handlerFactory=cd.createFactory(n(this,Gs),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=cd.createFactory(n(this,Gs),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=nr.v4();return new wu(n(this,Gs),{id:e,...t,handlerFactory:this.handlerFactory})}}Gs=new WeakMap,Ri=new WeakMap;const tD=2e3;var ra,Ze,et,Ho,Fo,ki,ia,qo,na,Mi,ws,aa,Kc,jo,Cu,Dd,Cf,Go,Ru,Od,Rf,Nd,kf,Ld,Mf,Vd,If,xd,Af,Wo,ku,Jo,Mu;class sD extends st.EventEmitter{constructor(e,r){super();g(this,aa);g(this,jo);g(this,Dd);g(this,Go);g(this,Od);g(this,Nd);g(this,Ld);g(this,Vd);g(this,xd);g(this,Wo);g(this,Jo);h(this,"context");g(this,ra,void 0);g(this,Ze,void 0);g(this,et,void 0);g(this,Ho,void 0);g(this,Fo,void 0);g(this,ki,void 0);g(this,ia,void 0);g(this,qo,void 0);g(this,na,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,Mi,void 0);g(this,ws,"all");this.context=e,m(this,ki,r),m(this,ra,new eD(e)),m(this,ia,new J0(r)),m(this,qo,gs),n(this,aa,Kc).mediaState={send:{state:mn.NEW},recv:{state:mn.NEW}},ya(this.context,"forceRelay")&&m(this,ws,"relay"),this.logger.info(`ICE Transport Policy initially set to ${n(this,ws)}`),L(this,jo,Cu).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return n(this,ki)}get socketHandler(){return n(this,ia)}get sendTransport(){return n(this,Ze)}get recvTransport(){return n(this,et)}get events(){return n(this,qo)}set sendTransportConnectedCallback(e){m(this,Ho,e)}set recvTransportConnectedCallback(e){m(this,Fo,e)}async setupTransports(e){await L(this,Dd,Cf).call(this,e);let r,i;e.send&&(r=L(this,Go,Ru).call(this,n(this,Ze)).then(a=>{try{n(this,Ho).call(this,a)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=L(this,Go,Ru).call(this,n(this,et)).then(a=>{try{n(this,Fo).call(this,a)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,Ze);this.logger.info("Closing send transport",{transport:{id:a,serverId:o,type:c}}),n(this,Ze).close(),n(this,Ze).removeAllListeners(),m(this,Ze,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,et);this.logger.info("Closing recv transport",{transport:{id:a,serverId:o,type:c}}),(r=n(this,et))==null||r.close(),(i=n(this,et))==null||i.removeAllListeners(),m(this,et,void 0)}L(this,jo,Cu).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}ra=new WeakMap,Ze=new WeakMap,et=new WeakMap,Ho=new WeakMap,Fo=new WeakMap,ki=new WeakMap,ia=new WeakMap,qo=new WeakMap,na=new WeakMap,Mi=new WeakMap,ws=new WeakMap,aa=new WeakSet,Kc=function(){return this.context.getValue("connectionHandler")},jo=new WeakSet,Cu=function(){m(this,Mi,{send:void 0,recv:void 0})},Dd=new WeakSet,Cf=async function(e){var o,c,d,l,u,p,f,T;ya(this.context,"forceRelay")&&m(this,ws,"relay"),this.logger.info(`ICE Transport Policy set to ${n(this,ws)}`);const a=await ht().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&L(this,Nd,kf).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(f=(p=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:p.enableStereo)!=null?f:!1,enableDtx:!1},iceTransportPolicy:n(this,ws)}),e.recv&&L(this,Ld,Mf).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(T=this.context.getValue("modules").e2ee)==null?void 0:T.enabled},iceTransportPolicy:n(this,ws)})},Go=new WeakSet,Ru=async function(e){const{id:r,serverId:i,direction:a}=e;L(this,Vd,If).call(this,e);try{return await Pf(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:a}});try{if(e.closed)throw new Er("Cannot reconnect closed transport");await L(this,Od,Rf).call(this,e)}catch(l){if(l instanceof Er){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:a}}),e.close(),e.removeAllListeners(),o}},Od=new WeakSet,Rf=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!n(this,ki).isConnected)throw new Er("Socket is not connected");if(e.connectionState==="closed")throw new Er("Transport is closed");try{await e.connect(a=>L(this,xd,Af).call(this,i,a)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(a){throw n(this,na).transportFailureCount[i]+=1,a.message==="ice connection failed"?new Er(a.message):a}},Nd=new WeakSet,kf=function(e){var r,i;if(n(this,Ze)&&n(this,Ze).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=n(this,Ze))==null?void 0:r.id,serverId:(i=n(this,Ze))==null?void 0:i.serverId,type:"send"}});return}m(this,Ze,n(this,ra).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(n(this,Ze))},Ld=new WeakSet,Mf=function(e){var r,i;if(n(this,et)&&n(this,et).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=n(this,et))==null?void 0:r.id,serverId:(i=n(this,et))==null?void 0:i.serverId,type:"recv"}});return}m(this,et,n(this,ra).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(n(this,et))},Vd=new WeakSet,If=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async a=>{L(this,Jo,Mu).call(this,{state:a,direction:r}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:a}});const o=()=>{const c=n(this,Mi)[r];c!==void 0&&(clearTimeout(c),n(this,Mi)[r]=void 0)};switch(a){case"connected":o(),n(this,na).lastConnectionTime=performance.now();break;case"disconnected":n(this,Mi)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await L(this,Wo,ku).call(this,e.direction)},tD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await L(this,Wo,ku).call(this,e.direction);break}}),e.on("icecandidate",async a=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:a})}),e.on("datachannel:events",async(a,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:a,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(a,X0(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${a}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},xd=new WeakSet,Af=async function(e,r){const i=e==="recv";try{const{sdp:a,type:o}=r,c={consuming:i,description:{sdp:a,type:o,target:i?or.SUBSCRIBER:or.PUBLISHER},producers:[]};return n(this,ia).connectTransport(c)}catch(a){throw this.logger.error(`Error in ${e} transport connection:`,{error:a}),a}},Wo=new WeakSet,ku=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),n(this,ki).isConnected&&n(this,na).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),m(this,ws,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:n(this,Ze)}),this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:n(this,et)}),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}L(this,Jo,Mu).call(this,{state:mn.CONNECTED,direction:e})},Jo=new WeakSet,Mu=function(e){const{state:r,direction:i}=e;n(this,aa,Kc).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(w.TRANSPORT_STATE_UPDATE,{transport:i,...n(this,aa,Kc).mediaState[i]})};var Ud,Kt;class rD{constructor(t,e,r,i,a){g(this,Ud,void 0);g(this,Kt,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=a,m(this,Ud,t),m(this,Kt,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:p}=d,f={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:p,...f})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),a=new Map;t.forEach(d=>a.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=a.get(d);if(!u)return;if(l.errorCode){n(this,Kt).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let p={};try{p=JSON.parse(l.producerState.appData)}catch(f){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:p})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{n(this,Kt).info("Negotiating socket consumer",{transport:this.recvTransport}),n(this,Kt).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:or.SUBSCRIBER}};return n(this,Kt).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,z_.toBinary(r)),n(this,Kt).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){n(this,Kt).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const a=r.map(l=>l.localId);n(this,Kt).info(`Closing consumers: ${JSON.stringify(a)}`);const o={description:{sdp:i.sdp,type:i.type,target:or.SUBSCRIBER},consumerIds:a,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=PC.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(a=>a&&a.id);i.forEach(({id:a,producingTransportId:o,localId:c})=>{r.requests.push({producerId:a,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),n(this,Kt).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:a})=>a)})}}Ud=new WeakMap,Kt=new WeakMap;class Sh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return rs.parse(t).media.filter(a=>e==="video"?a.type==="video":a.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:a,producingTransportId:o}){var p,f;const c=Sh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:or.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(p=i.screenShare)!=null?p:!1,mimeType:`${e}/${(f=a[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}var Ii,Lr,oa,Ko,Cs,$d,Ws,ca,zo,Iu,Bd,Df,Hd,Of,Fd,Nf,qd,Lf;class iD extends sD{constructor(e,r){super(e,r);g(this,zo);g(this,Bd);g(this,Hd);g(this,Fd);g(this,qd);g(this,Ii,void 0);g(this,Lr,void 0);g(this,oa,void 0);g(this,Ko,void 0);g(this,Cs,void 0);g(this,$d,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,Ws,[]);g(this,ca,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{m(this,Ko,new Sh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{n(this,oa).clear(),m(this,Cs,new rD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return n(this,Ii)}get consumers(){return n(this,Lr)}get producerIdToConsumerIdMap(){return n(this,oa)}get logger(){return this.context.getValue("logger")}reset(){m(this,Ii,new Map),m(this,Lr,new Map),m(this,oa,new Map)}async createProducer(e,r){var i,a;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,L(this,Bd,Df).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,o),L(this,Hd,Of).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((a=e==null?void 0:e.track)==null?void 0:a.kind)||"unknown"} producer`,{error:o}),n(this,$d).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var a;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),(a=this.context.getValue("modules").e2ee)!=null&&a.enabled&&this.context.getValue("peerSessionStore").emit(w.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(n(this,Ii).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){n(this,ca)||clearTimeout(n(this,ca)),m(this,Ws,n(this,Ws).concat(e)),await L(this,zo,Iu).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!n(this,Cs))return;const r=e.map(a=>this.consumers.get(a)).filter(a=>a!==void 0);if(r.length===0)return;const{failedConsumers:i}=await n(this,Cs).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(n(this,Lr).keys()))}async switchConsumersToLayer(e,r){n(this,Cs).switchConsumersToLayer(e,r)}}Ii=new WeakMap,Lr=new WeakMap,oa=new WeakMap,Ko=new WeakMap,Cs=new WeakMap,$d=new WeakMap,Ws=new WeakMap,ca=new WeakMap,zo=new WeakSet,Iu=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=n(this,Ws).splice(0,n(this,Ws).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),a=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(a.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(a,L(this,Fd,Nf).bind(this),n(this,Cs).negotiate.bind(n(this,Cs)));if(o.forEach(L(this,qd,Lf).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);m(this,Ws,n(this,Ws).concat(d)),m(this,ca,setTimeout(L(this,zo,Iu).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(a){}await this.setupTransports({recv:!0})}}},Bd=new WeakSet,Df=function(e){return n(this,Ko).create(e)},Hd=new WeakSet,Of=function(e,r){e.on("close",async(i,a)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==dd){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:or.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),a({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),n(this,Ii).set(e.id,e)},Fd=new WeakSet,Nf=async function(e){try{return await this.recvTransport.canConsume(),await n(this,Cs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},qd=new WeakSet,Lf=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),n(this,Lr).delete(e.id),this.context.getValue("peerSessionStore").emit(w.CONSUMER_CLOSED,{id:e.id})}),n(this,Lr).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(w.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};var Yo,Qo,Xo,da,la,ua,Zo,ec,ha,ft,ds,ls,Ai,Di,Js,tc,jd,Vf,Gd,xf,Wd,Uf,Jd,$f;const Kd=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:a=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,jd);g(this,Gd);g(this,Yo,void 0);g(this,Qo,void 0);g(this,Xo,void 0);g(this,da,void 0);g(this,la,void 0);g(this,ua,void 0);g(this,Zo,void 0);g(this,ec,void 0);g(this,ha,void 0);g(this,ft,void 0);g(this,ds,void 0);g(this,ls,!1);g(this,Ai,0);g(this,Di,0);g(this,Js,[]);g(this,tc,void 0);m(this,da,t),m(this,ft,t),m(this,Yo,e),m(this,Qo,r),m(this,Xo,i),m(this,la,a),m(this,ua,o),m(this,Zo,c),m(this,ec,d),m(this,ha,l),m(this,tc,u),m(this,ds,t/2)}get voiceDetected(){return n(this,ls)}processAudioChunk(t){var o,c;const e=L(o=Kd,Wd,Uf).call(o,t),r=L(c=Kd,Jd,$f).call(c,t);return L(this,jd,Vf).call(this,e),e/n(this,ds)>n(this,ha)&&e>n(this,ft)&&r>n(this,Yo)?(m(this,Ai,n(this,Ai)+1),m(this,Di,n(this,Xo)),n(this,Ai)>=n(this,Qo)&&m(this,ls,!0)):(m(this,Ai,0),n(this,Di)>0?m(this,Di,n(this,Di)-1):n(this,ls)&&m(this,ls,!1),n(this,ls)||L(this,Gd,xf).call(this,e)),{energy:e,isVoice:n(this,ls)}}reset(){m(this,ls,!1),m(this,Ai,0),m(this,Di,0),m(this,ft,n(this,da)),m(this,ds,n(this,da)/2),m(this,Js,[])}getThresholdInfo(){return{currentEnergyThreshold:n(this,ft),backgroundNoiseEnergy:n(this,ds),energyRatioThreshold:n(this,ha)}}};let Ya=Kd;Yo=new WeakMap,Qo=new WeakMap,Xo=new WeakMap,da=new WeakMap,la=new WeakMap,ua=new WeakMap,Zo=new WeakMap,ec=new WeakMap,ha=new WeakMap,ft=new WeakMap,ds=new WeakMap,ls=new WeakMap,Ai=new WeakMap,Di=new WeakMap,Js=new WeakMap,tc=new WeakMap,jd=new WeakSet,Vf=function(t){n(this,ls)?m(this,ft,n(this,ua)*n(this,ft)+(1-n(this,ua))*t):m(this,ft,n(this,la)*n(this,ft)+(1-n(this,la))*n(this,ds)),m(this,ft,Math.max(n(this,Zo),Math.min(n(this,ec),n(this,ft))))},Gd=new WeakSet,xf=function(t){if(t<n(this,ft)*1.2)if(n(this,Js).push(t),n(this,Js).length>n(this,tc)&&n(this,Js).shift(),n(this,Js).length>=10){const e=[...n(this,Js)].sort((i,a)=>i-a),r=Math.floor(e.length/2);m(this,ds,e[r])}else m(this,ds,.95*n(this,ds)+.05*t)},Wd=new WeakSet,Uf=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Jd=new WeakSet,$f=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(Ya,Wd),g(Ya,Jd);var sc;class Fp{constructor(t){h(this,"RNAudioSampleHandler");g(this,sc,void 0);m(this,sc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return n(this,sc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}sc=new WeakMap;var rc;class qp{constructor(t){h(this,"audioContext");h(this,"analyser");g(this,rc,void 0);m(this,rc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return n(this,rc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}rc=new WeakMap;class nD{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const aD=60,oD=400;var Ks,zs,Ys,ic,pa,ga,Vr,Oi,ma,Ni,Qs,Rs,zd,Bf,nc,Au,Yd,Hf,Qd,Ff;const oo=class{constructor(t,e){g(this,zd);g(this,Yd);g(this,Ks,void 0);g(this,zs,void 0);g(this,Ys,void 0);g(this,ic,void 0);g(this,pa,void 0);g(this,ga,void 0);g(this,Vr,void 0);g(this,Oi,void 0);g(this,ma,void 0);g(this,Ni,void 0);g(this,Qs,void 0);g(this,Rs,void 0);this.reportRequest=e,m(this,Ni,t),m(this,ga,new Ya);const{isReactNative:r}=navigator;m(this,Qs,r?new Fp(n(this,Ni)):new qp(n(this,Ni))),m(this,Rs,r?nD:Uc)}get logger(){return n(this,Ni).getValue("logger")}set producerId(t){m(this,Ys,t)}set audioTrack(t){m(this,ic,t),n(this,Qs)instanceof qp&&(n(this,Qs).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${n(this,Ys)}`),n(this,Ks)&&n(this,Rs).clearInterval(n(this,Ks)),m(this,Ks,n(this,Rs).setInterval(async()=>{var i;if(!n(this,ic)||!n(this,Ys))return;const{energy:t}=L(this,zd,Bf).call(this),e=L(i=oo,nc,Au).call(i,t);let r=.9;n(this,ma)!==e&&n(this,ma)?r=.9:e?r=.3:r=.5,m(this,pa,(n(this,pa)||0)*(1-r)+t*r)},aD)),n(this,zs)&&n(this,Rs).clearInterval(n(this,zs)),m(this,zs,n(this,Rs).setInterval(L(this,Yd,Hf).bind(this),oD))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${n(this,Ys)}`),n(this,Ks)&&(n(this,Rs).clearInterval(n(this,Ks)),m(this,Ks,void 0)),n(this,zs)&&(n(this,Rs).clearInterval(n(this,zs)),m(this,zs,void 0))}catch(t){}n(this,ga).reset(),n(this,Qs)instanceof Fp&&n(this,Qs).stop()}};let Qa=oo;Ks=new WeakMap,zs=new WeakMap,Ys=new WeakMap,ic=new WeakMap,pa=new WeakMap,ga=new WeakMap,Vr=new WeakMap,Oi=new WeakMap,ma=new WeakMap,Ni=new WeakMap,Qs=new WeakMap,Rs=new WeakMap,zd=new WeakSet,Bf=function(){var o;const{samples:t}=n(this,Qs),{energy:e,isVoice:r}=n(this,ga).processAudioChunk(t),i=L(o=oo,Qd,Ff).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,Vr)||i<n(this,Vr))&&m(this,Vr,i),(!n(this,Oi)||i>n(this,Oi))&&m(this,Oi,i),{energy:(i-n(this,Vr))/(n(this,Oi)-n(this,Vr))*10||0,isVoice:r})},nc=new WeakSet,Au=function(t){return t<5},Yd=new WeakSet,Hf=function(t=n(this,pa)){var r;if(!n(this,Ys)||!t)return;const e={producerId:n(this,Ys),energy:Math.round(t),silent:L(r=oo,nc,Au).call(r,t)};m(this,ma,e.silent),this.reportRequest(e)},Qd=new WeakSet,Ff=function(t){const e=Math.log10(t);return Math.round(e)},g(Qa,nc),g(Qa,Qd);var cD=Object.defineProperty,dD=Object.getOwnPropertyDescriptor,ne=(s,t,e,r)=>{for(var i=r>1?void 0:r?dD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&cD(t,e,i),i},ac,oc,tt,q,Xd,dt,Li,Vi,xi,cc,zt,Xs,lt,Tt,xr,nn,Zd,qf,el,jf,tl,Gf,dc,Du,sl,Wf,rl,Jf,ut,_t,Ui,Xa,il,Kf,nl,zf,al,Yf;class se{constructor(t,e){g(this,xr);g(this,Zd);g(this,el);g(this,tl);g(this,dc);g(this,sl);g(this,rl);g(this,ut);g(this,Ui);g(this,il);g(this,nl);g(this,al);h(this,"context");h(this,"authToken");h(this,"e2ee");g(this,ac,void 0);g(this,oc,void 0);g(this,tt,void 0);g(this,q,void 0);g(this,Xd,void 0);g(this,dt,void 0);g(this,Li,void 0);g(this,Vi,void 0);g(this,xi,void 0);g(this,cc,void 0);g(this,zt,null);g(this,Xs,void 0);g(this,lt,void 0);g(this,Tt,void 0);var i,a;this.context=t;const{socket:r}=e;this.mediaJoined=!1,m(this,tt,r),m(this,Li,!1),m(this,q,new iD(t,r)),m(this,dt,n(this,q).events),m(this,Xs,new Set),m(this,lt,new Map),m(this,Vi,!1),m(this,xi,new bu(t.getValue("logger"))),m(this,Tt,new Qa(this.context,n(this,q).socketHandler.audioActivity.bind(n(this,q).socketHandler))),this.e2ee=(a=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?a:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,cc,sh(async()=>{if(!n(this,xr,nn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(n(this,oc),n(this,ac),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return n(this,xr,nn).mediaJoined}set mediaJoined(t){n(this,xr,nn).mediaJoined=t}reset(){n(this,q).closeAllProducers(),n(this,q).closeAllConsumers(),n(this,lt).clear(),n(this,Xs).clear(),m(this,zt,null),n(this,xi).stop(),n(this,q).stopAllTransports(),n(this,q).reset(),m(this,xi,new bu)}async joinRoom(t,e,r=!1,i=!1,a={}){n(this,xr,nn).mediaJoinAttempted=!0,m(this,Li,!0),r&&this.reset();try{return await n(this,xi).push(()=>L(this,Zd,qf).call(this,t,e,i,a),"joinRoom")}catch(o){return this.logger.error("Error in room joining process",{error:o}),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return n(this,zt)?n(this,zt):(m(this,zt,(async()=>{try{await L(this,dc,Du).call(this,t,e,r,i)}catch(a){throw m(this,zt,null),a}})()),n(this,zt))}getConsumers(){return n(this,q).consumers}getProducers(){return n(this,q).producers}async leaveRoom(){n(this,q).stopAllTransports(),m(this,Vi,!1),n(this,xr,nn).mediaJoinAttempted=!1;const t={closeRoom:!1};n(this,tt).sendMessagePromise(n(this,dt).leaveRoom,yw.toBinary(t)).then(r=>{var i;(i=cC.fromBinary(r.payload))!=null&&i.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(r=>{this.logger.error("error on sending leave room request",{error:r})}),this.context.getValue("callstats").callEnded(),await this.context.getValue("telemetry").destruct()}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():n(this,q).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const a=n(this,q).producerIdToConsumerIdMap.get(i.producerId);return a?(r.push(a),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await n(this,q).closeConsumers(e)}async _shareWebcam(t){var u,p,f,T;const e=Ee.WEBCAM,r=L(this,ut,_t).call(this,e);if(r){const E=await r;if(n(this,q).producers.has(E)){const b=n(this,q).producers.get(E);if(!b.closed)return await b.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=L(this,al,Yf).call(this,t),a=ya(this.context,"disableSimulcast"),o=(p=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:p.simulcastConfig;a||o&&o.disable||!((T=(f=this.context)==null?void 0:f.getValue("theme"))!=null&&T.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=YA(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,lt).delete(e)},l=n(this,q).createProducer(i,d);return L(this,Ui,Xa).call(this,e,l.then(E=>E.id)),l.then(E=>E.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ge.isElectron()},stopTracks:!1},a=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,lt).delete(Ee.SCREENSHARE_VIDEO),n(this,lt).delete(Ee.SCREENSHARE_AUDIO)},o=n(this,q).createProducer(i,a);L(this,Ui,Xa).call(this,Ee.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ge.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=n(this,q).createProducer(d,l),L(this,Ui,Xa).call(this,Ee.SCREENSHARE_AUDIO,c.then(u=>u.id))}await Promise.all([o,c||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new yt("track undefined");const e=L(this,ut,_t).call(this,Ee.MIC);if(e){const o=await e;if(n(this,q).producers.has(o)){const c=n(this,q).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),n(this,Tt)&&(n(this,Tt).audioTrack=t,n(this,Tt).producerId=o,n(this,Tt).start());return}await n(this,q).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=L(this,nl,zf).call(this,t),i=()=>{n(this,lt).delete(Ee.MIC)},a=n(this,q).createProducer(r,i);L(this,Ui,Xa).call(this,Ee.MIC,a.then(o=>o.id)),await a.then(o=>{n(this,Tt)&&(n(this,Tt).audioTrack=o.track,n(this,Tt).producerId=o.id,n(this,Tt).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await L(this,ut,_t).call(this,Ee.MIC),e=n(this,q).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=n(this,Tt))==null||i.stop();const r={producerId:e.id,pause:!0};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(r))}async pauseWebcam(){const t=await L(this,ut,_t).call(this,Ee.WEBCAM),e=n(this,q).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(r))}async resumeMic(){const t=await L(this,ut,_t).call(this,Ee.MIC),e=n(this,q).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(r))}async resumeWebcam(t=Ee.WEBCAM){const e=await L(this,ut,_t).call(this,t),r=n(this,q).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(i))}async disableWebcam(){const t=Ee.WEBCAM,e=await L(this,ut,_t).call(this,t);L(this,il,Kf).call(this,t),e&&await n(this,q).closeProducer(e)}async disableMic(){var e;const t=await L(this,ut,_t).call(this,Ee.MIC);t&&await n(this,q).closeProducer(t),(e=n(this,Tt))==null||e.stop(),n(this,lt).delete(Ee.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await L(this,ut,_t).call(this,Ee.SCREENSHARE_VIDEO),e=await L(this,ut,_t).call(this,Ee.SCREENSHARE_AUDIO);t&&await n(this,q).closeProducer(t),e&&await n(this,q).closeProducer(e),n(this,Xs).clear(),n(this,lt).delete(Ee.SCREENSHARE_VIDEO),n(this,lt).delete(Ee.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await L(this,ut,_t).call(this,Ee.WEBCAM);await n(this,q).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await L(this,ut,_t).call(this,Ee.SCREENSHARE_VIDEO);await n(this,q).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await n(this,q).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};n(this,q).socketHandler.kickPeer(e)}kickAll(){n(this,q).socketHandler.kickAll()}async muteAll(t){if(!await n(this,q).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,q).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await n(this,q).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await n(this,q).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await n(this,tt).sendMessagePromise(n(this,dt).globalPinPeer,Nw.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&n(this,q).producers.get(t.producerId)&&n(this,Xs).add(t.consumerPeerId),n(this,Xs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));n(this,q).switchConsumersToLayer(r,e)}async handleSocketEvents(){n(this,tt).on(n(this,dt).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=UC.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===ir.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(w.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===ir.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),n(this,tt).on(n(this,dt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:a,producerId:o,screenShare:c}}=Tp.fromBinary(t);if(c)return;const d=i===ir.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${a} payload: ${JSON.stringify(Tp.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&a&&this.context.getValue("peerSessionStore").emit(d==="audio"?w.MUTE_SELF:w.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(w.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:a,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&a||u.paused!==a&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${a}`),a?(u.pause(),this.context.getValue("peerSessionStore").emit(w.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(w.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),n(this,tt).on(n(this,dt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=ru.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),n(this,Xs).delete(e),n(this,q).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(w.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),n(this,tt).on(n(this,dt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=HC.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=n(this,q).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),n(this,q).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),n(this,q).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(w.CONSUMER_CLOSED,{id:i})}).catch(a=>{this.logger.error("error closing consumer",{error:a})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),n(this,tt).on(n(this,dt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,Li)&&!n(this,Vi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_DISCONNECTED),n(this,cc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=n(this,q).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(n(this,q).producers.values()).find(a=>a.id===r);i&&this.context.getValue("peerSessionStore").emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}ac=new WeakMap,oc=new WeakMap,tt=new WeakMap,q=new WeakMap,Xd=new WeakMap,dt=new WeakMap,Li=new WeakMap,Vi=new WeakMap,xi=new WeakMap,cc=new WeakMap,zt=new WeakMap,Xs=new WeakMap,lt=new WeakMap,Tt=new WeakMap,xr=new WeakSet,nn=function(){return this.context.getValue("connectionHandler")},Zd=new WeakSet,qf=async function(t,e,r,i){m(this,oc,t);try{n(this,zt)?await n(this,zt):await L(this,dc,Du).call(this,t,e,r,i),L(this,tl,Gf).call(this,e);const{joined:a,error:o}=await L(this,el,jf).call(this);return{roomJoined:a,error:o}}catch(a){return this.logger.error("Failed to complete room join",{error:a}),{roomJoined:!1,error:a}}finally{m(this,zt,null)}},el=new WeakSet,jf=async function(){try{this.mediaJoined=!0;const{roomState:t}=await n(this,q).socketHandler.notifySelfJoinComplete();return m(this,ac,t.roomUuid),m(this,Vi,!0),m(this,Li,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},tl=new WeakSet,Gf=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...ge.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},dc=new WeakSet,Du=async function(t,e,r,i){try{const a=L(this,sl,Wf).call(this);await L(this,rl,Jf).call(this,t,e,r,a),await n(this,q).setupTransports({send:!0,recv:!0})}catch(a){throw this.logger.error("Failed to initialize connection",{error:a}),a}},sl=new WeakSet,Wf=function(){const t=W0("video/VP8");return m(this,Xd,t),t},rl=new WeakSet,Jf=async function(t,e,r,i){await Pf(async(a,o)=>{if(!n(this,tt).isConnected){o(new Error("Socket is not connected"));return}a>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${a}`});try{await n(this,q).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},ut=new WeakSet,_t=function(t){return n(this,lt).get(t)},Ui=new WeakSet,Xa=function(t,e){return n(this,lt).set(t,e)},il=new WeakSet,Kf=function(t){return n(this,lt).delete(t)},nl=new WeakSet,zf=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},al=new WeakSet,Yf=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};ne([y.trace("MediaNodeClient.reset")],se.prototype,"reset",1);ne([y.trace("MediaNodeClient.joinRoom")],se.prototype,"joinRoom",1);ne([y.trace("MediaNodeClient.leaveRoom")],se.prototype,"leaveRoom",1);ne([y.trace("MediaNodeClient.activatePeers")],se.prototype,"activatePeers",1);ne([y.trace("MediaNodeClient.createConsumers")],se.prototype,"createConsumers",1);ne([y.trace("MediaNodeClient.closeConsumers")],se.prototype,"closeConsumers",1);ne([y.trace("MediaNodeClient._shareWebcam")],se.prototype,"_shareWebcam",1);ne([y.trace("MediaNodeClient.shareWebcam")],se.prototype,"shareWebcam",1);ne([y.trace("MediaNodeClient.shareScreen")],se.prototype,"shareScreen",1);ne([y.trace("MediaNodeClient.shareMic")],se.prototype,"shareMic",1);ne([y.trace("MediaNodeClient.pauseMic")],se.prototype,"pauseMic",1);ne([y.trace("MediaNodeClient.pauseWebcam")],se.prototype,"pauseWebcam",1);ne([y.trace("MediaNodeClient.resumeMic")],se.prototype,"resumeMic",1);ne([y.trace("MediaNodeClient.resumeWebcam")],se.prototype,"resumeWebcam",1);ne([y.trace("MediaNodeClient.disableWebcam")],se.prototype,"disableWebcam",1);ne([y.trace("MediaNodeClient.disableMic")],se.prototype,"disableMic",1);ne([y.trace("MediaNodeClient.disableScreenShare")],se.prototype,"disableScreenShare",1);ne([y.trace("MediaNodeClient.muteSelf")],se.prototype,"muteSelf",1);ne([y.trace("MediaNodeClient.resetVideoProducers")],se.prototype,"resetVideoProducers",1);ne([y.trace("MediaNodeClient.changeDisplayName")],se.prototype,"changeDisplayName",1);ne([y.trace("MediaNodeClient.kickPeer")],se.prototype,"kick",1);ne([y.trace("MediaNodeClient.kickAllPeers")],se.prototype,"kickAll",1);ne([y.trace("MediaNodeClient.muteAll")],se.prototype,"muteAll",1);ne([y.trace("MediaNodeClient.muteAllVideo")],se.prototype,"muteAllVideo",1);ne([y.trace("MediaNodeClient.disableAudio")],se.prototype,"disableAudio",1);ne([y.trace("MediaNodeClient.disableVideo")],se.prototype,"disableVideo",1);ne([y.trace("MediaNodeClient.pinPeer")],se.prototype,"pinPeer",1);ne([y.trace("MediaNodeClient.validateScreenShare")],se.prototype,"validateScreenShare",1);function Qf(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new se(s,t);return s.setValue("roomNodeClient",r),r}function Xf(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var lD=Object.defineProperty,uD=Object.getOwnPropertyDescriptor,Zi=(s,t,e,r)=>{for(var i=r>1?void 0:r?uD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&lD(t,e,i),i},$i,us,X,St,Ut,hg;const Zf=(hg=class{constructor(s,t,e,r){g(this,St);h(this,"self");h(this,"authToken");g(this,$i,void 0);h(this,"viewType");g(this,us,void 0);g(this,X,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,X,s),this.viewType=r,this.authToken=a,m(this,$i,i),m(this,us,e),this.setupEvents()}get peerId(){return n(this,X).getValue("peerId")}get telemetry(){return n(this,X).getValue("telemetry")}get logger(){return n(this,X).getValue("logger")}get mediaJoined(){return n(this,X).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=ht(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Je.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const p=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),s.getValue("callstats").devices("AUDIO",p==null?void 0:p.filter(f=>f.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",p==null?void 0:p.filter(f=>f.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",p==null?void 0:p.filter(f=>f.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:ge.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:h_(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(f){l.error("Callstats:: initialization failed",{error:f})}},0):l.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new Zf(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===H.Allowed&&r)try{await n(this,St,Ut).shareMic(s),this.self.audioEnabled||n(this,St,Ut).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{await n(this,St,Ut).shareWebcam(t),this.self.videoEnabled||n(this,St,Ut).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&a)try{await((c=n(this,St,Ut))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){n(this,X).getValue("callstats").callEnded(),n(this,St,Ut).reset(),s&&await this.joinRoom(s)}setupEvents(){n(this,X).getValue("peerSessionStore").on(w.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),n(this,X).getValue("peerSessionStore").on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,X).getValue("peerSessionStore").on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,X).getValue("peerSessionStore").on(w.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,X).getValue("peerSessionStore").on(w.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,X).getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&(t=nr.v4()),n(this,$i).updateURL(t),n(this,X).getValue("telemetry").resetPeerId(t),ht().setHeader("tracing-id",t),qr.remapContext(t,n(this,X)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,X).getValue("peerSessionStore").on(w.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,us).on(V.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,us).on(Fc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,X).getValue("peerSessionStore").emit(w.UPDATE_PERMISSIONS,t.patch)})}),n(this,us).on(V.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,us).on(V.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,us).on(V.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,X).getValue("peerSessionStore").onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,X).getValue("peerSessionStore").on(w.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,X).getValue("callstats").audioOff())}),n(this,X).getValue("peerSessionStore").on(w.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,X).getValue("callstats").videoOff())}),n(this,X).getValue("peerSessionStore").onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(w.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await n(this,us).joinRoom(this.self);n(this,us).socket.flush();const e=oh(t.stageType);if(n(this,X).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new C("Check the network and try again.","0002")}try{await this.joinMediaRoom(s),n(this,X).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof Er&&t.message==="ice connection failed"?new C("A firewall or network restriction may be blocking the connection.","0014"):new C("Check the network and try again.","0014")}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=n(this,X).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,X).notify("stageStatus");try{(e=n(this,$i))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}Xf(n(this,X)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,X).getAllValues();try{if(e===rr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}Qf(n(this,X),{socket:n(this,$i),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:p}=(o=await((a=n(this,St,Ut))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw p!=null?p:new Error("Could not connect to media server");i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=n(this,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===rr.Webinar)&&n(this,St,Ut)&&(n(this,St,Ut).mediaJoined&&s!=="disconnected"&&await n(this,St,Ut).leaveRoom(),!(s==="stageLeft"&&t===rr.Livestream)&&(n(this,St,Ut).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},$i=new WeakMap,us=new WeakMap,X=new WeakMap,St=new WeakSet,Ut=function(){return n(this,X).getValue("roomNodeClient")},hg);let zr=Zf;Zi([y.trace("SelfController.resetSelf")],zr.prototype,"resetSelf",1);Zi([y.trace("SelfController.setupEvents")],zr.prototype,"setupEvents",1);Zi([y.trace("SelfController.joinRoom")],zr.prototype,"joinRoom",1);Zi([y.trace("SelfController.leaveRoom")],zr.prototype,"leaveRoom",1);Zi([y.trace("SelfController.joinMediaRoom")],zr.prototype,"joinMediaRoom",1);Zi([y.trace("SelfController.leaveMediaRoom")],zr.prototype,"leaveMediaRoom",1);Zi([y.trace("SelfController.init")],zr,"init",1);var lc;class hD{constructor(t){g(this,lc,void 0);m(this,lc,t)}on(t,e){let r;t===V.roomPeerCount?r=yp.fromBinary.bind(yp):r=Ap.fromBinary.bind(Ap),n(this,lc).on(t,({payload:i})=>{if(t===V.roomPeerCount&&!i)return;const a=r(i);e(a)})}}lc=new WeakMap;var uc,hc;class pD{constructor(t,e){g(this,uc,void 0);g(this,hc,void 0);m(this,uc,e),m(this,hc,t)}get logger(){return n(this,hc).getValue("logger")}on(t,e){let r,i;switch(t){case V.transcript:{r=Ul.fromBinary.bind(Ul),i=Ul.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,uc).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}uc=new WeakMap,hc=new WeakMap;var gD=Object.defineProperty,mD=Object.getOwnPropertyDescriptor,vh=(s,t,e,r)=>{for(var i=r>1?void 0:r?mD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&gD(t,e,i),i},Zs,fa;class Cl{constructor(t,e){g(this,Zs,void 0);g(this,fa,void 0);m(this,Zs,e),m(this,fa,t)}get logger(){return n(this,fa).getValue("logger")}get telemetry(){return n(this,fa).getValue("telemetry")}getPolls(){return n(this,Zs).sendMessagePromise(Ns.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,Zs).sendMessage(Ns.createPoll,_I.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,Zs).sendMessage(Ns.votePoll,CI.toBinary(r))}on(t,e){let r,i;switch(t){case Ns.updatePoll:case Ns.createPoll:case Ns.votePoll:{r=jl.fromBinary.bind(jl),i=jl.create();break}}n(this,Zs).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){n(this,Zs).removeListeners(t)}}Zs=new WeakMap,fa=new WeakMap;vh([y.trace("PollSocketHandler.getPolls")],Cl.prototype,"getPolls",1);vh([y.trace("PollSocketHandler.createPoll")],Cl.prototype,"createPoll",1);vh([y.trace("PollSocketHandler.votePoll")],Cl.prototype,"votePoll",1);var fD=Object.defineProperty,TD=Object.getOwnPropertyDescriptor,SD=(s,t,e,r)=>{for(var i=r>1?void 0:r?TD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&fD(t,e,i),i},At;class eT{constructor(t,e){h(this,"socket");g(this,At,void 0);m(this,At,t),this.socket=e,this.handleSocketEvents(),n(this,At).setValue("roomSocketHandler",this)}get telemetry(){return n(this,At).getValue("telemetry")}get logger(){return n(this,At).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(V.joinRoom,fR.toBinary(e));try{const{peer:a}=tn.fromBinary((await r).payload);n(this,At).getValue("connectionHandler").socketJoined=!0,n(this,At).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return n(this,At).getValue("peerSessionStore").emit(w.ROOM_STATE,d),n(this,At).getValue("peerSessionStore").emit(w.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),a}}async getAllAddedParticipants(){try{return ek.fromBinary((await this.socket.sendMessagePromise(V.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const a={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(V.getRoomPeersInfo,aR.toBinary(a));i=$l.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(V.getRoomPeersInfo);t=$l.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(V.getRoomPeersInfo);t=$l.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(V.getPeerInfo,Hm.toBinary({peerId:t}));e=tn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Ep.create();try{const e=await this.socket.sendMessagePromise(V.getRoomInfo);t=Ep.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=wp.create();try{const e=await this.socket.sendMessagePromise(V.getRoomStageState);t=wp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(V.broadcastMessage,qa.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(V.broadcastToEntity,qa.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(V.broadcastToEntity,qa.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(V.leaveRoom,SR.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(V.kick,qm.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(V.kickAll,Um.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(V.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(V.acceptWaitingRoomRequests,ak.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(V.denyWaitingRoomRequests,ck.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Fc.updateUserPreset,xk.toBinary(r))}handleSocketEvents(){this.socket.on(V.broadcastMessage,({payload:t})=>{try{const e=qa.fromBinary(t);n(this,At).getValue("peerSessionStore").emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(V.broadcastToEntity,({payload:t})=>{try{const e=qa.fromBinary(t);n(this,At).getValue("peerSessionStore").emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case V.joinRoom:case V.leaveRoom:case V.kick:case V.kickAll:{r=tn.fromBinary.bind(tn),i=tn.create();break}case V.getWaitingRoomRequests:{r=(a,o)=>a?_p.fromBinary(a,o):{requests:[]},i=_p.create();break}case V.recordingPaused:case V.recordingStarted:case V.recordingStopped:{r=Np.fromBinary.bind(Np);break}case Fc.updateUserPreset:{r=Cp.fromBinary.bind(Cp);break}case gs.peerJoinedBroadcast:case yr.peerJoinedBroadcast:{r=mp.fromBinary.bind(mp);break}case gs.selfJoinComplete:case yr.selfJoinComplete:{r=su.fromBinary.bind(su);break}case gs.globalPeerPinBroadcast:case yr.globalPeerPinBroadcast:{r=Sp.fromBinary.bind(Sp);break}case gs.selectedPeer:case yr.selectedPeer:{r=tu.fromBinary.bind(tu);break}case gs.selectedPeerDiff:case yr.selectedPeerDiff:{r=gp.fromBinary.bind(gp);break}case gs.leaveRoom:case yr.leaveRoom:{r=ru.fromBinary.bind(ru);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Fc.getUserPresets,Ik.toBinary(e)),i=Nk.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}At=new WeakMap;SD([y.trace("RoomSocketHandler.joinRoom")],eT.prototype,"joinRoom",1);var vt;class vD{constructor(t){g(this,vt,void 0);m(this,vt,t)}async getStageRequests(){const{payload:t}=await n(this,vt).sendMessagePromise(V.getStageRequests);return t?ql.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,vt).sendMessage(V.requestStageAccess)}cancelRequestAccess(){n(this,vt).sendMessage(V.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,vt).sendMessage(V.grantStageAccess,gI.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,vt).sendMessage(V.denyStageAccess,fI.toBinary(e))}joinStage(){return n(this,vt).sendMessagePromise(V.joinStage,void 0,void 0,V.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,vt).sendMessagePromise(V.leaveStage,Op.toBinary(e),void 0,V.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,vt).sendMessagePromise(V.leaveStage,Op.toBinary(e))}on(t,e){let r;switch(t){case V.grantStageAccess:case V.denyStageAccess:{r=void 0;break}case V.getStagePeers:{r=Dp.fromBinary.bind(Dp);break}case V.getStageRequests:case V.requestStageAccess:case V.cancelStageRequest:{r=ql.fromBinary.bind(ql);break}case V.peerStageStatusUpdate:{r=vp.fromBinary.bind(vp);break}}n(this,vt).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}async getPeerInfo(t){const e=await n(this,vt).sendMessagePromise(V.getPeerInfo,Hm.toBinary({peerId:t}));return tn.fromBinary(e.payload)}}vt=new WeakMap;var Ve,pc;class yD{constructor(t,e){g(this,Ve,void 0);g(this,pc,void 0);m(this,Ve,e),m(this,pc,t)}get logger(){return n(this,pc).getValue("logger")}addPlugin(t,e){n(this,Ve).sendMessage(F.addPlugin,AM.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,Ve).sendMessage(F.removePlugin,OM.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await n(this,Ve).sendMessagePromise(F.getPlugins);return t?sI.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,Ve).sendMessage(F.customPluginEventToRoom,qM.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,Ve).sendMessage(F.customPluginEventToPeers,GM.toBinary(a),i)}enablePluginForRoom(t,e){n(this,Ve).sendMessage(F.enablePluginForRoom,LM.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,Ve).sendMessage(F.enablePluginForPeers,$M.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,Ve).sendMessage(F.disablePluginForRoom,xM.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,Ve).sendMessage(F.disablePluginForPeers,HM.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,Ve).sendMessage(F.storeInsertKeys,Rp.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Ve).sendMessage(F.storeGetKeys,zM.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Ve).sendMessage(F.storeDeleteKeys,QM.toBinary(a),i)}storeDelete(t,e,r){n(this,Ve).sendMessage(F.storeDelete,ZM.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};n(this,Ve).sendMessage(F.storeInsertKeys,Rp.toBinary(i))}on(t,e){let r;switch(t){case F.addPlugin:case F.enablePluginForPeers:case F.enablePluginForRoom:{r=ou.fromBinary.bind(ou);break}case F.removePlugin:case F.disablePluginForPeers:case F.disablePluginForRoom:{r=kp.fromBinary.bind(kp);break}case F.customPluginEventToPeers:case F.customPluginEventToRoom:{r=Ip.fromBinary.bind(Ip);break}case F.storeInsertKeys:case F.storeGetKeys:case F.storeDeleteKeys:case F.storeDelete:{r=Mp.fromBinary.bind(Mp);break}}n(this,Ve).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Ve=new WeakMap,pc=new WeakMap;var ED=Object.defineProperty,PD=(s,t,e)=>t in s?ED(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,bD=(s,t,e)=>(PD(s,typeof t!="symbol"?t+"":t,e),e),yh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},I=(s,t,e)=>(yh(s,t,"read from private field"),e?e.call(s):t.get(s)),ue=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},te=(s,t,e,r)=>(yh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Te=(s,t,e)=>(yh(s,t,"access private method"),e),ld={},_D={get exports(){return ld},set exports(s){ld=s}},fn=typeof Reflect=="object"?Reflect:null,jp=fn&&typeof fn.apply=="function"?fn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},zc;fn&&typeof fn.ownKeys=="function"?zc=fn.ownKeys:Object.getOwnPropertySymbols?zc=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:zc=function(s){return Object.getOwnPropertyNames(s)};function wD(s){console&&console.warn&&console.warn(s)}var tT=Number.isNaN||function(s){return s!==s};function ie(){ie.init.call(this)}_D.exports=ie;ld.once=MD;ie.EventEmitter=ie;ie.prototype._events=void 0;ie.prototype._eventsCount=0;ie.prototype._maxListeners=void 0;var Gp=10;function Rl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ie,"defaultMaxListeners",{enumerable:!0,get:function(){return Gp},set:function(s){if(typeof s!="number"||s<0||tT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Gp=s}});ie.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ie.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||tT(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function sT(s){return s._maxListeners===void 0?ie.defaultMaxListeners:s._maxListeners}ie.prototype.getMaxListeners=function(){return sT(this)};ie.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")jp(c,this,t);else for(var d=c.length,l=oT(c,d),e=0;e<d;++e)jp(l[e],this,t);return!0};function rT(s,t,e,r){var i,a,o;if(Rl(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=sT(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,wD(c)}return s}ie.prototype.addListener=function(s,t){return rT(this,s,t,!1)};ie.prototype.on=ie.prototype.addListener;ie.prototype.prependListener=function(s,t){return rT(this,s,t,!0)};function CD(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function iT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=CD.bind(r);return i.listener=e,r.wrapFn=i,i}ie.prototype.once=function(s,t){return Rl(t),this.on(s,iT(this,s,t)),this};ie.prototype.prependOnceListener=function(s,t){return Rl(t),this.prependListener(s,iT(this,s,t)),this};ie.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Rl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():RD(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ie.prototype.off=ie.prototype.removeListener;ie.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function nT(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?kD(i):oT(i,i.length)}ie.prototype.listeners=function(s){return nT(this,s,!0)};ie.prototype.rawListeners=function(s){return nT(this,s,!1)};ie.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):aT.call(s,t)};ie.prototype.listenerCount=aT;function aT(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ie.prototype.eventNames=function(){return this._eventsCount>0?zc(this._events):[]};function oT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function RD(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function kD(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function MD(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}cT(s,t,a,{once:!0}),t!=="error"&&ID(s,i,{once:!0})})}function ID(s,t,e){typeof s.on=="function"&&cT(s,"error",t,e)}function cT(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class AD extends S.MessageType{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const Wp=new AD;class dT{static encode(t){return Wp.toBinary(t)}static decode(t){return Wp.fromBinary(new Uint8Array(t))}}function DD(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Sr;class OD{constructor(t={}){bD(this,"opts"),ue(this,Sr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},te(this,Sr,0)}async wait(){te(this,Sr,I(this,Sr)+1);const t=DD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**I(this,Sr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return I(this,Sr)}reset(){te(this,Sr,0)}}Sr=new WeakMap;const gr={debug:0,info:1,warn:2,error:3};var ei,ti;class ND{constructor(t){ue(this,ei,void 0),ue(this,ti,void 0),te(this,ei,console),te(this,ti,t)}debug(...t){gr[I(this,ti)]>gr.debug||I(this,ei).debug("[Sockrates]:",...t)}info(...t){gr[I(this,ti)]>gr.info||I(this,ei).info("[Sockrates]:",...t)}warn(...t){gr[I(this,ti)]>gr.warn||I(this,ei).warn("[Sockrates]:",...t)}error(...t){gr[I(this,ti)]>gr.error||I(this,ei).error("[Sockrates]:",...t)}}ei=new WeakMap,ti=new WeakMap;var lT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(lT||{});const LD="2",VD="3";var we,an,fe,Ae,vr,We,tr,Hr,ps,on,Os,Ou,uT,Za,Yc,Nu,hT,Lu,Jp,ud,Vu,xu,pT,ro,Qc,io,hd,pd,Uu,Tn,no,ao,gd;class xD{constructor(t,e){var f,T,E,b,_,k,A,x,N,$;ue(this,Ou),ue(this,Za),ue(this,Nu),ue(this,Lu),ue(this,ud),ue(this,xu),ue(this,ro),ue(this,io),ue(this,pd),ue(this,Tn),ue(this,ao),ue(this,we,void 0),ue(this,an,void 0),ue(this,fe,void 0),ue(this,Ae,void 0),ue(this,vr,void 0),ue(this,We,void 0),ue(this,tr,void 0),ue(this,Hr,void 0),ue(this,ps,void 0),ue(this,on,void 0),ue(this,Os,void 0);var r,i,a,o,c,d,l,u,p;te(this,an,t),te(this,vr,[]),te(this,We,new ld),te(this,tr,!0),te(this,ps,!1),te(this,fe,e!=null?e:{}),(f=(r=I(this,fe)).autoReconnect)!=null||(r.autoReconnect=!0),(T=(i=I(this,fe)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(a=I(this,fe)).pingTimeout)!=null||(a.pingTimeout=3e4),(b=(o=I(this,fe)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(_=(c=I(this,fe)).debug)!=null||(c.debug=!0),(k=(d=I(this,fe)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(A=(l=I(this,fe)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(x=(u=I(this,fe)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(N=(p=I(this,fe)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),te(this,Hr,{code:void 0,reason:void 0}),te(this,Ae,($=I(this,fe).logger)!=null?$:new ND(I(this,fe).debug?"debug":"info")),te(this,Os,new OD)}get readyState(){var t;return(t=I(this,we))==null?void 0:t.readyState}get url(){return I(this,an)}updateURL(t){te(this,an,t),Te(this,xu,pT).call(this)}get config(){return I(this,fe)}get sendQueue(){return I(this,vr)}flush(){if(!I(this,fe).queueOnDisconnect)return!1;const t=[];return I(this,vr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),te(this,vr,t),I(this,vr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){I(this,Ae).debug("Websocket was already connecting or connected.");return}if(I(this,tr)!==!1)return new Promise((e,r)=>{Te(this,Tn,no).call(this),Te(this,ao,gd).call(this);try{te(this,we,new WebSocket(Te(this,Ou,uT).call(this,I(this,an)))),I(this,we).binaryType="arraybuffer",I(this,Ae).debug("Connecting");const i=setTimeout(()=>{I(this,Ae).debug("Connection timeout. Closing socket"),te(this,tr,!0),Te(this,ao,gd).call(this),I(this,we).close(3001,"Connection Timeout"),I(this,fe).autoReconnect&&!I(this,ps)&&(I(this,We).emit("reconnecting"),Te(this,ro,Qc).call(this)),r(new Error("Connection timed out!"))},I(this,fe).connectionTimeout);I(this,we).onopen=()=>{I(this,Ae).debug(`Ready State: ${lT[I(this,we).readyState]}`),i&&clearTimeout(i),Te(this,pd,Uu).call(this),te(this,Hr,{code:void 0,reason:void 0}),I(this,We).emit("connected"),I(this,fe).flushOnReconnect&&this.flush(),e()},I(this,we).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),I(this,Ae).debug("Socket closed. Close event:",{event:a}),I(this,Ae).debug(`Connection closed code: ${o}`),I(this,Ae).debug(`Connection closed reason: ${c}`),I(this,ps)||Te(this,ud,Vu).call(this,o,c)}catch(o){Te(this,Za,Yc).call(this,o)}},I(this,we).onerror=a=>{Te(this,Za,Yc).call(this,a)},I(this,we).onmessage=a=>Te(this,Nu,hT).call(this,a)}catch(i){Te(this,Za,Yc).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(I(this,fe).queueOnDisconnect&&(!I(this,we)||I(this,we).readyState!==1))return I(this,Ae).debug("Queuing message since socket is not connected!",a),I(this,vr).push(a),!1;const o=dT.encode(a);return Te(this,io,hd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Te(this,io,hd).call(this,t)}receive(t,e){return I(this,We).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){I(this,We).on(t,e);return}this.receive(t,e)}removeAllListeners(){I(this,We).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){I(this,We).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){I(this,We).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){te(this,tr,!1),Te(this,Tn,no).call(this),this.removeAllListeners(),te(this,Hr,{code:1e3,reason:"Sockrates disconnect method called"}),I(this,we).close(1e3,"Sockrates disconnect method called.")}}we=new WeakMap,an=new WeakMap,fe=new WeakMap,Ae=new WeakMap,vr=new WeakMap,We=new WeakMap,tr=new WeakMap,Hr=new WeakMap,ps=new WeakMap,on=new WeakMap,Os=new WeakMap,Ou=new WeakSet,uT=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Za=new WeakSet,Yc=function(s,t){I(this,Ae).error("Error:",{error:s}),I(this,We).emit("errored",{error:s}),t==null||t(s)},Nu=new WeakSet,hT=function(s){if(Te(this,pd,Uu).call(this),s.data===LD){I(this,Ae).debug("Received ping from server"),Te(this,io,hd).call(this,VD);return}const t=dT.decode(s.data),{id:e,payload:r}=t;I(this,Ae).debug("Received message",{event:t.event,messageID:e}),I(this,We).emit(t.event.toString(),{id:e,payload:r})},Lu=new WeakSet,Jp=function(){return I(this,we).readyState===1},ud=new WeakSet,Vu=function(s,t){te(this,Hr,{reason:t,code:s}),I(this,We).emit("disconnected",{code:s,reason:t})},xu=new WeakSet,pT=function(){const{reason:s,code:t}=I(this,Hr);t&&t!==1e3&&I(this,tr)&&I(this,fe).autoReconnect&&!I(this,ps)&&(I(this,Ae).debug(`Triggering reconnection due to ${s}.`),I(this,We).emit("reconnecting"),Te(this,ro,Qc).call(this))},ro=new WeakSet,Qc=async function(s=!0){if(s&&I(this,ps)){I(this,Ae).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(I(this,ps)||I(this,Os).reset(),I(this,fe).maxReconnectionAttempts!==null&&I(this,Os).getAttempts()>=I(this,fe).maxReconnectionAttempts){I(this,We).emit("failed"),te(this,ps,!1);return}te(this,ps,!0),Te(this,ao,gd).call(this),Te(this,Tn,no).call(this);try{if(await I(this,Os).wait(),I(this,tr)===!1)return;if(I(this,Ae).debug(`Reconnection attempt ${I(this,Os).getAttempts()}`),I(this,We).emit("reconnectAttempt",{attempt:I(this,Os).getAttempts()}),await this.connect(),!Te(this,Lu,Jp).call(this))throw Error("Reconnect Failed");te(this,ps,!1),te(this,Hr,{code:void 0,reason:void 0}),I(this,We).emit("reconnected")}catch(t){I(this,Ae).debug("Failed to reconnect."),I(this,We).emit("reconnectFailure",{attempt:I(this,Os).getAttempts()}),Te(this,ro,Qc).call(this,!1)}},io=new WeakSet,hd=function(s){try{return I(this,we).send(s),!0}catch(t){return I(this,Ae).error(t.message),!1}},pd=new WeakSet,Uu=function(){this.config.disconnectOnPingTimeout&&(I(this,Ae).debug("Resetting ping timeout"),Te(this,Tn,no).call(this),te(this,on,setTimeout(()=>{var s;I(this,Ae).debug("Disconnecting the socket due to ping timeout"),te(this,tr,!0);const t=3002,e="Ping timeout";(s=I(this,we))==null||s.close(t,e),Te(this,ud,Vu).call(this,t,e)},I(this,fe).pingTimeout)))},Tn=new WeakSet,no=function(){I(this,on)&&(clearTimeout(I(this,on)),te(this,on,void 0))},ao=new WeakSet,gd=function(){I(this,we)&&(I(this,we).onopen=void 0,I(this,we).onerror=void 0,I(this,we).onmessage=void 0,I(this,we).onclose=void 0)};var UD=Object.defineProperty,$D=Object.getOwnPropertyDescriptor,kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?$D(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&UD(t,e,i),i};const Kp=65535,BD=3e3;var Ur,ve,ye,Re,Yt,Ge,gc,$u,mc,Bu,pg;const gT=(pg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,ye);g(this,gc);g(this,mc);g(this,Ur,void 0);g(this,ve,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");g(this,Yt,void 0);g(this,Ge,void 0);var a;if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");m(this,Yt,void 0),m(this,Ge,s),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,Ur,L(this,gc,$u).call(this,t)),m(this,ve,new xD(n(this,Ur),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,ye,Re).socketJoinAttempted}set joinAttempted(s){n(this,ye,Re).socketJoinAttempted=s}get telemetry(){return n(this,Ge).getValue("telemetry")}get logger(){return n(this,Ge).getValue("logger")}get peerId(){return n(this,Ge).getValue("peerId")}updateURL(s){s!==this.peerId&&(m(this,Ur,L(this,gc,$u).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,ve).updateURL(n(this,Ur))}static getSocketEdgeDomain(s){return gn({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,Ur)}async connect(){n(this,ye,Re).socketJoinAttempted=!0,await n(this,ve).connect(),n(this,ye,Re).socketJoinAttempted=!0,n(this,ye,Re).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){n(this,ye,Re).socketJoinAttempted=!1,n(this,ve).disconnect(),n(this,ye,Re).socketJoinAttempted=!0,n(this,ye,Re).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,ve).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return n(this,Ge).getValue("telemetry").injectContext(r),n(this,ve).send(s,e!=null?e:L(this,mc,Bu).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const a=i!=null?i:s;return new Promise((o,c)=>{const d=(E,b)=>{n(this,ve).removeListener(a,E),n(this,ve).removeListener(Kp,b),n(this,ve).removeListener(yr.errorResponse,b),n(this,ve).removeListener(gs.errorResponse,b)},l=r!=null?r:L(this,mc,Bu).call(this),u={};n(this,Ge).getValue("telemetry").injectContext(u);const f=({id:E,payload:b})=>{if(l===E){let _;try{const k=Xw.fromBinary(b);_=new Error(k.errorMessage)}catch(k){_=new Error("failed to parse error message",{cause:k});try{const A=ZC.fromBinary(b);_=new Error(A.message)}catch(A){_=new Error("failed to parse error message",{cause:A})}}c(_),d(T,f)}},T=({id:E,payload:b})=>{l===E&&(o({id:E,payload:b}),d(T,f))};n(this,ve).on(a,T),n(this,ve).on(Kp,f),n(this,ve).on(yr.errorResponse,f),n(this,ve).on(gs.errorResponse,f),setTimeout(()=>{d(T,f),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,ve).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){n(this,ve).on(s,t)}onStateEvent(s,t){n(this,ve).on(s,t)}removeListener(s,t){n(this,ve).removeListener(s,t)}removeListeners(s){n(this,ve).removeListeners(s)}flush(){return n(this,ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),n(this,Yt)&&(clearTimeout(n(this,Yt)),m(this,Yt,void 0)),n(this,ye,Re).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{recv:e,send:r}=(i=n(this,ye,Re).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==mn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==mn.CONNECTED?n(this,Ge).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,ye,Re).joinAttempted}):m(this,Yt,setTimeout(()=>{n(this,Ge).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,ye,Re).joinAttempted}),m(this,Yt,void 0)},BD)),n(this,ye,Re).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),n(this,ye,Re).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),n(this,ye,Re).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,ye,Re).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,ye,Re).mediaJoinAttempted}}),n(this,Yt)&&(clearTimeout(n(this,Yt)),m(this,Yt,void 0)),n(this,Ge).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,ye,Re).mediaJoinAttempted}),n(this,ye,Re).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),n(this,Ge).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_FAILED),n(this,ye,Re).updateSocketConnectionState("failed")})}},Ur=new WeakMap,ve=new WeakMap,ye=new WeakSet,Re=function(){return n(this,Ge).getValue("connectionHandler")},Yt=new WeakMap,Ge=new WeakMap,gc=new WeakSet,$u=function(s){const t=n(this,Ge).getValue("socketBaseURI")||n(this,Ge).getValue("baseURI");let e=gT.getSocketEdgeDomain(t);typeof ya(n(this,Ge),"socket_server_base")=="string"&&(e=ya(n(this,Ge),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),a=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...a!==s&&{oldPeerID:a},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>id[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},mc=new WeakSet,Bu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},pg);let Rc=gT;kl([y.trace("SocketService.connect")],Rc.prototype,"connect",1);kl([y.trace("SocketService.disconnect")],Rc.prototype,"disconnect",1);kl([y.trace("SocketService.sendMessagePromise")],Rc.prototype,"sendMessagePromise",1);kl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Rc.prototype,"sendMessagePromiseWithTimeout",1);class HD{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=CR.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(a=e.parentMeeting.participants)!=null?a:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=XR.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Fm.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return bp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return FR.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(V.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(V.createConnectedRooms,IR.toBinary({payloads:t}));return bp.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(V.deleteConnectedRooms,BR.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(V.movePeers,KR.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}}}var FD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,jD=(s,t,e,r)=>{for(var i=r>1?void 0:r?qD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FD(t,e,i),i},hs;class mT extends Lt{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);g(this,hs,void 0);m(this,hs,e)}get supportsConnectedMeetings(){return n(this,hs).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
10
|
+
Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await n(this,hs).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await n(this,hs).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await n(this,hs).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await n(this,hs).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,hs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,hs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),a}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>a.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}hs=new WeakMap;jD([Et({maxInvocations:60,period:60})],mT.prototype,"getConnectedMeetings",1);var GD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,Eh=(s,t,e,r)=>{for(var i=r>1?void 0:r?WD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&GD(t,e,i),i},ce,gg;const fT=(gg=class{constructor(s){h(this,"connectedMeetings");g(this,ce,void 0);m(this,ce,s),this.connectedMeetings=new mT(s)}get telemetry(){return n(this,ce).getValue("telemetry")}get logger(){return n(this,ce).getValue("logger")}static init(s){const t=new fT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ce).getValue("connectedMeetingsSocketHandler").socketService.on(V.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ce).getValue("connectedMeetingsSocketHandler").socketService.on(V.transferPeer,this.handleTransferPeer.bind(this)),n(this,ce).getValue("connectedMeetingsSocketHandler").socketService.on(V.movedPeer,this.handleMovedPeer.bind(this)),n(this,ce).getValue("connectedMeetingsSocketHandler").socketService.on(V.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ce).getValue("connectedMeetingsSocketHandler").socketService.on(V.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,ce).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
11
|
+
Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:n(this,ce).getValue("self").videoEnabled,audio:n(this,ce).getValue("self").audioEnabled};try{n(this,ce).getValue("self").cleanupEvents(),await n(this,ce).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,ce).getValue("meeting"))==null?void 0:i.meta)==null?void 0:a.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await ST.init({...n(this,ce).getValue("options"),cachedUserDetails:null,defaults:{...n(this,ce).getValue("options").defaults,...e,mediaHandler:n(this,ce).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=n(this,ce).getValue("self");r.self.setName(n(this,ce).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=n(this,ce).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return n(this,ce).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,ce).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,ce).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},ce=new WeakMap,gg);let Ml=fT;Eh([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Ml.prototype,"getConnectedMeetings",1);Eh([y.trace("ConnectedMeetingsController.setupEvents")],Ml.prototype,"setupEvents",1);Eh([y.trace("ConnectedMeetingsController.switchMeeting")],Ml.prototype,"switchMeeting",1);var JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,Ph=(s,t,e,r)=>{for(var i=r>1?void 0:r?KD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&JD(t,e,i),i};const eo=class{constructor(s,t,e){h(this,"apiBase");h(this,"selfController");h(this,"pollController");h(this,"chatController");h(this,"metaController");h(this,"storesManager");h(this,"stageController");h(this,"pluginController");h(this,"internalsController");h(this,"recordingController");h(this,"livestreamController");h(this,"participantController");h(this,"connectedMeetingsController");h(this,"telemetry");h(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var N,$,K;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(Xf(s),ge.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=tA(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(a),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new VA(s);s.setValue("connectionHandler",l);let u="",p="",f=null;c.info("CF SFU is being used.");try{f=await d.getUserDetails(),u=((N=f.meeting)==null?void 0:N.title)||"",p=(($=f.socket)==null?void 0:$.baseUri)||s.getValue("baseURI"),s.setValue("presetName",f.preset.name),s.setValue("socketBaseURI",p),c.info(`Socket Base URI ${p} is being used`)}catch(Y){throw c.error("Failed to get user details",{error:Y}),Y instanceof du?Y.status===401?new C("Unauthorized. The auth token may be invalid or expired. (401)","0004"):Y.status===403?new C("Access denied. Insufficient permissions to join the meeting. (403)","0004"):Y.status===404?new C("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004"):Y.status>=500?new C(`The server encountered an error. Try again. (${Y.status})`,"0001"):Y.isHttpError?new C(`Request rejected by the server. (${Y.status})`,"0001"):Y.isTimeout?new C("Connection timed out. Check the network and try again.","0001"):new C("Unable to connect to the server. Check the internet connection.","0001"):new C((Y==null?void 0:Y.message)||"Failed to initialize.","0001")}const T=eo.createSocketService(s),E=T.connect(),b=d.getPlugins();try{await E}catch(Y){c.error("[Controller]: Failed to connect to socket server:",{error:Y})}const _=Tu.init(f.preset,!s.getValue("modules").theme);s.setValue("theme",_);const k=Eu.init(s,_.viewType,f.preset.permissions),A=eo.setupControllers(T,s,f,b,u,_,k);wA(_)&&((K=eo.createRoomNodeClient(s,T).initializeConnection(f.participant.name,i,!1,k))==null||K.catch(Ue=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Ue})}));const{controllers:x}=await A;return O_(),new eo(e,x,s)}static async setupControllers(s,t,e,r,i,a,o){var O,R,De;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:p,mediaConstraints:{audio:f}}=a;t.setValue("viewType",p),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(O=f.enableHighBitrate)!=null?O:!1,enableStereo:(R=f.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",ge.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let T,E,b,_,k,A,x,N,$;const K=new pD(t,s),Y=new HD(s);t.setValue("connectedMeetingsSocketHandler",Y);const Ue=new Cl(t,s),es=new ur(t,s),Yr=new vD(s),ts=new eT(t,s),M=new yD(t,s),v=new hD(s),P=await zr.init(t,ts,d,o,a);t.setValue("selfController",P);const U=await rf.init(t,P.self,ts,K,i);if(c.participant&&(N=new pr(t,P.self,ts)),(De=c.e2ee)!=null&&De.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(E=await Xt.init(t,es,P.self,N.participants)),c.internals&&(k=await dh.init(t)),c.livestream&&a.viewType===rr.Livestream&&(x=new pf(t,P.self,v)),c.poll&&(T=await Zm.init(t,P.self,Ue)),c.recording&&(A=new cf(t,P.self,ts)),c.stage&&(b=new nf(t,Yr,ts,P.self,N.participants)),c.plugin){if(!N)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Ds=await r;_=await bc.init(t,Ds,M,es,E==null?void 0:E.chat,P.self,N.participants,i)}if(c.connectedMeetings&&($=await Ml.init(t)),c.pip){const Ds=await eu._init(t,P.self);t.setValue("pip",Ds)}const Ce={storesManager:new k0(t,M),pollController:T,selfController:P,metaController:U,chatController:E,stageController:b,pluginController:_,recordingController:A,internalsController:k,livestreamController:x,participantController:N,connectedMeetingsController:$};return{theme:a,permissions:o,controllers:Ce}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return Qf(s,{socket:t,peerId:e})}static createSocketService(s){var d;const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),o=((d=s.getValue("socketBaseURI"))!=null?d:"").includes("realtime.cloudflare.com")?[]:["PING"];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(o)}`),new Rc(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let Il=eo;Ph([y.trace("Controller.init")],Il,"init",1);Ph([y.trace("Controller.createRoomNodeClient")],Il,"createRoomNodeClient",1);Ph([y.trace("Controller.createSocketService")],Il,"createSocketService",1);class zD{constructor(){h(this,"battery");h(this,"logger");h(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});h(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});h(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});h(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const zp=new zD;function YD(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let a=ri.baseURI.prod;t&&(a=t);const o=`https://${gn({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}var $r,Bi,Hi,fc,ol,TT;class QD{constructor(){g(this,ol);g(this,$r,new Audio);g(this,Bi,new MediaStream);g(this,Hi,new Map);g(this,fc,void 0);n(this,$r).srcObject=n(this,Bi),n(this,$r).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,Hi).has(e.id)||(n(this,Bi).addTrack(e),n(this,Hi).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,$r).setSinkId(t)}removeTrack(t){const e=n(this,Hi).get(t);e&&(n(this,Bi).removeTrack(e),n(this,Hi).delete(t))}async play(){return n(this,$r).srcObject=n(this,Bi),n(this,$r).play().catch(t=>{L(this,ol,TT).call(this,t)})}onError(t){m(this,fc,t)}}$r=new WeakMap,Bi=new WeakMap,Hi=new WeakMap,fc=new WeakMap,ol=new WeakSet,TT=function(t){var e;(e=n(this,fc))==null||e.call(this,t)};var Fi;class XD extends QD{constructor(){super();g(this,Fi,void 0);m(this,Fi,new Map)}addParticipantTrack(e,r){n(this,Fi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,Fi).get(e);r&&this.removeTrack(r),n(this,Fi).delete(e)}}Fi=new WeakMap;var ZD=Object.defineProperty,e1=Object.getOwnPropertyDescriptor,Al=(s,t,e,r)=>{for(var i=r>1?void 0:r?e1(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZD(t,e,i),i},xe,qi,mg;let Gr=(mg=class{constructor(t,e){g(this,xe,void 0);g(this,qi,void 0);m(this,qi,t),m(this,xe,e)}get peerId(){return n(this,qi).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:nr.v4(),a=qr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new Ef(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,T,E,b,_,k,A,x,N;ge.init();const e=(T=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?T:nr.v4(),{authToken:r,baseURI:i}=t,{meetingId:a,...o}=YD(r,i);if((E=o.baseURI)!=null&&E.includes("dyte.io"))throw new C("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Gr.setupContext(e,t,a,o),d=c.getValue("telemetry"),l=c.getValue("logger");wT(l),zp.init(l),d.init(c,{roomName:a,userId:o.participantId,organizationId:o.orgId,peerId:e},(_=(b=t.modules)==null?void 0:b.tracing)!=null?_:!0,(A=(k=t==null?void 0:t.modules)==null?void 0:k.devTools)==null?void 0:A.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(x=t.authToken)==null?void 0:x.slice(0,10)}...
|
|
12
|
+
${(N=t.authToken)==null?void 0:N.slice(-10)}`}});const u=await Il.init(c),p=new Gr(c,u);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const a=qr.createContext(t,e),o={...l_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",u_({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",ks(e.cachedUserDetails)),a.setValue("sdkVersion","1.5.0-staging.4"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new XD),a}async join(){const{selfController:t}=n(this,xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){zp.cleanup(),n(this,qi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,xe);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,xe).stageController)==null?void 0:t.stage}get stores(){return n(this,xe).storesManager}get audio(){return n(this,qi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},xe=new WeakMap,qi=new WeakMap,mg);Al([rt("0002"),hr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Gr.prototype,"join",1);Al([rt("0003")],Gr.prototype,"leave",1);Al([rt("0001"),hr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Gr,"init",1);Gr=Al([rt("0000")],Gr);const ST=Gr;module.exports=ST;
|